Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am new with Linq and I would like to sort some data that are in the BindingList. Once I did my Linq query, I need to use back the BindingList collection to bind my data. ``` var orderedList = //Here is linq query return (BindingList<MyObject>)orderedList; ``` This compiled but fails in execution, what is the trick?
``` new BindingList<MyObject>(orderedList.ToList()) ```
You can't always cast any collection type into any other collection. In terms of when the the compiler checks casting, check out this post on [Compile-time vs runtime casting](https://stackoverflow.com/a/4499558/1366033) However, you can easily produce a `BindingList` from an enumerable by doing some of the plumbing yourself. Just add the following Extension Method onto any Enumerable type to convert the collection into a BindingList. **C#**: ``` static class ExtensionMethods { public static BindingList<T> ToBindingList<T>(this IEnumerable<T> range) { return new BindingList<T>(range.ToList()); } } //use like this: var newBindingList = (from i in new[]{1,2,3,4} select i).ToBindingList(); ``` **VB**: ``` Module ExtensionMethods <Extension()> _ Public Function ToBindingList(Of T)(ByVal range As IEnumerable(Of T)) As BindingList(Of T) Return New BindingList(Of T)(range.ToList()) End Function End Module 'use like this: Dim newBindingList = (From i In {1, 2, 3, 4}).ToBindingList() ```
BindingList and LINQ?
[ "", "c#", ".net", "linq", ".net-3.5", "c#-3.0", "" ]
I am developing an .net application which heavely depends on plugins. The application itself contains an connection to a remote server. Recently I digged into Application domains and see them as the ideal solution for isolating the plugin code from the rest of the application. However there is one big disadvantage which makes me unable to implement the application domains for hosting the plugins. It seems there is no way to pass an object by reference to another application domain which is needed to pass an reference to the connection object. I was hoping someone could give me a workaround so I can pass an reference to that object. Note: Creating a proxy is out of the question, the connection layer already acts as a proxy since the classes are auto generated. Note2: System.AddIn can not be used as it is not available on the compact framework.
Have you tried deriving from [MarshalByRefObject](http://msdn.microsoft.com/en-us/library/system.marshalbyrefobject.aspx)? It's a pain in that it screws up your inheritance hierarchy, but I think it's what you want. From the docs: > MarshalByRefObject is the base class > for objects that communicate across > application domain boundaries by > exchanging messages using a proxy. > Objects that do not inherit from > MarshalByRefObject are implicitly > marshal by value. When a remote > application references a marshal by > value object, a copy of the object is > passed across application domain > boundaries. > > MarshalByRefObject objects are > accessed directly within the > boundaries of the local application > domain. The first time an application > in a remote application domain > accesses a MarshalByRefObject, a proxy > is passed to the remote application. > Subsequent calls on the proxy are > marshaled back to the object residing > in the local application domain. > > Types must inherit from > MarshalByRefObject when the type is > used across application domain > boundaries, and the state of the > object must not be copied because the > members of the object are not usable > outside the application domain where > they were created. In my experience, it can be pretty limiting - you really need to do as little as possible across the AppDomain boundary, preferrably restricting yourself to operations which only require primitive types, strings, and arrays of both. This may well be due to my own inexperience in working with multiple AppDomains, but it's just a warning that it's a bit of a minefield.
Be aware that clean-up of `MarshalByRefObject` proxies are cleaned up based on a lease. In short if you don't use the object for a specific time it will be reclaimed. You can control this by overriding `InitializeLifetimeService` to return a lease object which matches you needs. If you return `null` you effectively disable the leasing and then the object is only reclaimed when the AppDomain is unloaded.
Workaround .net application domain only passing objects by value
[ "", "c#", "appdomain", "marshalbyrefobject", "" ]
If i have a complex object, what is the best practice pattern to write code to compare 2 instances to see if they are the same
Implement the IEquatable interface. This defines a generalized method that a value type or class implements to create a type-specific method for determining equality of instances. Don't forget to override Equals(object) as well. More information here: <http://msdn.microsoft.com/en-us/library/ms131187.aspx>
I think the answer is highly problem dependent. For example, you may want to consider objects equal only if all of their properties are equivalent. This would perhaps be the case where each object doesn't have a uniquely identifying property. If there is such a property (or properties), say an ID or ID and Version, that uniquely identifies each object of the type, then you may only want to compare based on that property (or properties). The base pattern, however, ought to be something like: ``` if their references are equal (includes both null) return true else if one object is null return false else return value based on relevant properties ``` Note that if you override the Equals operator, you'll also want to override GetHashCode() so that the hash codes for equivalent objects are the same. This will ensure that data structures that use the hash code for determining duplicate keys work properly when the object is used as a key.
Comparing two objects .
[ "", "c#", "" ]
I have a Python function in which I am doing some sanitisation of the input parameters: ``` def func(param1, param2, param3): param1 = param1 or '' param2 = param2 or '' param3 = param3 or '' ``` This caters for the arguments being passed as *None* rather than empty strings. Is there an easier/more concise way to loop round the function parameters to apply such an expression to all of them. My actual function has nine parameters.
This looks like a good job for a decorator. How about this: ``` def sanitized(func): def sfunc(*args, **kwds): return func(*[arg or '' for arg in args], **dict((k, v or '') for k,v in kwds.iteritems())) sfunc.func_name = func.func_name sfunc.func_doc = func.func_doc return sfunc ``` You would use this on your function like so: ``` @sanitized def func(param1, param2, param3): print param1, param2, param3 ``` Then the parameters will be replaced by the empty string if they are false: ``` >>> func('foo', None, 'spam') foo spam ``` (Note that this will still mess up the function signature as Ned Batchelder points out in his answer. To fix that you could use [Michele Simionato's decorator module](http://pypi.python.org/pypi/decorator)-- I think you'd just need to add a `@decorator` before the definition of `sanitized`)
You could do some list manipulation: ``` def func(param1, param2, param3): param1, param2, param3 = map(lambda x: x or '', (param1, param2, param3)) ``` but I'm not sure that's better than just writing out the nine lines, since once you get to nine parameters, that's a heinously long line. You could change the declaration of the function: ``` def func(*args): param1, param2, param3 = map(lambda x: x or '', args) ``` but then you lose the documentation that comes from having real parameter names, as well as the possibility of changing the defaults, etc. And you still have a pretty fugly line there to unpack them. I say write out the nine lines, or change the function to have fewer parameters: nine is kind of a lot anyway!
Loop function parameters for sanity check
[ "", "python", "function", "parameters", "arguments", "sanitization", "" ]
I have a non-visual component which manages other visual controls. I need to have a reference to the form that the component is operating on, but i don't know how to get it. I am unsure of adding a constructor with the parent specified as control, as i want the component to work by just being dropped into the designer. The other thought i had was to have a Property of parent as a control, with the default value as 'Me' any suggestions would be great **Edit:** To clarify, this is a **component**, not a **control**, see here :[ComponentModel.Component](http://msdn.microsoft.com/en-us/library/system.componentmodel.component.aspx)
[It is important to understand that the ISite technique below only works at design time. Because ContainerControl is public and gets assigned a value VisualStudio will write initialization code that sets it at run-time. Site is set at run-time, but you can't get ContainerControl from it] [Here's an article](http://www.wiredprairie.us/journal/2004/05/finding_the_component_containe.html) that describes how to do it for a non-visual component. Basically you need to add a property ContainerControl to your component: ``` public ContainerControl ContainerControl { get { return _containerControl; } set { _containerControl = value; } } private ContainerControl _containerControl = null; ``` and override the Site property: ``` public override ISite Site { get { return base.Site; } set { base.Site = value; if (value == null) { return; } IDesignerHost host = value.GetService( typeof(IDesignerHost)) as IDesignerHost; if (host != null) { IComponent componentHost = host.RootComponent; if (componentHost is ContainerControl) { ContainerControl = componentHost as ContainerControl; } } } } ``` If you do this, the ContainerControl will be initialized to reference the containing form by the designer. The linked article explains it in more detail. A good way to see how to do things is to look at the implementation of Types in the .NET Framework that have behaviour similar to what you want with a tool such as Lutz Reflector. In this case, System.Windows.Forms.ErrorProvider is a good example to look at: a Component that needs to know its containing Form.
I use a recursive call to walk up the control chain. Add this to your control. ``` public Form ParentForm { get { return GetParentForm( this.Parent ); } } private Form GetParentForm( Control parent ) { Form form = parent as Form; if ( form != null ) { return form; } if ( parent != null ) { // Walk up the control hierarchy return GetParentForm( parent.Parent ); } return null; // Control is not on a Form } ``` **Edit:** I see you modified your question as I was typing this. If it is a component, the constructor of that component should take it's parent as a parameter and the parent should pass in this when constructed. Several other components do this such as the timer. Save the parent control as a member and then use it in the ParentForm property I gave you above instead of this.
Get Component's Parent Form
[ "", "c#", "vb.net", "winforms", "components", "" ]
I have been looking for a quadtree/quadtree node implementation on the net for ages. There is some basic stuff but nothing that I would be able to really use it a game. My purpose is to store objects in a game for processing things such as collision detection. I am not 100% certain that a quadtree is the best data structure to use, but from what I have read it is. I have already coded a Red-Black tree, but I don't really know if the performance would be good enough for my game (which will be an adventure 3rd person game like Ankh). How would I write a basic but complete quadtree class (or octree) in C++? How would you use the quad tree for collisions?
Quadtrees are used when you only need to store things that are effectively on a plane. Like units in a classic RTS where they are all on the ground or just a little bit above it. Essentially each node has links to 4 children that divide the node's space up into evenly distributed quarters. Octrees do the same but in all three dimensions rather than just two, and thus they have 8 child nodes and partition the space up into eights. They should be used when the game entities are distributed more evenly among all three dimensions. If you are looking for a binary tree - like a red-black tree - then you want to use a data structure called a binary space partitioning tree (BSP tree) or a version of it called the KD Tree. These partition space into halves using a plane, in the KD tree the planes are orthogonal (on the XZ, XY, ZY axes) so sometimes it works better in a 3D scene. BSP trees divide the scene up using planes in any orientation, but they can be quite useful, and they were used as far back as Doom. Now because you've partitioned the game space you now don't have to test every game entity against every other game entity to see if they collide, which is an O(n^2) algorithm at best. Instead you query the data structure to return the game entities within a sub-region of the game space, and only perform collision detection for those nodes against each other. This means that collision detection for all game entities should be n O(nlogn) operation (at worst). A couple of extra things to watch out for: * Make sure you test game entities from adjacent nodes, not just the ones in the current node, since they could still collide. * Rebalance the data structure after the entities have moved since you may have empty nodes in the data structure now, or ones that contain too many entities for good performance (also the degenerate case of all entities being in the same node).
A red-black tree is not a spatial index; it can only sort on a single ordinal key. A quadtree is (for two dimensions) a spatial index that allows fast lookup and elimination of points. An Octree does the same thing for three dimensions.
Quadtree vs Red-Black tree for a game in C++?
[ "", "c++", "quadtree", "" ]
I'm almost finished with the book "Head First Java". The reason I'm studying this is I'm hoping to get a job developing with JavaEE someday. Now I'm thinking, should I go ahead and study EE (moving on to Head First Servlets and JSP) or should I spend more time with SE? Would it help? I'll go on and say directly that I want to learn EE in the quickest yet the most optimum time needed (a balanced ind of way). Any advice? Thanks in advance!
To me its fine to go with JavaEE, as you already did adequate of SE. And certainly hanging out in programming forums will teach you now and then things which are still hidden from you. Believe me there would be many. Anyhow, I am having few advices for you, which will help you down the road. * Its better to have a very good command on Java Collection API * Another important is to know Java Threading Mechanism and related classes * Effective Java is a must read for any Java developer. So go and read it * Don't jump into any framework prior practicing plain Servlet and JSP, adequately * To know major design patterns is a must
Knowledge is never a bad thing, so more SE is recommended. But there's nothing wrong with getting your feet wet with EE now. Start with servlets, JSPs, and JDBC. You can do lots of useful things with just these, and it's fair to call it EE. If you do write JSPs, just make sure that you do it the right way - using JSTL, the JSP Standard Tag Library. No scriptlet code.
Should I do more JavaSE before jumping to JavaEE?
[ "", "java", "jakarta-ee", "" ]
I am trying to get some `JavaScript` to programmatically adjust a HTML `img` tag's width to display various sized images correctly. I have a fixed width `img` tag at `800px` to display an image, this is the max width. If the image is wider then `800px` I want to display it at `800px` wide; If the image is less than `800px` wide I want to preserve its width to avoid stretching it. I use this html/javacript code to get a partial solution: ``` function resize_image(id) { var img = document.getElementById(id); var normal_width = img.width; img.removeAttribute("width"); var real_width = img.width; if (real_width < normal_width) { img.width = real_width; } else { img.width = normal_width; } } ``` ``` <img id="myimage" onload="resize_image(self.id);" src="https://via.placeholder.com/350x150" width="800" /> ``` The above code seems to work on all browsers I have tested except `Safari` (images don't display unless you refresh the page). I know I can use CSS `max-width` but that wont work on `IE` < 7 which is a show stopper. How can I get this working for all browsers? Many thanks in advance.
I have never seen a safari in work, but you can try changing your onload event to this: ``` onload="resize_image(self.id);return true" ``` It could be that without a return value, safari thinks that this object should not be loaded.
Use the IE6 css+javascript hack: ``` .dynamic_img { width: expression(document.body.clientWidth <= 800? "auto" : "800px"); max-width: 800px; //For normal browsers } ```
HTML + Javascript: Dynamic Image Resize?
[ "", "javascript", "html", "css", "resize-image", "" ]
A coworker asked me to look at indexing on some tables because his query was running very long. Over an hour. ``` select count(1) from databaseA.dbo.table1 inner join databaseA.dbo.table2 on (table1.key = table2.key) inner join databaseB.dbo.table3 on (table1.key = table3.key) ``` Note the different databases. This was being run from DatabaseB Tables 1 and 2 were over 2 million records long. Table3 had a dozen records or so. I looked at the query plan and the optimizer decided to do nested-loop index seeks into tables 1 and 2 with Table3 as the driving table! My first assumption was that statistics were seriously messed up on Tables1 & 2 but before updating statistics I tried adding a join hint thusly: ``` select count(1) from databaseA.dbo.table1 inner HASH join databaseA.dbo.table2 on (table1.key = table2.key) inner join databaseB.dbo.table3 on (table1.key = table3.key) ``` Results returned in 15 seconds. Since I was short on time, I passed the results back to him but I'm worried that this might result in problems down the road. Should I revisit the statistics issue and resolve the problem that way? Could the bad query plan have resulted from the join being from a separate databases? Can anyone offer me some ideas based on your experience?
I would suspect the statistics first. As you are no doubt aware, Join hints should be avoided in 99% of cases and used only when you have proof that they are absolutely required.
Check statistics, and indexing on the table first. Index hints can cause problems. If the data in the tables changes the optimizer will be unable to choose a more efficent plan since you have forced it to always use a hash.
Is this join hint dangerous?
[ "", "sql", "join", "sql-server-2000", "join-hints", "" ]
i'm using this example implementation found at <http://tangentsoft.net/wskfaq/examples/basics/select-server.html> This is doing most of what I need, handles connections without blocking and does all work in its thread (not creating a new thread for each connection as some examples do), but i'm worried since i've been told winsock will only support max 64 client connectios :S Is this 64 connections true? What other choices do I have? It would be cool to have a c++ example for a similar implementation. Thanks
**Alternative library:** You should consider using [boost asio](http://www.boost.org/doc/libs/1_37_0/doc/html/boost_asio.html). It is a cross platform networking library which simplifies many of the tasks you may have to do. You can find the [example source code you seek here](http://www.boost.org/doc/libs/1_37_0/doc/html/boost_asio/examples.html). --- **About the 64 limit:** There is no hard 64 connection limit that you will experience with a good design. Basically if you use some kind of threading model you will not experience this limitation. Here's some information on the limit you heard about: > 4.9 - What are the "64 sockets" limitations? > > There are two 64-socket limitations: > > The Win32 event mechanism (e.g. > WaitForMultipleObjects()) can only > wait on 64 event objects at a time. > Winsock 2 provides the > WSAEventSelect() function which lets > you use Win32's event mechanism to > wait for events on sockets. Because it > uses Win32's event mechanism, you can > only wait for events on 64 sockets at > a time. If you want to wait on more > than 64 Winsock event objects at a > time, you need to use multiple > threads, each waiting on no more than > 64 of the sockets. > > The select() function is also limited > in certain situations to waiting on 64 > sockets at a time. The FD\_SETSIZE > constant defined in winsock.h > determines the size of the fd\_set > structures you pass to select(). It's > defined by default to 64. You can > define this constant to a higher value > before you #include winsock.h, and > this will override the default value. > Unfortunately, at least one > non-Microsoft Winsock stack and some > Layered Service Providers assume the > default of 64; they will ignore > sockets beyond the 64th in larger > fd\_sets. > > You can write a test program to try > this on the systems you plan on > supporting, to see if they are not > limited. If they are, you can get > around this with threads, just as you > would with event objects. [Source](http://tangentsoft.net/wskfaq/advanced.html)
@Brian: ``` if ((gConnections.size() + 1) > 64) { // For the background on this check, see // www.tangentsoft.net/wskfaq/advanced.html#64sockets // The +1 is to account for the listener socket. cout << "WARNING: More than 63 client " "connections accepted. This will not " "work reliably on some Winsock " "stacks!" << endl; } ``` To the OP: Why would you not want to use winsock2? You could try to look at building your own server using IOCP, although making this cross-platform is a little tricky. You could look at Boost::asio like Brian suggested.
alternatives to winsock2 with example server source in c++
[ "", "c++", "winsock", "" ]
I have a List (Foo) and I want to see if it's equal to another List (foo). What is the fastest way ?
Here are the steps I would do: 1. Do an object.ReferenceEquals() if true, then return true. 2. Check the count, if not the same, return false. 3. Compare the elements one by one. Here are some suggestions for the method: 1. Base the implementation on ICollection. This gives you the count, but doesn't restrict to specific collection type or contained type. 2. You can implement the method as an extension method to ICollection. 3. You will need to use the .Equals() for comparing the elements of the list.
From 3.5 onwards you may use a LINQ function for this: ``` List<string> l1 = new List<string> {"Hello", "World","How","Are","You"}; List<string> l2 = new List<string> {"Hello","World","How","Are","You"}; Console.WriteLine(l1.SequenceEqual(l2)); ``` It also knows an overload to provide your own comparer
Fastest way to compare two lists
[ "", "c#", "collections", "" ]
In the application I'm working on porting to the web, we currently dynamically access different tables at runtime from run to run, based on a "template" string that is specified. I would like to move the burden of doing that back to the database now that we are moving to SQL server, so I don't have to mess with a dynamic GridView. I thought of writing a Table-valued UDF with a parameter for the table name and one for the query WHERE clause. I entered the following for my UDF but obviously it doesn't work. Is there any way to take a varchar or string of some kind and get a table reference that can work in the FROM clause? ``` CREATE FUNCTION TemplateSelector ( @template varchar(40), @code varchar(80) ) RETURNS TABLE AS RETURN ( SELECT * FROM @template WHERE ProductionCode = @code ) ``` Or some other way of getting a result set similar in concept to this. Basically all records in the table indicated by the varchar @template with the matching ProductionCode of the @code. I get the error "Must declare the table variable "@template"", so SQL server probably things I'm trying to select from a table variable. On Edit: Yeah I don't need to do it in a function, I can run Stored Procs, I've just not written any of them before.
``` CREATE PROCEDURE TemplateSelector ( @template varchar(40), @code varchar(80) ) AS EXEC('SELECT * FROM ' + @template + ' WHERE ProductionCode = ' + @code) ``` This works, though it's not a UDF.
The only way to do this is with the exec command. Also, you have to move it out to a stored proc instead of a function. Apparently functions can't execute dynamic sql.
How do I supply the FROM clause of a SELECT statement from a UDF parameter
[ "", "sql", "sql-server", "user-defined-functions", "" ]
I've got this code in a pair of button click event handlers on a C# form: ``` class frmLogin { private const int SHORT_HEIGHT = 120; private const int LONG_HEIGHT = 220; private EventHandler ExpandHandler; private EventHandler ShrinkHandler; public frmLogin() { InitializeComponent(); ExpandHandler = new EventHandler(btnExpand_Click); ShrinkHandler = new EventHandler(btnShrink_Click); btnExpand.Click += ExpandHandler; } private void btnExpand_Click(object sender, EventArgs e) { this.Height = LONG_HEIGHT; btnExpand.Text = "<< Hide Server"; btnExpand.Click -= ExpandHandler; btnExpand.Click += ShrinkHandler; } private void btnShrink_Click(object sender, EventArgs e) { this.Height = SHORT_HEIGHT; btnExpand.Text = "Choose Server >>"; btnExpand.Click -= ShrinkHandler; btnExpand.Click += ExpandHandler; } } ``` The text change occurs without issue, but on one particular client machine, a Dell M4300 laptop workstation, the height change does not take effect. Has anyone resolved a similar issue, and what was the fix if so?
My guess: The DPI or system font size is different on that machine and your form's AutoScaleMode is either "Font" or "Dpi", making your form's MinimumSize or MaximumSize prevent the change.
Check the display mode for the laptop, and in particular check the aspect-ratio setting. Sometimes laptops do weird things to facilitate the wide, short screen.
C# - cannot set form.height
[ "", "c#", "winforms", ".net-2.0", "" ]
I wish to print a `Stack<Integer>` object as nicely as the Eclipse debugger does (i.e. `[1,2,3...]`) but printing it with `out = "output:" + stack` doesn't return this nice result. Just to clarify, I'm talking about Java's built-in collection so I can't override its `toString()`. How can I get a nice printable version of the stack?
You could convert it to an array and then print that out with `Arrays.toString(Object[])`: ``` System.out.println(Arrays.toString(stack.toArray())); ```
``` String.join(",", yourIterable); ``` (Java 8)
Printing Java Collections Nicely (toString Doesn't Return Pretty Output)
[ "", "java", "debugging", "pretty-print", "" ]
> **Possible Duplicates:** > [C++0X when?](https://stackoverflow.com/questions/226061/c0x-when) > [When will C++0x be finished?](https://stackoverflow.com/questions/5436139/when-will-c0x-be-finished) When will [C++0x](http://en.wikipedia.org/wiki/C%2B%2B0x) be released? Anyone here know anything?
**Edit**: We have a new standard now : <http://herbsutter.com/2011/08/12/we-have-an-international-standard-c0x-is-unanimously-approved/> --- **Edit**: The FDIS is done, so officially it should be released in few months. See : <http://herbsutter.com/2011/03/25/we-have-fdis-trip-report-march-2011-c-standards-meeting/> --- Herb Sutter is a useful source of information on this as the convener of then ISO C++ committee (until recently). **EDIT** See his latest blog post [here](http://herbsutter.wordpress.com/2010/03/13/trip-report-march-2010-iso-c-standards-meeting/) from March 13, 2010 for an update on recent progress: C++0x is now a Final Committee Draft, and... *"... assuming all goes well , C++0x could officially be published as soon as next year as ISO C++ 2011, and we can stop with the “x-is-hex” jokes and just start calling it C++11."* P.J. Plauger has taken over as the new convener, but I expect that Herb will continue to provide updates on the committee's progress - and as Herb also works for Microsoft, early clues as to when a Microsoft implementation of C++0X will be available.
The deadline is **2009**.
When will C++0x be released?
[ "", "c++", "c++11", "" ]
Hi i'v look through the WMI class... but none can help me in getting the partition table information... now i'm having a project which is to display the USB thumbdrive's .MBR how should i go about it? really puzzle... Any help and guide will be very much appreciated! p.s. the code can only be written in C# **Edit** Thank you! I've browse through the CreateFile documentation... Still wondering how should I use P/Invoke to call CreateFile and to read the boot sector( display out the .MBR )? Do you have any reference code for this portion? Thank you once again!!
If you're prepared to parse the raw information yourself, you can use P/Invoke to call CreateFile. If your user account has enough mojo, you can open the raw disk device by passing it a string, something like `"\\.\PHYSICALDRIVE0"`. See the documentation for CreateFile for more details.
If you want you can use WMI to get information about any drive. To do this you need to query the corresponding WMI classes. With C# you must add these references: ``` System.Management ``` and using statements: ``` using System.Management; ``` To get disk info for which are attached to your computer you can use this query: ``` Select * From Win32_DiskDrive ``` with C#, you can query like: ``` SelectQuery wmi_sorgusu = new SelectQuery("Select * from Win32_DiskDrive"); ManagementObjectSearcher wmi_bulucu = new ManagementObjectSearcher( wmi_sorgusu ); foreach (ManagementObject wmi_nesne in wmi_bulucu.Get()) { Console.WriteLine(wmi_nesne.GetPropertyValue( "DeviceID" ).ToString()); Console.WriteLine(wmi_nesne.GetPropertyValue( "InterfaceType" ).ToString()); Console.WriteLine(wmi_nesne.GetPropertyValue( "Caption" ).ToString()); Console.WriteLine(wmi_nesne.GetPropertyValue( "Status" ).ToString()); Console.WriteLine(wmi_nesne.GetPropertyValue( "MediaLoaded" ).ToString()); //... etc } ``` After getting the device parameters, you can use the same method to query Win32\_DiskPartition WMI Class. You can give the device parameters to SELECT query as WHERE clause. Queries to Win32\_DiskPartition returns all the partitions of all drives attached to system.
How should I using C# to read partition table/boot sector?
[ "", "c#", "" ]
At the company I work for, I have created a Error Logging class to handle errors in my ASP.net application. It is a custom class because we are not allowed to install additional software on our servers (nLog, log4net, etc). I currently use it in two of my projects and have seen some good results from it. Right now I am trapping the errors that cause page and application errors. It sends and stores the error message and all inner exceptions. The problem I am having now is, I am receiving errors that I am not quite sure how to reproduce. I have not heard any error reports from any of my users. I am not sure what they are doing, or even if they are seeing these as errors. I am thinking about creating an Event Log on each page, or the ones I want additional information on. Keeping it as a Session variable on the page, and writing events to it (start/end of functions, variable changes, etc). Then only if an error is called to have that send along with the error message to see if it gives a better picture of what is going on. I am hoping that doing it this way will not give me tons of event logs when all users access the application, just want was going on right before the error happen with the one user. Do you know of any pitfalls I should watchout with method? Do you have any advise for things to look for? Update: @Saret: I understnad where you are coming from with that response and I agree. I am fairly new to this company and still need to learn how they do things. In the past I have had conversations with my coworkers how it would be great to have this product, or use this open source project. The problem comes down to is, we work on secure systems and getting approval to get these things takes a lot of time, top cover, and dealing with all the red tape. I will look into the situation further because I believe having a good error logging system in place is important, currently nothing is being used. @Jim Blizard: I wanted to try to get away from logging/storing everything someplace to come back and find out what is important to the situation that caused the error. I didn't want to fall into overload of information that is talked about in artical that Roberto Barros linked. My current method of thinking is, keeping a string in memory on each page, and if an error is rasied, on the pages Page\_Error event, grab that string and attach it to the exception that is getting logged. That way I am only logging the error/exceptions that occured and storing the event log with that error. If nothing happens, that log that was being created is dropped into the bit bucket never to be seen again. @Roberto Barros: Thanks for that link, I remember reading it somewhere but forgot to save it.
This might not be the exact answer you are looking for, but why develop your own error logging mechanism when there are powerful tools (which you mention) that handle all these key issues for you? I can appreciate you are not allowed to install additional software but aren't logging libraries just classes like your custom code? Where is the fundamental difference? I would reckon the time spent worrying about implementing a logging framework might be better spent advocating and making a business case for a decent logging solution.
I once worked for an agency that would not allow installation of anything that wasn't purely my own code or their (horrid) COM objects. If you have this type of limitation, then see if you can grab the source for log4net and include in your project. There is nothing better than log4net currently when it comes to logging.
How much information to log from errors?
[ "", "c#", "asp.net", "error-logging", "" ]
I recently watched [this youtube tutorial](http://www.youtube.com/watch?v=hp1Y9bhail8) on the Null Object design pattern. Even though there were some errors in it: such as the NullCar that doesn't do anything creates an infinite loop, the concept was well explained. My question is, what do you do when the objects that can be null have getters, and are used in your code? How do you know which value to return by default? Or should I implement this pattern inside all the objects? What if I need to return strings or primitives? I'm talking from a Java perspective. **EDIT**: won't I be trading null objects testing for default value testing ? If not , why not ?
As far as I've understood it the idea is that the null object's value is as close to "nothing" as possible. That unfortunately means you have to define it yourself. As an example I personally use "" when I can't pass a null String, null object number for me is -1 (mostly because by default most database sequences start at 1 and we use those for item id:s a lot so -1 is dead giveaway it's a null object), with lists/maps/sets it's `Collections.EMPTY_SET`, `EMPTY_MAP` or `EMPTY_LIST` and so on and so forth. If I have custom class I have to create a null object from, I remove all actual data from it and see where that takes me and then apply what I just mentioned until it's "empty". So you really don't "know" which value to return by default, you just have to decide it by yourself.
The objective of a Null Object is to avoid having Null references in the code. The values returned by Null Object getters depend on your domain. Zero or empty string are usually appropriate. If we transpose the Null Object pattern to real life, what you're asking is similar to ask "*how old is nobody ?*". Perhaps your design can be improved as you seem not to follow the [tell, don't ask](http://www.pragprog.com/articles/tell-dont-ask) principle. EDIT: the [Null Object design pattern](http://cs.oberlin.edu/~jwalker/nullObjPattern/) is typically used when an object delegates behavior to another object (such as in Strategy or State Design Patterns) ; as Tom Hawtin - tackline commented, use [Special Case Objects](http://martinfowler.com/eaaCatalog/specialCase.html) for objects returning values.
Null object design pattern question
[ "", "java", "design-patterns", "null-object-pattern", "" ]
I've made a C# usercontrol with one textbox and one richtextbox. How can I access the properties of the richtextbox from outside the usercontrol. For example.. if i put it in a form, how can i use the Text propertie of the richtextbox??? thanks
Cleanest way is to expose the desired properties as properties of your usercontrol, e.g: ``` class MyUserControl { // expose the Text of the richtext control (read-only) public string TextOfRichTextBox { get { return richTextBox.Text; } } // expose the Checked Property of a checkbox (read/write) public bool CheckBoxProperty { get { return checkBox.Checked; } set { checkBox.Checked = value; } } //... } ``` In this way you can control which properties you want to expose and whether they should be read/write or read-only. (of course you should use better names for the properties, depending on their meaning). Another advantage of this approach is that it hides the internal implementation of your user control. Should you ever want to exchange your richtext control with a different one, you won't break the callers/users of your control.
Change the access modifier ("Modifiers") of the RichTextBox in the property grid to Public.
How to access properties of a usercontrol in C#
[ "", "c#", "user-controls", "properties", "richtextbox", "" ]
I found several other questions on SO regarding the JavaMail API and sending mail through an SMTP server, but none of them discussed using TLS security. I'm trying to use JavaMail to send status updates to myself through my work SMTP mail server, but it requires TLS, and I can't find any examples online of how to use JavaMail to access an SMTP server that requires TLS encryption. Can anyone help with this?
We actually have some notification code in our product that uses TLS to send mail if it is available. You will need to set the Java Mail properties. You only need the TLS one but you might need SSL if your SMTP server uses SSL. ``` Properties props = new Properties(); props.put("mail.smtp.starttls.enable","true"); props.put("mail.smtp.auth", "true"); // If you need to authenticate // Use the following if you need SSL props.put("mail.smtp.socketFactory.port", d_port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); ``` You can then either pass this to a JavaMail Session or any other session instantiator like `Session.getDefaultInstance(props)`.
Good post, the line ``` props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); ``` is mandatory if the SMTP server uses **SSL Authentication**, like the GMail SMTP server does. However if the server uses **Plaintext Authentication over TLS**, it should not be present, because Java Mail will complain about the initial connection being plaintext. Also make sure you are using the latest version of Java Mail. Recently I used some old Java Mail jars from a previous project and could not make the code work, because the login process was failing. After I have upgraded to the latest version of Java Mail, the reason of the error became clear: it was a javax.net.ssl.SSLHandshakeException, which was not thrown up in the old version of the lib.
Using JavaMail with TLS
[ "", "java", "smtp", "jakarta-mail", "ssl", "" ]
What is the easiest way to highlight the difference between two strings in PHP? I'm thinking along the lines of the Stack Overflow edit history page, where new text is in green and removed text is in red. If there are any pre-written functions or classes available, that would be ideal.
You were able to use the PHP Horde\_Text\_Diff package. However this package is no longer available.
Just wrote a class to compute smallest (not to be taken literally) number of edits to transform one string into another string: <http://www.raymondhill.net/finediff/> It has a static function to render a HTML version of the diff. It's a first version, and likely to be improved, but it works just fine as of now, so I am throwing it out there in case someone needs to generate a compact diff efficiently, like I needed. Edit: It's on Github now: <https://github.com/gorhill/PHP-FineDiff>
Highlight the difference between two strings in PHP
[ "", "php", "string", "diff", "word-diff", "" ]
I have now seen 2 methods for determining if an argument has been passed to a JavaScript function. I'm wondering if one method is better than the other or if one is just bad to use? ``` function Test(argument1, argument2) { if (Test.arguments.length == 1) argument2 = 'blah'; alert(argument2); } Test('test'); ``` Or ``` function Test(argument1, argument2) { argument2 = argument2 || 'blah'; alert(argument2); } Test('test'); ``` As far as I can tell, they both result in the same thing, but I've only used the first one before in production. Another Option as mentioned by [Tom](https://stackoverflow.com/questions/411352/how-best-to-determine-if-an-argument-is-not-sent-to-the-javascript-function#411368): ``` function Test(argument1, argument2) { if(argument2 === null) { argument2 = 'blah'; } alert(argument2); } ``` As per Juan's comment, it would be better to change Tom's suggestion to: ``` function Test(argument1, argument2) { if(argument2 === undefined) { argument2 = 'blah'; } alert(argument2); } ```
There are several different ways to check if an argument was passed to a function. In addition to the two you mentioned in your (original) question - checking `arguments.length` or using the `||` operator to provide default values - one can also explicitly check the arguments for `undefined` via `argument2 === undefined` or `typeof argument2 === 'undefined'` if one is paranoid (see comments). Using the `||` operator has become standard practice - all the cool kids do it - but be careful: The default value will be triggered if the argument evaluates to `false`, which means it might actually be `undefined`, `null`, `false`, `0`, `''` (or anything else for which `Boolean(...)` returns `false`). So the question is when to use which check, as they all yield slightly different results. Checking `arguments.length` exhibits the 'most correct' behaviour, but it might not be feasible if there's more than one optional argument. The test for `undefined` is next 'best' - it only 'fails' if the function is explicitly called with an `undefined` value, which in all likelyhood should be treated the same way as omitting the argument. The use of the `||` operator might trigger usage of the default value even if a valid argument is provided. On the other hand, its behaviour might actually be desired. To summarize: *Only use it if you know what you're doing!* In my opinion, using `||` is also the way to go if there's more than one optional argument and one doesn't want to pass an object literal as a workaround for named parameters. Another nice way to provide default values using `arguments.length` is possible by falling through the labels of a switch statement: ``` function test(requiredArg, optionalArg1, optionalArg2, optionalArg3) { switch(arguments.length) { case 1: optionalArg1 = 'default1'; case 2: optionalArg2 = 'default2'; case 3: optionalArg3 = 'default3'; case 4: break; default: throw new Error('illegal argument count') } // do stuff } ``` This has the downside that the programmer's intention is not (visually) obvious and uses 'magic numbers'; it is therefore possibly error prone.
If you are using jQuery, one option that is nice (especially for complicated situations) is to use [jQuery's extend method](http://api.jquery.com/jQuery.extend/). ``` function foo(options) { default_options = { timeout : 1000, callback : function(){}, some_number : 50, some_text : "hello world" }; options = $.extend({}, default_options, options); } ``` If you call the function then like this: ``` foo({timeout : 500}); ``` The options variable would then be: ``` { timeout : 500, callback : function(){}, some_number : 50, some_text : "hello world" }; ```
How best to determine if an argument is not sent to the JavaScript function
[ "", "javascript", "arguments", "" ]
Okay, I have this program and I don't want more than one instance of it running. So what I have right now is it grabs all instances that match it's name, and if there are more than one it quits and lets the user know it's already running in another instance. However, there is a special case in which the new instance will want change what the other instance is doing, then it will exit. How can I do this? Here's an example: I have this program that times an event. I don't want more than one running at the same time because you can't be doing two things at once (for this application). Now say a third party program wants to notify this thread that the user is now working on something else, so it launches the application again. If the application is already running, it will update it's actions, else it will act as normal. How can this be done? This is what I use to tell if there is another instance running: ``` string proc = Process.GetCurrentProcess().ProcessName; Process[] processess = Process.GetProcessesByName(proc); if (processess.Length > 1) { MessageBox.Show("There is an instance of the Timer already running"); return; } ```
The thing that complicates this is the fact that you want, in certain conditions, to allow a second invocation of the program to do something if another one is running. Using the named mutex will allow you to detect whether the program is already running -- it should be holding the mutex already. You will still need a way to communicate with it to tell the running program to do something when the second one runs. An asynchronous message queue would probably work, you'd just need to have the running program check it periodically to see if there are any new messages waiting. The message would need to tell the program how to change. Look at the [System.Threading](http://msdn.microsoft.com/en-us/library/system.threading.aspx) namespace (since it looks like you're using .Net already), in particular the mutex and semaphore classes, and [System.Messaging.MessageQueue](http://msdn.microsoft.com/en-us/library/system.messaging.messagequeue.aspx) for message exchange. The basic idea is: ``` program start try to acquire mutex (or semaphore) if failed send message via message queue to running program exit else set up listener for message queue run rest of program ``` The listener could take the form of a timer that expires periodically with the expiration callback checking for messages in the queue and updating the program actions accordingly. The timer would need to autoreset so that it would go back to listening. Your program will need the ability to recover from being interrupted by the timer and "restart" based on the updated configuration.
You can use a shared (named) mutex for this. See the [Win32 API documentation for Mutex objects](http://msdn.microsoft.com/en-us/library/ms684266(VS.85).aspx) (I assume C# has language bindings for this).
Preventing a second instance from running except in a specific case
[ "", "c#", "multithreading", "process", "" ]
Does anyone know how to turn this string: "Smith, John R" Into this string: "jsmith" ? I need to lowercase everything with lower() Find where the comma is and track it's integer location value Get the first character after that comma and put it in front of the string Then get the entire last name and stick it after the first initial. Sidenote - instr() function is not compatible with my version Thanks for any help!
Start by writing your own INSTR function - call it my\_instr for example. It will start at char 1 and loop until it finds a ','. Then use as you would INSTR.
The best way to do this is using Oracle Regular Expressions feature, like this: ``` SELECT LOWER(regexp_replace('Smith, John R', '(.+)(, )([A-Z])(.+)', '\3\1', 1, 1)) FROM DUAL; ``` That says, 1) when you find the pattern of any set of characters, followed by ", ", followed by an uppercase character, followed by any remaining characters, take the third element (initial of first name) and append the last name. Then make everything lowercase. Your side note: "instr() function is not compatible with my version" doesn't make sense to me, as that function's been around for ages. Check your version, because Regular Expressions was only added to Oracle in version 9i. Thanks for the points. -- Stew
Oracle SQL - Parsing a name string and converting it to first initial & last name
[ "", "sql", "string", "parsing", "informix", "" ]
Why is ++i is l-value and i++ not?
Well as another answerer pointed out already the reason why `++i` is an lvalue is to pass it to a reference. ``` int v = 0; int const & rcv = ++v; // would work if ++v is an rvalue too int & rv = ++v; // would not work if ++v is an rvalue ``` The reason for the second rule is to allow to initialize a reference using a literal, when the reference is a reference to const: ``` void taking_refc(int const& v); taking_refc(10); // valid, 10 is an rvalue though! ``` Why do we introduce an rvalue at all you may ask. Well, these terms come up when building the language rules for these two situations: * We want to have a locator value. That will represent a location which contains a value that can be read. * We want to represent the value of an expression. The above two points are taken from the C99 Standard which includes this nice footnote quite helpful: > [ The name ‘‘lvalue’’ comes originally > from the assignment expression E1 = > E2, in which the left operand E1 is > required to be a (modifiable) lvalue. > It is perhaps better considered as > representing an object ‘‘locator > value’’. What is sometimes called > ‘‘rvalue’’ is in this International > Standard described as the ‘‘value of > an expression’’. ] The locator value is called *lvalue*, while the value resulting from evaluating that location is called *rvalue*. That's right according also to the C++ Standard (talking about the lvalue-to-rvalue conversion): > 4.1/2: The value contained in the object > indicated by the lvalue is the rvalue > result. ### Conclusion Using the above semantics, it is clear now why `i++` is no lvalue but an rvalue. Because the expression returned is not located in `i` anymore (it's incremented!), it is just the value that can be of interest. Modifying that value returned by `i++` would make not sense, because we don't have a location from which we could read that value again. And so the Standard says it is an rvalue, and it thus can only bind to a reference-to-const. However, in constrast, the expression returned by `++i` is the location (lvalue) of `i`. Provoking an lvalue-to-rvalue conversion, like in `int a = ++i;` will read the value out of it. Alternatively, we can make a reference point to it, and read out the value later: `int &a = ++i;`. Note also the other occasions where rvalues are generated. For example, all temporaries are rvalues, the result of binary/unary + and minus and all return value expressions that are not references. All those expressions are not located in an named object, but carry rather values only. Those values can of course be backed up by objects that are not constant. The next C++ Version will include so-called `rvalue references` that, even though they point to nonconst, can bind to an rvalue. The rationale is to be able to "steal" away resources from those anonymous objects, and avoid copies doing that. Assuming a class-type that has overloaded prefix ++ (returning `Object&`) and postfix ++ (returning `Object`), the following would cause a copy first, and for the second case it will steal the resources from the rvalue: ``` Object o1(++a); // lvalue => can't steal. It will deep copy. Object o2(a++); // rvalue => steal resources (like just swapping pointers) ```
Other people have tackled the functional difference between post and pre increment. As far as being an **lvalue** is concerned, `i++` can't be assigned to because it doesn't refer to a variable. It refers to a calculated value. In terms of assignment, both of the following make no sense in the same sort of way: ``` i++ = 5; i + 0 = 5; ``` Because pre-increment returns a reference to the incremented variable rather than a temporary copy, `++i` is an lvalue. Preferring pre-increment for performance reasons becomes an especially good idea when you are incrementing something like an iterator object (eg in the STL) that may well be a good bit more heavyweight than an int.
Why is ++i considered an l-value, but i++ is not?
[ "", "c++", "operators", "increment", "rvalue", "" ]
I have an object in C# on which I need to execute a method on a regular basis. I would like this method to be executed only when other people are using my object, as soon as people stop using my object I would like this background operation to stop. So here is a simple example is this (which is broken): ``` class Fish { public Fish() { Thread t = new Thread(new ThreadStart(BackgroundWork)); t.IsBackground = true; t.Start(); } public void BackgroundWork() { while(true) { this.Swim(); Thread.Sleep(1000); } } public void Swim() { Console.WriteLine("The fish is Swimming"); } } ``` The problem is that if I new a Fish object anywhere, it never gets garbage collected, cause there is a background thread referencing it. Here is an illustrated version of broken code. ``` public void DoStuff() { Fish f = new Fish(); } // after existing from this method my Fish object keeps on swimming. ``` I know that the Fish object should be disposable and I should clean up the thread on dispose, but I have no control over my callers and can not ensure dispose is called. How do I work around this problem and ensure the background threads are automatically disposed even if Dispose is not called explicitly?
Here is my proposed solution to this problem: ``` class Fish : IDisposable { class Swimmer { Thread t; WeakReference fishRef; public ManualResetEvent terminate = new ManualResetEvent(false); public Swimmer(Fish3 fish) { this.fishRef = new WeakReference(fish); t = new Thread(new ThreadStart(BackgroundWork)); t.IsBackground = true; t.Start(); } public void BackgroundWork() { bool done = false; while(!done) { done = Swim(); if (!done) { done = terminate.WaitOne(1000, false); } } } // this is pulled out into a helper method to ensure // the Fish object is referenced for the minimal amount of time private bool Swim() { bool done; Fish fish = Fish; if (fish != null) { fish.Swim(); done = false; } else { done = true; } return done; } public Fish Fish { get { return fishRef.Target as Fish3; } } } Swimmer swimmer; public Fish() { swimmer = new Swimmer(this); } public void Swim() { Console.WriteLine("The third fish is Swimming"); } volatile bool disposed = false; public void Dispose() { if (!disposed) { swimmer.terminate.Set(); disposed = true; GC.SuppressFinalize(this); } } ~Fish() { if(!disposed) { Dispose(); } } } ```
I think the IDisposable solution is the correct one. If the users of your class don't follow the guidelines for using classes that implement IDisposable it's their fault - and you can make sure that the documentation explicitly mentions how the class should be used. Another, much messier, option would be a "KeepAlive" DateTime field that each method called by your client would update. The worker thread then checks the field periodically and exits if it hasn't been updated for a certain amount of time. When a method is setting the field the thread will be restarted if it has exited.
Automatically terminating non essential threads in C#
[ "", "c#", "multithreading", "" ]
I have a Double which could have a value from around 0.000001 to 1,000,000,000.000 I wish to format this number as a string but conditionally depending on its size. So if it's very small I want to format it with something like: ``` String.Format("{0:.000000000}", number); ``` if it's not that small, say 0.001 then I want to use something like ``` String.Format("{0:.00000}", number); ``` and if it's over, say 1,000 then format it as: ``` String.Format("{0:.0}", number); ``` Is there a clever way to construct this format string based on the size of the value I'm going to format?
Use Math.Log10 of the absolute value of the double to figure out how many 0's you need either left (if positive) or right (if negative) of the decimal place. Choose the format string based on this value. You'll need handle zero values separately. ``` string s; double epislon = 0.0000001; // or however near zero you want to consider as zero if (Math.Abs(value) < epislon) { int digits = Math.Log10( Math.Abs( value )); // if (digits >= 0) ++digits; // if you care about the exact number if (digits < -5) { s = string.Format( "{0:0.000000000}", value ); } else if (digits < 0) { s = string.Format( "{0:0.00000})", value ); } else { s = string.Format( "{0:#,###,###,##0.000}", value ); } } else { s = "0"; } ``` Or construct it dynamically based on the number of digits.
The first two String.Format in your question can be solved by automatically removing trailing zeros: ``` String.Format("{0:#,##0.########}", number); ``` And the last one you could solve by calling Math.Round(number,1) for values over 1000 and then use the same String.Format. Something like: ``` String.Format("{0:#,##0.########}", number<1000 ? number : Math.Round(number,1)); ```
Formatting double as string in C#
[ "", "c#", ".net", "formatting", "" ]
Hi I've got a DIV section that has only its title visible initially. What I would like to achieve is that when the visitor clicks anywhere on the area of `toggle_section` the `toggle_stuff` div toggles between visible/hidden. ``` <div id="toggle_section" onclick="javascript: new Effect.toggle('toggle_stuff', 'slide');"> <div id="toggle_title">Some title</div> <div id="toggle_stuff"> some content stuff <a href="/foo.php">Some link</a> </div> </div> ``` However, the way it is set-up right now, if I have any `<a>` link within the `toggle_section`, clicking that link will also execute the onclick event. Then my question is what would be the best way to set this type of behavior?
The most simple solution is to **add an extra onclick handler to the link** within your DIV which stops event propagation: ``` <div id="toggle_section" onclick="javascript: new Effect.toggle('toggle_stuff', 'slide');"> <div id="toggle_title">Some title</div> <div id="toggle_stuff"> some content stuff <a href="/foo.php" onclick="Event.stop(event);" >Some link</a> </div> </div> ``` The above example uses Prototype's [`Event.stop()`](http://www.prototypejs.org/api/event/stop) function in order to facilitate a cross browser event propagation stop. As you use the inline `onclick()` handler, most (if not all) browser will traverse the event in the bubbling phase first (which is what you want). A good guide to understanding the actual reasons behind this behaviour and the differences between *event capturing* and *event bubbling* can be found at the excellent [Quirksmode.](http://www.quirksmode.org/js/events_order.html)
in script : ``` function overlayvis(blck) { el = document.getElementById(blck.id); el.style.visibility = (el.style.visibility == 'visible') ? 'hidden' : 'visible'; } ``` activator link, followed by content (no reason that couldn't be else on the page): ``` <div onclick='overlayvis(showhideme)">show/hide stuff</div> <div id="showhideme"> ... content to hide / unhide ... </div> ``` I got this from [Modal window javascript css overlay](https://stackoverflow.com/questions/6578427/modal-window-javascript-css-overlay) - had to search for the source and was pleased to find it was this site. :)
How to use javascript onclick on a DIV tag to toggle visibility of a section that contains clickable links?
[ "", "javascript", "css", "prototypejs", "scriptaculous", "" ]
My webservice provider give me a large WSDL file, but we are going to use only a few function inside. I believe that the large WSDL have negative impact to the application performance. We use the webservice in client appliction, **startup time** and **memory usage** are issues. Large WSDL means that jax-ws will takes longer to do binding and will takes more memory for the stub class. Is is possible that we trim WSDL file to a lightweight version? Are there any tool for this purpose? I do not think my webservice provider will generate another WSDL for us. We may have to **do it auto in the build script**.
In short, your answers are "No tool, but you can DIY". I wish there are simple tool can do it because my WSDL contains too many unused function and schema of data structure. If I can automate it, WSDL -> trimmed WSDL -> generate client stubs classes. Nothing unused will be generated, no misuse, no maintenances required, we will not touch on the generated code, and I can really focus on the code which in use. Smaller JAR, shorter XML parse time. If the WSDL get updated, I will had only to rebuild client stubs classes and run unit test. I tried to keep off from human invoked. It takes time, easily to get mistake, and have to redo every time every little change on the original WSDL. I am not conversant on the WSDL schema. I am thinking can it be done by XSLT?
The size of the WSDL will have zero impact on performance... unless you are downloading it and/or parsing it for every request. And if you are doing the latter, don't. It need only be processed when the service changes, and the service should always change compatibly, with continuing support of old messages (at least for some overlapping time period). You should consider processing a WSDL to be a program change, and do it as you would any release, with versioning, and testing, etc.
Working with large wsdl, can we trim it?
[ "", "java", "web-services", "wsdl", "jax-ws", "" ]
I have a CustomAction as part of an MSI. It MUST run as a domain account that is also a member of the local Administrators account. It can't use the NoImpersonate flag to run the custom action as NT Authority\System as it will not then get access to network resources. On Vista/2008 with UAC enabled if NoImpersonate is off then it will run as the executing user but with the **unprivileged** token and not get access to local resources such as .installState. [See UAC Architecture](http://technet.microsoft.com/en-us/library/cc709628.aspx) Anyone know of a way to either * Force the MSI to run with the elevated token in the same way that running from an elevated command prompt does? * Force the CustomAction to run elevated (requireAdministrator in manifest doesn't appear to work)? * Work out if UAC is enabled and if it hasn't been ran elevated and if so warn or cancel the installation?
Answering my own question for any other poor s0d looking at this. * You can't add a manifest to an MSI. You could add a SETUP.EXE or bootstrapper to shell the MSI and manifest that with requireAdministrator but that defeats some of the point of using an MSI. * Adding a manifest to a CustomAction does not work as it is ran from msiexec.exe The way I have tackled this is to set the [MSIUSEREALADMINDETECTION](http://msdn.microsoft.com/en-us/library/aa816403(VS.85).aspx) property to 1 so the Privileged condition actually works and add a Launch Condition for [Privileged](http://msdn.microsoft.com/en-us/library/aa370852(VS.85).aspx) that gives an error message about running via an elevated command prompt and then quits the installation. This has the happy side effect - when an msi is ran from an elevated command prompt deferred CustomActions are ran as the current user with a full Administrator token (rather than standard user token) regardless of the [NoImpersonate](http://blogs.msdn.com/rflaming/archive/2006/09/23/768248.aspx) setting. More details - <http://www.microsoft.com/downloads/details.aspx?FamilyID=2cd92e43-6cda-478a-9e3b-4f831e899433> [Edit] - I've put script here that [lets you add the MSIUSEREALADMINDETECTION property](https://stackoverflow.com/questions/312490/script-to-add-msiuserealadmin-to-msi) as VS doesn't have ability to do it and Orca's a pain.
requireAdministrator in the manifest should work. You can also use a bootloader .exe file which can use ShellExecute with "RUNAS" as the verb (you can use 7-zip to create the bootloader, or there are many other ways).
Mark MSI so it has to be run as elevated Administrator account
[ "", "c#", "windows-installer", "uac", "custom-action", "" ]
I am trying to pass a dataString to to an ajax call using JQuery. In the call, I construct the get parameters and then send them to the php page on the receiving end. The trouble is that the data string has ampersands in them and the HTML strict validator is chocking on it. Here is the code: ``` $(document).ready(function(){ $("input#email").focus(); $('#login_submit').submit(function(){ var username = $('input#email').val(); var password = $('input#password').val(); var remember = $('input#remember').attr("checked"); var dataString = "email="+username+"&password="+password+"&remember="+remember; $.post('login.php', dataString, function(data) { if (data == 'Login Succeeded.') { location.reload(true); } else { $("input#email").focus(); $("#login_msg").html(data).effect("pulsate", {times: 2}, 1000); } }); return false; }); }); ``` and here is an example of the validator message: cannot generate system identifier for general entity "password". ``` var dataString = "email="+username+"&password="+password+"&remember="+rememb… ``` (in the validator the "p" after the first ampersand is marked red indicating the point of the failure).
Try putting your javascript inside a CDATA block like this: ``` <script type="text/javascript"> <![CDATA[ // content of your Javascript goes here ]]> </script> ``` which should make it pass validation. To be extra safe you can add Javascript comments around the CDATA tags to hide them from older browsers who don't understand the CDATA tag: ``` <script type="text/javascript"> /* <![CDATA[ */ // content of your Javascript goes here /* ]]> */ </script> ```
"\u0026" works!
How do I escape an ampersand in a javascript string so that the page will validate strict?
[ "", "javascript", "jquery", "ajax", "w3c-validation", "" ]
I have the following code: ``` if ($_POST['submit'] == "Next") { foreach($_POST['info'] as $key => $value) { echo $value; } } ``` How do I get the foreach function to start from the 2nd key in the array?
For reasonably small arrays, use [array\_slice](http://fr.php.net/manual/en/function.array-slice.php) to create a second one: ``` foreach(array_slice($_POST['info'],1) as $key=>$value) { echo $value; } ```
``` foreach(array_slice($_POST['info'], 1) as $key=>$value) { echo $value; } ``` Alternatively if you don't want to copy the array you could just do: ``` $isFirst = true; foreach($_POST['info'] as $key=>$value) { if ($isFirst) { $isFirst = false; continue; } echo $value; } ```
How to skip the 1st key in an array loop?
[ "", "php", "arrays", "" ]
If I have a string with a valid math expression such as: ``` String s = "1 + 2 * 7"; ``` Is there a built in library/function in .NET that will parse and evaluate that expression for me and return the result? In this case 15.
You could add a reference to Microsoft Script Control Library (COM) and use code like this to evaluate an expression. (Also works for JScript.) ``` Dim sc As New MSScriptControl.ScriptControl() sc.Language = "VBScript" Dim expression As String = "1 + 2 * 7" Dim result As Double = sc.Eval(expression) ``` **Edit** - C# version. ``` MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl(); sc.Language = "VBScript"; string expression = "1 + 2 * 7"; object result = sc.Eval(expression); MessageBox.Show(result.ToString()); ``` **Edit** - The ScriptControl is a COM object. In the "Add reference" dialog of the project select the "COM" tab and scroll down to "Microsoft Script Control 1.0" and select ok.
Strange that this famous and old question has not an answer that suggests the builtin [`DataTable.Compute`](http://msdn.microsoft.com/en-us/library/system.data.datatable.compute.aspx)-"trick". Here it is. ``` double result = Convert.ToDouble(new DataTable().Compute("1 + 2 * 7", null)); ``` The following arithmetic operators are supported in expressions: ``` + (addition) - (subtraction) * (multiplication) / (division) % (modulus) ``` More informations: [`DataColumn.Expression`](http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression.aspx) at *Expression Syntax*.
Is there a string math evaluator in .NET?
[ "", "c#", ".net", "" ]
Following on from [this](https://stackoverflow.com/questions/371418/can-you-represent-csv-data-in-googles-protocol-buffer-format) question, what would be the best way to represent a System.Decimal object in a Protocol Buffer?
Well, protobuf-net will simply handle this for you; it runs off the properties of types, and has full support for `decimal`. Since there is no direct way of expressing `decimal` in proto, it won't (currently) generate a `decimal` property from a ".proto" file, but it would be a nice tweak to recognise some common type ("BCL.Decimal" or similar) and interpret it as decimal. As for representing it - I had a [discussion document](http://code.google.com/p/protobuf-net/wiki/DotNetTypes) on this (now out of date I suspect) in the protobuf-net wiki area; there is now a working version in protobuf-net that simply does it for you. No doubt Jon and I will hammer this out more later today ;-p The protobuf-net version of this (in .proto) is something like (from [here](http://code.google.com/p/protobuf-net/source/browse/trunk/Tools/bcl.proto)): ``` message Decimal { optional uint64 lo = 1; // the first 64 bits of the underlying value optional uint32 hi = 2; // the last 32 bis of the underlying value optional sint32 signScale = 3; // the number of decimal digits, and the sign } ```
Marc and I have very vague plans to come up with a "common PB message" library such that you can represent pretty common types (date/time and decimal springing instantly to mind) in a common way, with conversions available in .NET and Java (and anything else anyone wants to contribute). If you're happy to stick to .NET, and you're looking for compactness, I'd possibly go with something like: ``` message Decimal { // 96-bit mantissa broken into two chunks optional uint64 mantissa_msb = 1; optional uint32 mantissa_lsb = 2; required sint32 exponent_and_sign = 3; } ``` The sign can just be represented by the sign of exponent\_and\_sign, with the exponent being the absolute value. Making both parts of the mantissa optional means that 0 is represented *very* compactly (but still differentiating between 0m and 0.0000m etc). exponent\_and\_sign could be optional as well if we really wanted. I don't know about Marc's project, but in my port I generate partial classes, so you can the put a conversion between System.Decimal and Protobuf.Common.Decimal (or whatever) into the partial class.
What's the best way to represent System.Decimal in Protocol Buffers?
[ "", "c#", ".net", "floating-point", "protocol-buffers", "" ]
I'm trying to use the StringEscapeUtils.escapeXML() function from org.apache.commons.lang... There are two versions of that function, one which expects (Writer, String) and one which just expects (String).... <http://commons.apache.org/lang/api/org/apache/commons/lang/StringEscapeUtils.html#escapeXml(java.lang.String)> I'm trying to use the version that just expects the String parameter without the Writer, but Java is complaining that I've not given it a Writer. How do I use this in my program so that I don't need a Writer? ``` String escXml = StringEscapeUtils.escapeXml(attr.get()); xml = xml.concat("<"+attr.getID()+">"+escXml+"</"+attr.getID()+">"); ``` I've also tried just doing it inline in the string itself. ``` xml = xml.concat("<"+attr.getID()+">"+StringEscapeUtils.escapeXml(attr.get())+"</"+attr.getID()+">"); ``` Both of these attempts have given me the error about it expecting the Writer though. Can anyone help me with this? Thanks, Matt
The error message is telling you that you are passing an Object into the method, not a String. If you are sure that the Object is a String, then you'll need to cast it to a String first. If this doesn't work, please post the actual code that is giving you trouble.
You should compile the java class with the specify version if you have install the more than one version of java in you system. You should compile your file using this way. javac -target -source E.g H:>javac -target 1.6 -source 1.6 Testt.java So your target and Source version is tell to the java so it will call the particular version class at run time..
How to tell Java which StringEscapeUtils.escapeXML() to use?
[ "", "java", "xml", "jsp", "" ]
I'm reading some code in the [Ogre3D](http://www.ogre3d.org) implementation and I can't understand what a `void *` type variable means. What does a pointer to `void` mean in C++?
A pointer to void, `void*` can point to any object: ``` int a = 5; void *p = &a; double b = 3.14; p = &b; ``` You can't dereference, increment or decrement that pointer, because you don't know what type you point to. The idea is that `void*` can be used for functions like `memcpy` that just copy memory blocks around, and don't care about the type that they copy.
It's just a generic pointer, used to pass data when you don't know the type. You have to cast it to the correct type in order to use it.
Pointer to void in C++?
[ "", "c++", "pointers", "void", "void-pointers", "" ]
What is the main difference between `StringBuffer` and `StringBuilder`? Is there any performance issues when deciding on any one of these?
[`StringBuffer`](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html) is synchronized, [`StringBuilder`](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html) is not.
[`StringBuilder`](http://docs.oracle.com/javase/9/docs/api/java/lang/StringBuilder.html) is faster than [`StringBuffer`](https://docs.oracle.com/javase/9/docs/api/java/lang/StringBuffer.html) because it's not `synchronized`. Here's a simple benchmark test: ``` public class Main { public static void main(String[] args) { int N = 77777777; long t; { StringBuffer sb = new StringBuffer(); t = System.currentTimeMillis(); for (int i = N; i --> 0 ;) { sb.append(""); } System.out.println(System.currentTimeMillis() - t); } { StringBuilder sb = new StringBuilder(); t = System.currentTimeMillis(); for (int i = N; i > 0 ; i--) { sb.append(""); } System.out.println(System.currentTimeMillis() - t); } } } ``` A [test run](http://ideone.com/OpUDPU) gives the numbers of `2241 ms` for `StringBuffer` vs `753 ms` for `StringBuilder`.
Difference between StringBuilder and StringBuffer
[ "", "java", "stringbuilder", "stringbuffer", "" ]
In a mysqli prepared statement, a NULL gets turned into '' (in the case of a string) or 0 (in the case of an integer). I would like to store it as a true NULL. Is there any way of doing this?
It's possible to bind a true NULL value to the prepared statements (read [this](http://www.php.net/manual/en/mysqli-stmt.bind-param.php#96148)). > You can, in fact, use mysqli\_bind\_parameter to pass a NULL value to the database. simply create a variable and store the NULL value (see the manpage for it) to the variable and bind that. Works great for me anyway. Thus it'll have to be something like: ``` <?php $mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world'); // person is some object you have defined earlier $name = $person->name(); $age = $person->age(); $nickname = ($person->nickname() != '') ? $person->nickname() : NULL; // prepare the statement $stmt = $mysqli->prepare("INSERT INTO Name, Age, Nickname VALUES (?, ?, ?)"); $stmt->bind_param('sis', $name, $age, $nickname); ?> ``` This should insert a NULL value into the database.
For anyone coming looking at this because they are having problems binding NULL in their `WHERE` statement, the solution is this: There is a mysql [NULL safe operator](http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html#operator_equal-to) that must be used: `<=>` Example: ``` <?php $price = NULL; // NOTE: no quotes - using php NULL $stmt = $mysqli->prepare("SELECT id FROM product WHERE price <=> ?"); // Will select products where the price is null $stmt->bind_param($price); ?> ```
using nulls in a mysqli prepared statement
[ "", "php", "mysql", "null", "mysqli", "prepared-statement", "" ]
After posting [this question](https://stackoverflow.com/questions/410890/how-to-trace-a-nullpointerexception-in-a-chain-of-getters "How to trace a NullPointerException in a chain of getters?") and reading [that one](https://stackoverflow.com/questions/271526/How-to-avoid-null-statements-in-java "how to avoid null statements in java?") I realized that it is very important to know if a method is supposed to return null, or if this is considered an error condition and an exceptions should be thrown. There also is a nice discussion when to [return ‘null’ or throw exception](https://stackoverflow.com/questions/175532/return-null-or-throw-exception) . **I'm writing a method and I already know if I want to return null or throw an exception, what is the best way to express my decision, in other words, to document my contract?** Some ways I can think of: * Write it down in the specs / the documentation (will anyone read it?) * Make it part of the method name (as I suggested [here](https://stackoverflow.com/questions/175532/return-null-or-throw-exception#411400 "answer on 'Return null or throw exception'")) * assume that every method that *throws* an exception will *not* return null, and every one that does 'not' throw *might* return null. I'm mainly talking about java, but it might apply to other languages, too: Why is there a formal way to express if exceptions will be thrown (the `throws` keywords) but no formal way to express if null might be returned? Why isn't there something like that: ``` public notnull Object methodWhichCannotReturnNull(int i) throws Exception { return null; // this would lead to a compiler error! } ``` ## Summary and Conclusion There are many ways to express the contract: * If your IDE supports it (as IntelliJ), it's best to use an annotation like `@NotNull` because it is visible to the programmer and can be used for automated compile time checking. There's a [plugin for Eclipse](http://groups.csail.mit.edu/pag/jsr308/eclipse/) to add support for these, but it didn't work for me. * If these are not an option, use custom Types like `Option<T>` or `NotNull<T>`, which add clarity and at least runtime checking. * In any way, documenting the contract in the JavaDoc never hurts and sometimes even helps. * Using method names to document the *nullability* of the return value was not proposed by anyone but me, and though it might be very verbose und not always useful, I still believe sometimes it has its advantages, too.
A very good follow up question. I consider `null` a truly special value, and if a method may return `null` it must clearly document in the Javadoc when it does (`@return some value ..., or null if ...`). When coding I'm defensive, and assume a method may return `null` unless I'm convinced it can't (e.g., because the Javadoc said so.) People realized that this is an issue, and a proposed solution is to use annotations to state the intention in a way it can be checked automatically. See [JSR 305: Annotations for Software Defect Detection](http://jcp.org/en/jsr/detail?id=305), [JSR 308: Annotations on Java Types](http://jcp.org/en/jsr/detail?id=308) and [JetBrain's Nullable How-To](http://www.jetbrains.com/idea/documentation/howto.html). Your example might look like this, and refused by the IDE, the compiler or other code analysis tools. ``` @NotNull public Object methodWhichCannotReturnNull(int i) throws Exception { return null; // this would lead to a compiler error! } ```
You can use the [`Option`](http://functionaljava.googlecode.com/svn/artifacts/2.17/javadoc/fj/data/Option.html) type, which is very much like a list that has zero or one element. A return type of `Option<Object>` indicates that the method may return an `Object`, or it may return a special value of type `None`. This type is a replacement for the use of null with better type checks. Example: ``` public Option<Integer> parseInt(String s) { try { return Option.some(Integer.parseInt(s)); } catch (Exception e) { return Option.none(); } } ``` If you use this consistently, you can turn on IDE null-warnings, or just use grep for `null` which should not appear in your code at all if you use `Option.none()` everywhere you would normaly use a `null` literal. `Option` comes standard with Scala, and it is called `Maybe` in Haskell. The link above is to a library called [Functional Java](http://functionaljava.org) that includes it. That version implements the `Iterable` interface, and has monadic methods that let you compose things nicely. For example, to provide a default value of 0 in case of `None`: ``` int x = optionalInt.orSome(0); ``` And you can replace this... ``` if (myString != null && !"".equals(myString)) ``` ...with this, if you have an `Option<String>`... ``` for (String s : myOptionString) ```
How to show if a method may return null
[ "", "java", "null", "design-by-contract", "" ]
I know of `python -c '<code>'`, but I'm wondering if there's a more elegant python equivalent to `perl -pi -e '<code>'`. I still use it quite a bit for things like find and replace in a whole directory (`perl -pi -e s/foo/bar/g *` or even `find . | xargs perl -pi -e s/foo/bar/g` for sub-directories). I actually feel that that which makes Perl Perl (free form Tim Toady-ness) is what makes `perl -pi -e` work so well, while with Python you'd have to do something along the lines of importing the re module, creating an re instance and then capture stdin, but maybe there's a Python shortcut that does all that and I missed it (sorely missed it)...
The command line usage from '`python -h`' certainly strongly suggests there is no such equivalent. Perl tends to make extensive use of '`$_`' (your examples make implicit use of it), and I don't think Python supports any similar concept, thereby making Python equivalents of the Perl one-liners much harder.
An equivalent to -pi isn't that hard to write in Python. 1. Write yourself a handy module with the -p and -i features you really like. Let's call it `pypi.py`. 2. Use `python -c 'import pypi; pypi.subs("this","that")'` You can implement the basic -p loop with the [fileinput](http://docs.python.org/library/fileinput.html) module. You'd have a function, `subs` that implements the essential "-i" algorithm of opening a file, saving the backup copy, and doing the substitute on each line. There are some activestate recipes like this. Here are some: * <http://code.activestate.com/recipes/437932/> * <http://code.activestate.com/recipes/435904/> * <http://code.activestate.com/recipes/576537/> Not built-in. But not difficult to write. And once written easy to customize.
Is there a Python equivalent to `perl -pi -e`?
[ "", "python", "perl", "command-line", "language-features", "" ]
I need to get the image dimensions of a JPEG in C++. I'm looking for either a fairly simple way to do it or a smallish library that provides that functionality. I'm working in C++ on OpenVMS, so any external libraries may have to be adapted to compile on our systems - so please don't post me links to big, closed source libraries! Has anyone come across anything that might do the trick, or understand the JPEG file format (I think I probably mean the JFIF file format here) to tell me how I might go about rolling my own solution?
You have this [C function](http://carnage-melon.tom7.org/stuff/jpegsize.html) which may extract the relevant data for you. > This is a C routine but should compile fine with C++. > Pass it a normal FILE pointer (from fopen) to the beginning of a jpeg file and two int pointers to be set with the image height and width. Or you may find in the [Boost library](http://www.boost.org/doc/libs/1_35_0/boost/gil/extension/io/jpeg_io.hpp) a jpeg class which has the right function (From [Adobe](http://www.adobe.com/technology/graphics/generic_image_library.html) [Generic Image Library](http://opensource.adobe.com/wiki/display/gil/Generic+Image+Library)). [jpeg\_read\_dimensions](http://stlab.adobe.com/gil/html/group___j_p_e_g___i_o.html#ga4) ``` boost::gil::jpeg_read_dimensions (const char *filename) ``` > Returns the width and height of the JPEG file at the specified location. Throws std::ios\_base::failure if the location does not correspond to a valid JPEG file.
libjpeg is reasonably small, open source and available on OpenVMS. It's probably quicker to install it than to handle JPEG yourself.
Get dimensions of JPEG in C++
[ "", "c++", "jpeg", "openvms", "" ]
I'm trying to convert an openGL [edit: "card that I drew"(?):) thx unwind]containing a lot of textures (nothing moving) into one PNG file that I can use in another part of the framework I'm working with. Is there a C++ library that does that? thanks!
If you simply mean "take a scene rendered by OpenGL and save it as an image," then it is fairly straightforward. You need to read the scene with glReadPixels(), and then convert that data to an image format such as PNG (<http://www.opengl.org/resources/faq/technical/miscellaneous.htm>). There are also more efficient ways of achieving this, such as using [FBO](http://www.songho.ca/opengl/gl_fbo.html#example)s. Instead of rendering the scene directly into the framebuffer, you can render it to a texture via an FBO, then render that texture as a full-screen quad. You can then take this texture and save it to a file (using [glGetTexImage](http://www.opengl.org/sdk/docs/man/xhtml/glGetTexImage.xml), for example).
What is an "OpenGL file"? OpenGL is a graphics API, it doesn't specify any file formats. Do you mean a DDS file, or something?
openGL into png
[ "", "c++", "opengl", "png", "ldf", "" ]
I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad. **Update** `html2text` looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean. --- Related questions: * [Filter out HTML tags and resolve entities in python](https://stackoverflow.com/questions/37486/filter-out-html-tags-and-resolve-entities-in-python) * [Convert XML/HTML Entities into Unicode String in Python](https://stackoverflow.com/questions/57708/convert-xmlhtml-entities-into-unicode-string-in-python)
[html2text](https://github.com/Alir3z4/html2text) is a Python program that does a pretty good job at this.
The best piece of code I found for extracting text without getting javascript or not wanted things : ``` from urllib.request import urlopen from bs4 import BeautifulSoup url = "http://news.bbc.co.uk/2/hi/health/2284783.stm" html = urlopen(url).read() soup = BeautifulSoup(html, features="html.parser") # kill all script and style elements for script in soup(["script", "style"]): script.extract() # rip it out # get text text = soup.get_text() # break into lines and remove leading and trailing space on each lines = (line.strip() for line in text.splitlines()) # break multi-headlines into a line each chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) # drop blank lines text = '\n'.join(chunk for chunk in chunks if chunk) print(text) ``` You just have to install BeautifulSoup before : ``` pip install beautifulsoup4 ```
Extracting text from HTML file using Python
[ "", "python", "html", "text", "html-content-extraction", "" ]
I have a php file which I will be using as exclusively as an include. Therefore I would like to throw an error instead of executing it when it's accessed directly by typing in the URL instead of being included. Basically I need to do a check as follows in the php file: ``` if ( $REQUEST_URL == $URL_OF_CURRENT_PAGE ) die ("Direct access not premitted"); ``` Is there an easy way to do this?
The easiest way for the generic "PHP app running on an Apache server that you may or may not fully control" situation is to put your includes in a directory and deny access to that directory in your .htaccess file. To save people the trouble of Googling, if you're using Apache, put this in a file called ".htaccess" in the directory you don't want to be accessible: ``` Deny from all ``` If you actually have full control of the server (more common these days even for little apps than when I first wrote this answer), the best approach is to stick the files you want to protect outside of the directory that your web server is serving from. So if your app is in `/srv/YourApp/`, set the server to serve files from `/srv/YourApp/app/` and put the includes in `/srv/YourApp/includes`, so there literally isn't any URL that can access them.
Add this to the page that you want to only be included ``` <?php if(!defined('MyConst')) { die('Direct access not permitted'); } ?> ``` then on the pages that include it add ``` <?php define('MyConst', TRUE); ?> ```
Prevent direct access to a php include file
[ "", "php", "include", "include-guards", "" ]
I see many, many sites that have URLs for individual pages such as <http://www.mysite.com/articles/this-is-article-1> <http://www.mysite.com/galleries/575> And they don't redirect, they don't run slowly... I know how to parse URL's, that's easy enough. But in my mind, that seems slow and cumbersome on a dynamic site. As well, if the pages are all staticly built (hende the custom URL) then that means all components of the page are static as well... (which would be bad) I'd love to hear some ideas about how this is typically accomplished.
Firstly, when comparing /plain/ URL rewriting at the application level to using /plain/ CGI (CGI can be PHP, ISAPI, ASP.NET, etc.) with serving static pages, serving static files will always, always win. There is simply less work. For example, in Windows and Linux (that I know of) there are even enhancements in the kernel for serving static files on a local drive via HTTP. To further make the point I even found a benchmark using several servers and OSs: <http://www.litespeedtech.com/web-server-performance-comparison-litespeed-2.0-vs.html#RESULT> Note that serving static files is dramatically faster than using any type of CGI However, there can potentially be performance and scalability gains by using rewritten URLs effectively and it is done with caching. If you return proper cache headers (see [cache-control directive in HTTP documentation](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9)) then it enables downstream servers to cache the data so you won't even get hits on your site. However, I guess you could get the same benefit with static pages :) I just happen to read an article on this very topic a day or two ago at the High Scalability blog: <http://highscalability.com/strategy-understanding-your-data-leads-best-scalability-solutions>
There are many ways you can handle the above. Generally speaking, there is always at least some form of redirection involved - although that could be at the .htaccess level rather than php. Here's a scenario: 1. Use .htaccess to redirect to your php processing script. 2. Parse the uri ($\_SERVER['REQUEST\_URI']) and ascertain the type of content (for instance, articles or galleries as per your examples). 3. Use the provided id (generally appended to the end of the uri, again as in your examples) to obtain the correct data - be that by serving a static file or querying a database for the requested content. This method is a very popular way of increasing SEO, but as you rightly highlight there can be difficulties in taking this approach - not typically performance, but it can make development or administration more troublesome (the later if your implementation is not well thought out and scalable).
Question on dynamic URL parsing
[ "", "php", "url", "url-parsing", "" ]
I have a script that I'd like to continue using, but it looks like I either have to find some workaround for a bug in Python 3, or downgrade back to 2.6, and thus having to downgrade other scripts as well... Hopefully someone here have already managed to find a workaround. The problem is that due to the new changes in Python 3.0 regarding bytes and strings, not all the library code is apparently tested. I have a script that downloades a page from a web server. This script passed a username and password as part of the url in python 2.6, but in Python 3.0, this doesn't work any more. For instance, this: ``` import urllib.request; url = "http://username:password@server/file"; urllib.request.urlretrieve(url, "temp.dat"); ``` fails with this exception: ``` Traceback (most recent call last): File "C:\Temp\test.py", line 5, in <module> urllib.request.urlretrieve(url, "test.html"); File "C:\Python30\lib\urllib\request.py", line 134, in urlretrieve return _urlopener.retrieve(url, filename, reporthook, data) File "C:\Python30\lib\urllib\request.py", line 1476, in retrieve fp = self.open(url, data) File "C:\Python30\lib\urllib\request.py", line 1444, in open return getattr(self, name)(url) File "C:\Python30\lib\urllib\request.py", line 1618, in open_http return self._open_generic_http(http.client.HTTPConnection, url, data) File "C:\Python30\lib\urllib\request.py", line 1576, in _open_generic_http auth = base64.b64encode(user_passwd).strip() File "C:\Python30\lib\base64.py", line 56, in b64encode raise TypeError("expected bytes, not %s" % s.__class__.__name__) TypeError: expected bytes, not str ``` Apparently, base64-encoding now needs bytes in and outputs a string, and thus urlretrieve (or some code therein) which builds up a string of username:password, and tries to base64-encode this for simple authorization, fails. If I instead try to use urlopen, like this: ``` import urllib.request; url = "http://username:password@server/file"; f = urllib.request.urlopen(url); contents = f.read(); ``` Then it fails with this exception: ``` Traceback (most recent call last): File "C:\Temp\test.py", line 5, in <module> f = urllib.request.urlopen(url); File "C:\Python30\lib\urllib\request.py", line 122, in urlopen return _opener.open(url, data, timeout) File "C:\Python30\lib\urllib\request.py", line 359, in open response = self._open(req, data) File "C:\Python30\lib\urllib\request.py", line 377, in _open '_open', req) File "C:\Python30\lib\urllib\request.py", line 337, in _call_chain result = func(*args) File "C:\Python30\lib\urllib\request.py", line 1082, in http_open return self.do_open(http.client.HTTPConnection, req) File "C:\Python30\lib\urllib\request.py", line 1051, in do_open h = http_class(host, timeout=req.timeout) # will parse host:port File "C:\Python30\lib\http\client.py", line 620, in __init__ self._set_hostport(host, port) File "C:\Python30\lib\http\client.py", line 632, in _set_hostport raise InvalidURL("nonnumeric port: '%s'" % host[i+1:]) http.client.InvalidURL: nonnumeric port: 'password@server' ``` Apparently the url parsing in this "next gen url retrieval library" doesn't know what to do with username and passwords in the url. What other choices do I have?
Direct from the Py3k docs: <http://docs.python.org/dev/py3k/library/urllib.request.html#examples> ``` import urllib.request # Create an OpenerDirector with support for Basic HTTP Authentication... auth_handler = urllib.request.HTTPBasicAuthHandler() auth_handler.add_password(realm='PDQ Application', uri='https://mahler:8092/site-updates.py', user='klem', passwd='kadidd!ehopper') opener = urllib.request.build_opener(auth_handler) # ...and install it globally so it can be used with urlopen. urllib.request.install_opener(opener) urllib.request.urlopen('http://www.example.com/login.html') ```
My advice would be to maintain your 2.\* branch as your production branch until you can get the 3.0 stuff sorted. I am going to wait a while before moving over to Python 3.0. There seems a lot of people in a rush, but I just want everything sorted out, and a decent selection of third-party libraries. This may take a year, it may take 18 months, but the pressure to "upgrade" is really low for me.
How to download a file over http with authorization in python 3.0, working around bugs?
[ "", "python", "python-3.x", "urllib", "" ]
I've seen a number of people claim that you should specifically name each column you want in your select query. Assuming I'm going to use all of the columns anyway, why would I not use `SELECT *`? Even considering the question \*[SQL query - Select \* from view or Select col1, col2, … colN from view](https://stackoverflow.com/questions/128412/sql-query-question-select-from-view-or-select-col1col2from-view)\*, I don't think this is an exact duplicate as I'm approaching the issue from a slightly different perspective. One of our principles is to not optimize before it's time. With that in mind, it seems like using `SELECT *` should be the **preferred** method until it is proven to be a resource issue or the schema is pretty much set in stone. Which, as we know, won't occur until development is completely done. That said, is there an overriding issue to not use `SELECT *`?
The essence of the quote of not prematurely optimizing is to go for simple and straightforward code and **then** use a profiler to point out the hot spots, which you can then optimize to be efficient. When you use select \* you're make it impossible to profile, therefore you're not writing clear & straightforward code and you are going against the spirit of the quote. `select *` is an anti-pattern. --- So selecting columns is not a premature optimization. A few things off the top of my head .... 1. If you specify columns in a SQL statement, the SQL execution engine will error if that column is removed from the table and the query is executed. 2. You can more easily scan code where that column is being used. 3. You should always write queries to bring back the least amount of information. 4. As others mention if you use ordinal column access you should never use select \* 5. If your SQL statement joins tables, select \* gives you all columns from all tables in the join The corollary is that using `select *` ... 1. The columns used by the application is opaque 2. DBA's and their query profilers are unable to help your application's poor performance 3. The code is more brittle when changes occur 4. Your database and network are suffering because they are bringing back too much data (I/O) 5. Database engine optimizations are minimal as you're bringing back all data regardless (logical). --- Writing correct SQL is just as easy as writing `Select *`. So the real lazy person writes proper SQL because they don't want to revisit the code and try to remember what they were doing when they did it. They don't want to explain to the DBA's about every bit of code. They don't want to explain to their clients why the application runs like a dog.
If your code depends on the columns being in a specific order, your code will break when there are changes to the table. Also, you may be fetching too much from the table when you select \*, especially if there is a binary field in the table. Just because you are using all the columns now, it doesn't mean someone else isn't going to add an extra column to the table. It also adds overhead to the plan execution caching since it has to fetch the meta data about the table to know what columns are in \*.
What is the reason not to use select *?
[ "", "sql", "" ]
This particular example relates to Django in Python, but should apply to any language supporting exceptions: ``` try: object = ModelClass.objects.get(search=value) except DoesNotExist: pass if object: # do stuff ``` The Django model class provides a simple method *get* which allows me to search for *one and only one* object from the database, if it finds more or less it raises an exception. If can find zero or more with an alternative *filter* method, which returns a list: ``` objects = ModelClass.objects.filter(search=value) if len(objects) == 1: object = objects[0] # do stuff ``` **Am I overly averse to exceptions?** To me the exception seems a little wasteful, at a guess, a quarter-to-a-half of the time will be 'exceptional'. I'd much prefer a function that returns *None* on failure. Would I be better to use Django's *filter* method and process the list myself?
The clue is in the name - exceptions should be exceptional. If you always expect the item will exist then use `get`, but if you expect it not to exist a reasonable proportion of the time (i.e. it not existing is an expected result rather than an exceptional result) then I'd suggest using `filter`. So, seeing as you indicated that between 1 in 2 and 1 in 4 are expected not to exist, I'd definitely write a wrapper around `filter`, as that's definitely not an exceptional case.
Believe it or not, this actually is an issue that is a bit different in each language. In Python, exceptions are regularly thrown for events that aren't exceptional by the language itself. Thus I think that the "you should only throw exceptions under exceptional circumstances" rule doesn't quite apply. I think the results you'll get on this forum will be slanted towards that point of view though, considering the high number of .Net programmers (see [this question](https://stackoverflow.com/questions/351400/why-are-net-programmers-so-afraid-of-exceptions)) for more info on that). At a very minimum, I'd better not catch anyone who sticks to that rule ever using a generator or a for loop in Python (both of which involve throwing exceptions for non-exceptional circumstances).
Avoid exceptions?
[ "", "python", "django", "exception", "" ]
every time i code a gui (in my case with GWT, never touched gui programming before), i notice that my code becomes a big mess, when the applications becomes more complex. It's really frustrating to look over my code and get a headache of all these setters in object constructors and this messy throwing together of these. I am using the MVC Pattern and it really helps to get a lot clearer. Unfortunately my whole view component isn't clear at any point. ;-) I tried to use a lot of interfaces to abstract from the building process and to have just a few implemented interfaces which will be added together, (I thought i could switch between different libraries, like Gwt-Ext and Gxt, easily) but still i am not really happy. I am sure you had this problems too, and i want to ask you what practice do you follow to get cleaner code? Are there design patterns for gui coding except MVC? What are your tricks for highly readable and beautiful user interface code?
Martin Fowler wrote interesting article on this topic: [GUI Architectures](http://martinfowler.com/eaaDev/uiArchs.html)
When I'm coding a GUI in GWT I like to create Widgets that do just some small task. This way It becomes much clearer when you then combine those widgets in the final view. On the other hand you can get a widget mess all over. So try to balance what can go in a new widget (to be used on many places) and what in the view.
Patterns and more for clean and easy gui code
[ "", "java", "user-interface", "design-patterns", "gwt", "" ]
I have three buttons and need to save some data. I have a idea, I have to set an ID to every button and then let the JS determinate witch button that has been pressed, like: ``` $("#mySpecifikButton").click(function() { ....some code here... }); ``` but then Im stuck. For example I have 9 users. All they have an ID in the db. So now we have all the users in separate rows: ``` <p><a id="userID">user 0</a></p> <p><a id="userID">user 1</a></p> <p><a id="userID">user 2</a></p> <p><a id="userID">user 3</a></p> ... ``` When I press on a specifik user I want to add it to db through php with help of jquery. But how do I sent it to php with JS (jquery)? Im I thinking right or is there better ways? If I didn't described it well, ask me.
From what I can see, you can use Ajax to send the value of the button that has been pressed to the php script. Search the [jQuery site](http://jquery.com) for documentation on $.get and $.post. :) Edit: Now that I'm not on my iPod, it'll be much easier to type. :P Here's what I mean: ``` <input type="button" value="Button 1" id="1" /> <input type="button" value="Button 2" id="2" /> <input type="button" value="Button 3" id="3" /> <input type="button" value="Button 4" id="4" /> ``` Then, use some JS: ``` <script type="text/javascript"> $("input[type=button]").click(function() { $.post("myPHPscript.php",{buttonID: $(this).attr("id")},function(d) { //d is the response from the PHP page. //Do something with it! }); }); </script> ```
As it sounds like you are making changes to the database, I would recommend using the `$.post( url, [data], [callback], [type] );` [link](http://docs.jquery.com/Ajax/jQuery.post#urldatacallbacktype). You can just post a form to the server and deal with it like you would any other form post.
jquery & php: saving some data without reload
[ "", "php", "jquery", "" ]
It's been a while since I used Java in anger so please forgive me if this is silly. I have just got started on a Java project where we are using JAXB to de-serializing an incoming XML string (from Jetty Server). The project is only using JAXB for this situation. What are the alternatives to JAXB? What are pros/cons of JAXB to these alternatives I have done some googling and found lots of reference material, but is there a definitive source that is the goto place for JAXB questions or do people just see what people are doing and interpret from there. Thanks.
I've found JAX-B pretty useful and actually like it better than many of the alternatives, especially if I'm starting from scratch and generating a schema from Java objects rather than Java objects from a schema. In my experience, for whatever reason, I've found good documentation hard to come by from just Google searches. The best electronic documentation is provided in the JAX-B download where you'll also find numerous examples. "[SOA Using Java Web Services](https://rads.stackoverflow.com/amzn/click/com/0130449687)" also has a good overview. As for alternatives, there is: * [XStream](http://xstream.codehaus.org/) * [Castor](http://castor.codehaus.org/xml-framework.html) and probably several more.
XML Bean comes to mind (<http://xmlbeans.apache.org/>) One of the PROS about JAXB is that it now comes bundle in with JDK6. The generate output is really tight and efficient. We are currently converting all our XML Bean implementation to use JAXB 2. The big CONS that we have seen is the lack of XSD related operations.
Java JAXB Pros/Cons and Documentation
[ "", "java", "documentation", "jaxb", "" ]
I have a simple question and wish to hear others' experiences regarding which is the best way to replicate images across multiple hosts. I have determined that storing images in the database and then using database replication over multiple hosts would result in maximum availability. The worry I have with the filesystem is the difficulty synchronising the images (e.g I don't want 5 servers all hitting the same server for images!). Now, the only concerns I have with storing images in the database is the extra queries hitting the database and the extra handling i'd have to put in place in apache if I wanted 'virtual' image links to point to database entries. (e.g AddHandler) As far as my understanding goes: * If you have a script serving up the images: Each image would require a database call. * If you display the images inline as binary data: Which could be done in a single database call. * To provide external / linkable images you would have to add a addHandler for the extension you wish to 'fake' and point it to your scripting language (e.g php, asp). I might have missed something, but I'm curious if anyone has any better ideas? --- Edit: Tom has suggested using mod\_rewrite to save using an AddHandler, I have accepted as a proposed solution to the AddHandler issue; however I don't yet feel like I have a complete solution yet so please, please, keep answering ;) A few have suggested using lighttpd over Apache. How different are the ISAPI modules for lighttpd?
If you store images in the database, you take an extra database hit *plus* you lose the innate caching/file serving optimizations in your web server. Apache will serve a static image much faster than PHP can manage it. In our large app environments, we use up to 4 clusters: * App server cluster * Web service/data service cluster * Static resource (image, documents, multi-media) cluster * Database cluster You'd be surprised how much traffic a static resource server can handle. Since it's not really computing (no app logic), a response can be optimized like crazy. If you go with a separate static resource cluster, you also leave yourself open to change just that portion of your architecture. For instance, in some benchmarks [lighttpd](http://www.lighttpd.net/) is even faster at serving static resources than apache. If you have a separate cluster, you can change your http server there without changing anything else in your app environment. I'd start with a 2-machine static resource cluster and see how that performs. That's another benefit of separating functions - you can scale out only where you need it. As far as synchronizing files, take a look at existing [file synchronization](http://en.wikipedia.org/wiki/File_synchronization) tools versus rolling your own. You may find something that does what you need without having to write a line of code.
Serving the images from wherever you decide to store them is a trivial problem; I won't discuss how to solve it. Deciding where to store them is the real decision you need to make. You need to think about what your goals are: * Redundancy of hardware * Lots of cheap storage * Read-scaling * Write-scaling The last two are not the same and will definitely cause problems. If you are confident that the size of this image library will not exceed the disc you're happy to put on your web servers (say, 200G at the time of writing, as being the largest high speed server-grade discs that can be obtained; I assume you want to use 1U web servers so you won't be able to store more than that in raid1, depending on your vendor), then you can get very good read-scaling by placing a copy of all the images on every web server. Of course you might want to keep a master copy somewhere too, and have a daemon or process which syncs them from time to time, and have monitoring to check that they remain in sync and this daemon works, but these are details. Keeping a copy on every web server will make read-scaling pretty much perfect. But keeping a copy everywhere will ruin write-scalability, as every single web server will have to write every changed / new file. Therefore your total write throughput will be limited to the slowest single web server in the cluster. "Sharding" your image data between many servers will give good read/write scalability, but is a nontrivial exercise. It may also allow you to use cheap(ish) storage. Having a single central server (or active/passive pair or something) with expensive IO hardware will give better write-throughput than using "cheap" IO hardware everywhere, but you'll then be limited by read-scalability.
File / Image Replication
[ "", "php", "mysql", "sql-server", "apache", "image", "" ]
What is the use of anonymous classes in Java? Can we say that usage of anonymous class is one of the advantages of Java?
By an "anonymous class", I take it you mean [anonymous inner class](http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html). An anonymous inner class can come useful when making an instance of an object with certain "extras" such as overriding methods, without having to actually subclass a class. I tend to use it as a shortcut for attaching an event listener: ``` button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // do something } }); ``` Using this method makes coding a little bit quicker, as I don't need to make an extra class that implements `ActionListener` -- I can just instantiate an anonymous inner class without actually making a separate class. I only use this technique for "quick and dirty" tasks where making an entire class feels unnecessary. Having multiple anonymous inner classes that do exactly the same thing should be refactored to an actual class, be it an inner class or a separate class.
Anonymous inner classes are effectively closures, so they can be used to emulate lambda expressions or "delegates". For example, take this interface: ``` public interface F<A, B> { B f(A a); } ``` You can use this anonymously to create a [first-class function](http://en.wikipedia.org/wiki/First-class_function) in Java. Let's say you have the following method that returns the first number larger than i in the given list, or i if no number is larger: ``` public static int larger(final List<Integer> ns, final int i) { for (Integer n : ns) if (n > i) return n; return i; } ``` And then you have another method that returns the first number smaller than i in the given list, or i if no number is smaller: ``` public static int smaller(final List<Integer> ns, final int i) { for (Integer n : ns) if (n < i) return n; return i; } ``` These methods are almost identical. Using the first-class function type F, we can rewrite these into one method as follows: ``` public static <T> T firstMatch(final List<T> ts, final F<T, Boolean> f, T z) { for (T t : ts) if (f.f(t)) return t; return z; } ``` You can use an anonymous class to use the firstMatch method: ``` F<Integer, Boolean> greaterThanTen = new F<Integer, Boolean> { Boolean f(final Integer n) { return n > 10; } }; int moreThanMyFingersCanCount = firstMatch(xs, greaterThanTen, x); ``` This is a really contrived example, but its easy to see that being able to pass functions around as if they were values is a pretty useful feature. See ["Can Your Programming Language Do This"](http://www.joelonsoftware.com/items/2006/08/01.html) by Joel himself. A nice library for programming Java in this style: [Functional Java.](http://functionaljava.org)
How are anonymous inner classes used in Java?
[ "", "java", "anonymous-class", "anonymous-inner-class", "" ]
I would like to know how I can refer to a list item object if I had for example the following html list ``` <div id="subdiv_2"> <div id="subdiv_3"> <ul> <li><a href="">Item1</a></li> <li><a href="">Item2</a></li> <li><a href="">Item3</a></li> </ul> </div> </div> ``` How is it possible to register an onclick to the Item2 li without it having to have a unique elementId eg I can do so for subdiv\_3 because it has a unique ID and isn't in the list by ``` document.getElementById('subdiv_3').addEventListener('click', function();, false); ``` My goal is ultimately to assign a function to each list object, for the number of list objects with unique parameters based upon the list object number eg: ``` for(i=0;i<list.length;i++){ "document.getElementById(list.item"+i+").addEventListener(\'click\',function("+i+");,false);"; } ```
You could get all the children elements of `subdiv_3` that are `<li>`. Then iterate through that loop adding the functions as you go. ``` div = document.getElementById('subdiv_3'); els = div.getElementsByTagName('li'); for (var i=0, len=els.length; i<len; i++) { alert(i); // add your functions here } ``` Looking at your code sample, when you're in the loop creating your functions you may run into closure scoping problems. (All the functions will appear to use the same value of i.) Check out my answer to this question to deal with that problem: [How to Add Event Handler with Arguments to an Array of Elements in Javascript?](https://stackoverflow.com/questions/315712/how-to-add-event-handler-with-arguments-to-an-array-of-elements-in-javascript)
@Supernovah: You can actually assign a real function to `setTimeot()`. That rids you of the string formatting, which will stand in your way when you want to do more complex things than just setting one property. This is the code: ``` function attachToList() { var div = document.getElementById('menu2'); var els = div.getElementsByTagName('li'); // create a closure returning an anonymous inner function var fn = function(li) { return function() { li.style.backgroundColor = "#FFFFCC"; }; }; for (var i=0, len=els.length; i<len; i++) { // create function instance suitable for current iteration var changeLi = fn(els[i]); // pass function reference to setTimeout() setTimeout(changeLi, 250*i); } } ``` And a short explanation: Using a *closure* is the trick that makes sure when `setTimeout()` triggers, all variables still have the expected values. You do this by writing a function that returns a function. The outer function takes parameters, the inner function does not. But it *refers* to the parameters of the outer function. In the loop, you call the outer function (with correct parameters) and get a whole new inner function every time, each which has it's own version of the parameter values. This is the one you assign to `setTimeout()`.
Refer to a html List item object properly in javascript for Event Registration
[ "", "javascript", "html", "dom", "event-handling", "html-lists", "" ]
After I downloaded the [Google Mail](http://mobile.google.com) and [Google Maps](http://mobile.google.com) application into my mobile phone I got an idea about a service that I want to implement. My problem is that I never did any programming for the mobile platform and I need someone to point me out some resources for the Hello World on a mobile and then something a bit more complicated. Let's make it a bit broad, as in J2ME in general for the moment. I'll dig into Android once I get the non Android/\*Berry/etc out of the way.
Clicking [here](http://developers.sun.com/mobility/midp/articles/wtoolkit/) would be a pretty good place to start, it's where the best J2ME programmers have started before you...
Install [NetBeans with J2ME](http://www.netbeans.org/features/javame/index.html) - you can test your mobile applications on a variety of target device emulators. Easy development model - you can develop GUIs rapidly with the Visual Mobile Designer.
Java Mobile programming for a beginner, where to start?
[ "", "java", "mobile", "mobile-phones", "" ]
I want to override access to one variable in a class, but return all others normally. How do I accomplish this with `__getattribute__`? I tried the following (which should also illustrate what I'm trying to do) but I get a recursion error: ``` class D(object): def __init__(self): self.test=20 self.test2=21 def __getattribute__(self,name): if name=='test': return 0. else: return self.__dict__[name] >>> print D().test 0.0 >>> print D().test2 ... RuntimeError: maximum recursion depth exceeded in cmp ```
You get a recursion error because your attempt to access the `self.__dict__` attribute inside `__getattribute__` invokes your `__getattribute__` again. If you use `object`'s `__getattribute__` instead, it works: ``` class D(object): def __init__(self): self.test=20 self.test2=21 def __getattribute__(self,name): if name=='test': return 0. else: return object.__getattribute__(self, name) ``` This works because `object` (in this example) is the base class. By calling the base version of `__getattribute__` you avoid the recursive hell you were in before. Ipython output with code in foo.py: ``` In [1]: from foo import * In [2]: d = D() In [3]: d.test Out[3]: 0.0 In [4]: d.test2 Out[4]: 21 ``` **Update:** There's something in the section titled [*More attribute access for new-style classes*](http://docs.python.org/reference/datamodel.html#more-attribute-access-for-new-style-classes) in the current documentation, where they recommend doing exactly this to avoid the infinite recursion.
Actually, I believe you want to use the [`__getattr__`](https://docs.python.org/3/reference/datamodel.html#object.__getattr__) special method instead. Quote from the Python docs: > `__getattr__( self, name)` > > Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). `name` is the attribute name. This method should return the (computed) attribute value or raise an `AttributeError` exception. > Note that if the attribute is found through the normal mechanism, `__getattr__()` is not called. (This is an intentional asymmetry between `__getattr__()` and `__setattr__()`.) This is done both for efficiency reasons and because otherwise `__setattr__()` would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the `__getattribute__()` method below for a way to actually get total control in new-style classes. Note: for this to work, the instance should *not* have a `test` attribute, so the line `self.test=20` should be removed.
How do I implement __getattribute__ without an infinite recursion error?
[ "", "python", "class", "getattr", "" ]
I'm learning about DDD, and have come across the statement that "value-objects" should be immutable. I understand that this means that the objects state should not change after it has been created. This is kind of a new way of thinking for me, but it makes sense in many cases. Ok, so I start creating immutable value-objects. * I make sure they take the entire state as parameters to the constructor, * I don't add property setters, * and make sure no methods are allowed to modify the content (only return new instances). But now I want to create this value object that will contain 8 different numeric values. If I create a constructor having 8 numeric parameters I feel that it will not be very easy to use, or rather - it will be easy to make a mistake when passing in the numbers. This can't be good design. *So the questions is:* Are there any other ways of making my immutable object better.., any magic that can be done in C# to overcome a long parameter list in the constructor? I'm very interested in hearing your ideas.. **UPDATE:** Before anyone mentions it, one idea has been discussed here: [Immutable object pattern in C# - what do you think?](https://stackoverflow.com/questions/263585/immutable-object-pattern-in-c-what-do-you-think) Would be interested in hearing other suggestions or comments though.
Use a builder: ``` public class Entity { public class Builder { private int _field1; private int _field2; private int _field3; public Builder WithField1(int value) { _field1 = value; return this; } public Builder WithField2(int value) { _field2 = value; return this; } public Builder WithField3(int value) { _field3 = value; return this; } public Entity Build() { return new Entity(_field1, _field2, _field3); } } private int _field1; private int _field2; private int _field3; private Entity(int field1, int field2, int field3) { // Set the fields. } public int Field1 { get { return _field1; } } public int Field2 { get { return _field2; } } public int Field3 { get { return _field3; } } public static Builder Build() { return new Builder(); } } ``` Then create it like: ``` Entity myEntity = Entity.Build() .WithField1(123) .WithField2(456) .WithField3(789) .Build() ``` If some of the parameters are optional you won't need to call the WithXXX method and they can have default values.
At the moment, you'd have to use a constructor with lots of args, or a builder. In C# 4.0 (VS2010), you can use named/optional arguments to achieve something similar to C# 3.0 object-initializers - see [here](http://marcgravell.blogspot.com/2008/11/immutability-and-optional-parameters.html). The example on the blog is: ``` Person p = new Person ( forename: "Fred", surname: "Flintstone" ); ``` But you can easily see how something similar can apply for any constructor (or other complex method). Compare to the C# 3.0 object-initializer syntax (with a mutable type): ``` Person p = new Person { Forename = "Fred", Surname = "Flintstone" }; ``` Not much to tell them apart, really. Jon Skeet has posted some thoughts on this subject too, [here](http://codeblog.jonskeet.uk/2008/03/15/c-4-immutable-type-initialization/).
How to design an immutable object with complex initialization
[ "", "c#", "domain-driven-design", "immutability", "" ]
The setTimeout function always seems to give me trouble. Right now I have a function that is recursive (calls itself through setTimeout) and changes the elements height. The function is sent two arguments: the element to be altered and that elements maximum height. The purpose of the function is to unfold the element, or "slide down" at a constant pace. I'm aware I could probably solve this problem with jQuery, but I'm trying my own function. ``` function slide_down(element, max_height) { if(element.clientHeight < max_height) { var factor = 10; var new_height = (element.clientHeight + factor >= max_height) ? max_height : (element.clientHeight + factor); element.style.height = new_height + 'px'; var func_call = 'slide_down(' + element + ', ' + max_height + ');'; window.setTimeout(func_call, 10); } } ``` I have tested the arguments when the function is initially called. max\_height is set to 20 because it is the elements desired height (I got this value from .scrollHeight). When the function is done, I want to have it call itself until max\_height is the element's height. I do that with this setTimeout call: ``` var func_call = 'slide_down(' + element + ', ' + max_height + ');'; window.setTimeout(func_call, 10); ``` And it is not working. THIS does work: ``` var func_call = 'alert(1);'; window.setTimeout(func_call, 10); ``` I have also tried putting the function call directly into the setTimeout statement, still does not work. Note that the element's height DOES change the first iteration, the function just never calls itself. So the element variable is set correctly, and I used alert() to display the max\_height which is also correct. ``` alert(func_call); ``` Alerts this: ``` slide_down([object HTMLParagraphElement], 20); ```
When you do this: ``` var func_call = 'slide_down(' + element + ', ' + max_height + ');'; ``` you're converting element to a string, so your timeout will look like ``` slide_down("[Object]", 100); ``` which obviously won't work. What you should be doing is creating a closure - it's a little complicated but basically you create a function, and local variable from the old function are still available within the new function. ``` function slide_down(element, max_height) { if(element.clientHeight < max_height) { var factor = 10; var new_height = (element.clientHeight + factor >= max_height) ? max_height : (element.clientHeight + factor); element.style.height = new_height + 'px'; var func = function() { slide_down(element, max_height); } window.setTimeout(func, 10); } } ``` Also 10 is a bit short for a timeout - I'd recommend using 50 as a minimum.
First of all, this "Right now I have a function that is recursive (calls itself through setTimeout)" screams **[setInterval](http://www.w3schools.com/jsref/met_win_setinterval.asp)** to me if you're not varying the period. Secondly, this is because the element reference is lost in the string concat as element.toString() will be "[object]". Try passing in an id you can re-find, store a reference a level up, or (as I've just seen matt b point out) the expanded method form.
Javascript's setTimeout function not calling
[ "", "javascript", "settimeout", "" ]
I am doing some TTF work for MOSA (the correlating body between all the C# operating systems). Me and Colin Burn are currently working on getting some TTF code working (less me these days :) - he made a lot of progress). In any case, the TTF spec allows for an arbitrary amount of control points between the 'handles' and **gasp** NO handles at all (the TTF has an example of a circle demonstrating it - well done idiots - you saved 10 bytes). Can anyone give me a pointer on how this could be done? I looked at the Bezier article on Wikipedia but it wasn't really that much help - they show it happening, but don't give any math. Something 'program' ready would help (my Calculus isn't what it should be) - some pseudocode or something. Thanks guys.
I did some digging and found some [algorithms](http://www.cs.technion.ac.il/~cs234326/projects/fonts/Methods.htm) for the TTF spec over at [this site over here](http://www.cs.technion.ac.il/~cs234326/projects/fonts/).
From the [Bezier article](http://en.wikipedia.org/wiki/Bezier_curves) in wikipedia, with some practical calculus knowledge, you can translate the formulas to a computer program like the following pseudo C# code listing. I'm doing it with quadratic spline, but it is easy to translate to another. ``` // Quadratic spline, with three given points // B(t) = (1-t)^2P(0) + 2*tP(1) + t^2P(2) // where T is a real number in the interval [0, 1] public void DrawQuadSpline(Point p0, Point p1, Point p2, int steps) { Point next = p0; Point previous = p0; double tStep = 1 / ((float) steps); double t = 0; for (int i = 0; i < steps; i++) { float x = CalculateQuadSpline(P0.x, P1.x, P2.x, t); float y = CalculateQuadSpline(P0.y, P1.y, P2.y, t); Point next = new Point(x, y); drawLine(previous, next); previous = next; t = t + tStep; } } private void CalculateQuadSpline(float z0, float z1, float z2, float t) { return (1.0-t)*(1.0-t)*z0 + 2.0*t*z1 + t*t*z2; } ``` It might need some tweaking as I've only did this in Java before, but that's basically it.
Turn a N-Ary B-Spline into a sequence of Quadratic or Cubic B-Splines
[ "", "c#", "algorithm", "math", "spline", "" ]
After returning to an old Rails project I found none of the destroy/delete links worked and clicking cancel on the confirmation popup would still submit the link. Example of my code is: ``` <%= link_to 'Delete', admin_user_path(@user), :confirm => 'Are you sure?', :method => :delete %> ```
This problem occurs if you are using jQuery, and if not, then look for something like that: In my case, I was using: javascript\_include\_tag :all %> And it was not working, but when I put it like: javascript\_include\_tag :defaults %> It worked!
Chris, Hi. I had the same problem. I deleted Firebug and the problem persisted. I read from another user that he needed to restart Firefox, that didn't work either. Some said try Safari, that didn't work either. In the end it was a novice thing: I have helpers to insert an icon, like edit\_icon, which return a nice image tag for the edit icon, etc. One of these helper methods was the delete\_icon method, where I wrote like this: def delete\_icon(object=nil) link\_to image\_tag('icons/delete.jpg', :width => 20, :border=>0), object, :confirm => 'Are you sure?', :method => :delete end It was a (good) attempt at DRY, but better it would have been had I just had def delete\_icon(object), and not object=nil, because it makes it clearer when I call it that I must pass it the object to destroy. Calling the same method with the object to be deleted worked for me. In short: double check your helper methods if you're trying to DRY.
method: => :delete not working and :confirm option ignored
[ "", "javascript", "ruby-on-rails", "" ]
I'm looking for a way in .NET (2.0, C# in particular) for source code to trigger a debugging break as if a breakpoint was set at that point, without having to remember to set a specific breakpoint there in the debugger, and without interfering with production runtime. Our code needs to swallow exceptions in production so we don't disrupt a client application that links to us, but I'm trying to set it up so that such errors will pop up to be analyzed if it happens to be running in a debugger, and otherwise will be safely ignored. My attempt to use `Debug.Assert(false)` has been less than ideal, and I assume that `Debug.Fail()` would behave the same way. It should theoretically have no effect in production, and it does successfully stop when debugging, but by design there is (as far as I can tell) no way to continue execution if you want to ignore that error, like you could with an actual breakpoint, and like it would do in production where we swallow the error. It also apparently breaks evaluation of variable state because the debugger actually stops down in native system code and not in ours, so it's debugging help is limited. (Maybe I'm missing some way of getting back into things to look at the variables and so on where it happened. ???) I was hoping for something like `Debug.Break()`, but it doesn't seem to exist (unless maybe in a later version of .NET?), and no other `Debug` methods seem applicable, either. **Update:** While ctacke's answer is the best match for what I was looking for, I have since also discovered a trick with Debug.Assert()--when running in the debugger--Pause the debugger, go to the code for the Debug.Assert call pending (highlighted in green because it is down in the framework code) and hit Step-Out (shift-F11), then hit Ignore in the assert dialog box. This will leave the debugger paused upon the return of the assert (and able to continue execution as if it hadn't occurred, because it was ignored). There may be other ways to do much the same thing (does hitting Retry do this more directly?), but this way was intuitive.
You probably are after something like this: ``` if(System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break(); ``` Of course that will still get compiled in a Release build. If you want it to behave more like the Debug object where the code simply doesn't exist in a Release build, then you could do something like this: ``` // Conditional("Debug") means that calls to DebugBreak will only be // compiled when Debug is defined. DebugBreak will still be compiled // even in release mode, but the #if eliminates the code within it. // DebuggerHidden is so that, when the break happens, the call stack // is at the caller rather than inside of DebugBreak. [DebuggerHidden] [Conditional("DEBUG")] void DebugBreak() { if(System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break(); } ``` Then add a call to it in your code.
I ran into a situation once where this didn't work ``` System.Diagnostics.Debugger.Break(); ``` but this did ``` System.Diagnostics.Debugger.Launch(); ```
Can .NET source code hard-code a debugging breakpoint?
[ "", "c#", "visual-studio", ".net-2.0", "breakpoints", "" ]
Note: Using MySQL 4.0, which means no subqueries (at present). I have 2 tables: * A "user\_details" table * A "skills" table, which has the user\_id and a "skill\_id", which maps to a predefined set of skills defined elsewhere. The current query allows an admin to search for users by selecting skills, and the query works in an OR fashion, eg: ``` LEFT JOIN skills ON (ud.user_id = skills.user_id) WHERE skills.skill_id in (51, 52, 53, 54, 55) GROUP BY ud.user_id ``` This returns too many records and thus I want this search field to work in an AND fashion, where a user must have ALL the selected skills to be returned in the search. It may be possible to get MySQL upgraded if subqueries are the best option. edit: Something to do with group by, count, having etc. Can you restrict a group by command with a requirement on how many matched rows you return? (eg 5 in this example). edit2: Testing out: ``` HAVING COUNT( * ) > 5 ```
You don't need a subquery or a join. ``` SELECT user_id FROM skills WHERE skill_id IN (51, 52, 53, 54, 55) GROUP BY user_id HAVING COUNT(*) = 5; ```
Just add more single joins. INNER JOIN skills s ON u.id - us.userid AND skill\_id = $s1 INNER JOIN skills s ON u.id - us.userid AND skill\_id = $s2 INNER JOIN skills s ON u.id - us.userid AND skill\_id = $s3 INNER JOIN skills s ON u.id - us.userid AND skill\_id = $s4 etc. It will be required to join to them all. You don't need any groups or counts.
mysql: joining tables + finding records with an AND style query, rather than OR
[ "", "mysql", "sql", "sql-match-all", "" ]
Ok, all these methods of getting data in a Silverlight control are confusing me. I've looked at ADO.Net Data Services, Web Service and Silverlight-enabled WCF services. I'm just not sure when one is appropriate to use over another. What pros/cons do each offer? I've built a web app, and a Silverlight control. I will be adding one of those 3 options to my web application and consuming it from my Silverlight component.
From the silverlight perspective, WCF is heavily constrained anyway, so most of the *usual* benefits of WCF don't apply. However, it is still a fairly nice, consistent programming model. WCF is primarily a SOAP stack, so it is very good at presenting data as rigid operations. ADO.NET Data Services is a REST stack, and allows very expressive queries to be performed dynamically over the wire. I don't know how it is in Silverlight, but a regular ADO.NET Data Services proxy (the bit on your client app) has very rich support for both query and data changes back to the server. Note that applying changes requires either a: Entity Framework, or b: lots of work. But you should get query and update very cheaply with this approach. With WCF, you get a much more controlled stack, so you will need to code all the distinct operations you want to be able to do. But this also means you have a known attack surface etc; it is much harder to exploit a locked down API like a fixed SOAP endpoint. Re regular web-services (pre-WCF): only go down that route if you want to support very specific legacy callers.
I know this is old, but I just wanted to add my 2 cents. I would highly recommend using WCF; and use the WCF Service Library project over the Silverlight-enabled web service. They are both essentially the same, but the Silverlight-enabled web service changes the binding to basic instead of ws\*. It also adds an asp.net compatibility mode attribute. --- * WCF is *usually* faster: See "A Performance Comparison of Windows Communication Foundation (WCF) with Existing Distributed Communication Technologies" @ <http://msdn.microsoft.com/en-us/library/bb310550.aspx> * WCF encapsulates asmx, wse, msmq, enterprise services, and remoting. * WCF services can be included and run within iis, windows forms, etc. * WCF isn't restricted to using HTTP, but with minimal configuration can also use tcp, named pipes etc. * complex data types are easier to expose and serialize. * WCF just scales really well. Plus, they can be used to incorporate workflows from WF. --- There's probably not a wrong technology to use, but it seems as if Microsoft is going to be moving forward with WCF. Plus, it's just so much easier to write one code base that can be exposed so many different ways with just a few configuration changes to the WCF service. I recommend not using the Silverlight-enabled web service, just because the programming structure is set up a little better with the WCF model, but this is probably a matter of opinion.
Silverlight enabled WCF Service vs Web Service vs ADO.NET Data Service
[ "", "c#", ".net", "silverlight", "wcf", "web-services", "" ]
I have a situation where I need to process large (many GB's) amounts of data as such: 1. build a large string by appending many smaller (C char\*) strings 2. trim the string 3. convert the string into a C++ const std::string for processing (read only) 4. repeat The data in each iteration are independent. My question is, I'd like to minimise (if possible eliminate) heap allocated memory usage, as it at the moment is my largest performance problem. Is there a way to convert a C string (char\*) into a stl C++ string (std::string) without requiring std::string to internally alloc/copy the data? Alternatively, could I use stringstreams or something similar to re-use a large buffer? **Edit:** Thanks for the answers, for clarity, I think a revised question would be: *How can I build (via multiple appends) a stl C++ string efficiently. And if performing this action in a loop, where each loop is totally independant, how can I re-use thisallocated space.*
Is it at all possible to use a C++ string in step 1? If you use `string::reserve(size_t)`, you can allocate a large enough buffer to prevent multiple heap allocations while appending the smaller strings, and then you can just use that same C++ string throughout all of the remaining steps. See [this link](http://en.cppreference.com/w/cpp/string/basic_string/reserve) for more information on the `reserve` function.
You can't actually form a std::string without copying the data. A stringstream would probably reuse the memory from pass to pass (though I think the standard is silent on whether it actually has to), but it still wouldn't avoid the copying. A common approach to this sort of problem is to write the code which processes the data in step 3 to use a begin/end iterator pair; then it can easily process either a std::string, a vector of chars, a pair of raw pointers, etc. Unlike passing it a container type like std::string, it would no longer know or care how the memory was allocated, since it would still belong to the caller. Carrying this idea to its logical conclusion is [boost::range](http://www.boost.org/doc/libs/1_37_0/libs/range/index.html), which adds all the overloaded constructors to still let the caller just pass a string/vector/list/any sort of container with .begin() and .end(), or separate iterators. Having written your processing code to work on an arbitrary iterator range, you could then even write a custom iterator (not as hard as it sounds, basically just an object with some standard typedefs, and operator ++/\*/=/==/!= overloaded to get a forward-only iterator) that takes care of advancing to the next fragment each time it hit the end of the one it's working on, skipping over whitespace (I assume that's what you meant by trim). That you never had to assemble the whole string contiguously at all. Whether or not this would be a win depends on how many fragments/how large of fragments you have. This is essentially what the SGI rope mentioned by Martin York is: a string where append forms a linked list of fragments instead of a contiguous buffer, which is thus suitable for much longer values. --- **UPDATE** (since I still see occasional upvotes on this answer): C++17 introduces another choice: [std::string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view), which replaced std::string in many function signatures, is a non-owning reference to a character data. It is implicitly convertible from std::string, but can also be explicitly constructed from contiguous data owned somewhere else, avoiding the unnecessary copying std::string imposes.
initializing std::string from char* without copy
[ "", "c++", "string", "memory-management", "stl", "" ]
Why must class members declared as `const` be initialized in the constructor initializer list rather than in the constructor body? What is the difference between the two?
In C++, an object is considered fully initialised when execution enters the body of the constructor. You said: > "i wanted to know why const must be > intialized in constructor initializer > list rather than in it's body ?." What you are missing is that **initialisation** happens in the initialisation list, and **assignment** happens in the body of the constructor. The steps in logic: 1) A const object can only be initialised. 2) An object has all of its members initialised in the initialisation list. Even if you do not explicitly initialise them there, the compiler will happily do so for you :-) 3) Therefore, putting 1) and 2) together, a member which is const can only ever have a value assigned to it at initialisation, which happens during the initialisation list.
`const` and reference variables must be initialized on the line they are declared. ``` class Something { private: const int m_nValue; public: Something() { m_nValue = 5; } }; ``` would produce code equivalent to; ``` const int nValue; // error, const vars must be assigned values immediately nValue = 5; ``` Assigning const or reference member variables values in the body of the constructor is not sufficient. C++ provides another way of initializing member variables that allows to initialize member variables when they are created rather than afterwards. This is done through use of an initialization list. You can assign values to variables in two ways: explicitly and implicitly: view plaincopy to clipboardprint? ``` int nValue = 5; // explicit assignment double dValue(4.7); // implicit assignment ``` Using an initialization list is very similar to doing implicit assignments. Remember that the member initialization list, used to initialize base and member data objects, is in the definition, not declaration of the constructor. More on [cpp-tutorial](http://www.learncpp.com/cpp-tutorial/101-constructor-initialization-lists/) and [Code Wrangler](http://codewrangler.home.comcast.net/~codewrangler/tech_info/ctor_init.html).
Why must const members be initialized in the constructor initializer rather than in its body?
[ "", "c++", "constructor", "initialization", "constants", "" ]
In using PHP's DOM classes (DOMNode, DOMEElement, etc) I have noticed that they possess truly readonly properties. For example, I can read the $nodeName property of a DOMNode, but I cannot write to it (if I do PHP throws a fatal error). How can I create readonly properties of my own in PHP?
You can do it like this: ``` class Example { private $__readOnly = 'hello world'; function __get($name) { if($name === 'readOnly') return $this->__readOnly; user_error("Invalid property: " . __CLASS__ . "->$name"); } function __set($name, $value) { user_error("Can't set property: " . __CLASS__ . "->$name"); } } ``` Only use this when you really need it - it is slower than normal property access. For PHP, it's best to adopt a policy of only using setter methods to change a property from the outside.
## Since PHP 8.1 there are implemented native readonly properties [Documentation](https://www.php.net/manual/en/language.oop5.properties.php#language.oop5.properties.readonly-properties) You can initialize readonly property only once during the declaration of the property. ``` class Test { public readonly string $prop; public function __construct(string $prop) { $this->prop = $prop; } } ``` -- ``` class Test { public function __construct( public readonly string $prop, ) {} } ``` Trying to modify the readonly propety will cause following error: ``` Error: Cannot modify readonly property Test::$prop ``` **Update PHP 8.2** Since PHP 8.2 you are able to define as `readonly` a whole class. ``` readonly class Test { public string $prop; public function __construct(string $prop) { $this->prop = $prop; } } ```
PHP Readonly Properties?
[ "", "php", "programming-languages", "" ]
Is there an automatic way to add base classes to Linq2Sql entities? I know I can define a partial and implement that but there has to be an automated way, right?
The LINQ-to-SQL code-generator supports this directly. The base-class for the data-context can be set in the designer, as the `Base Class` property. Alternatively, edit the dbml directly: right click, "Edit With...", "XML Editor" To change the base class for the entities, set the type: ``` <Database EntityBase="Some.NameSpace.Foo" ... > ``` To change the base class for the data-context, set the type: ``` <Database BaseType="Some.NameSpace.Bar" ... > ``` In both cases, use the fully-qualified type in the attribute. Et voila. Note that because it is very literal, you can also use this approach to make your entities implement an interface - for example, when my classes have properties like `LastUpdated` and `UpdatedBy`, I might have an `IAuditable` interface that defines these. Then I can put code in my data-context's `SubmitChanges` (override) that calls `GetChangeSet()` and sets these values for all the `IAuditable` entities being updated; very sweet.
EDIT: [Marc's answer](https://stackoverflow.com/questions/411515/way-to-automatically-add-a-linqtosql-base-class-to-entities#411903) is clearly the right way to go in this case, but I'm leaving this answer here for posterity - it's a handy trick to know about in some cases, where you only need a partial class to change the inheritance/interfaces of a class. I don't know of any automated way, but if you wanted to do this for multiple classes and *only* wanted to specify the base class, you might consider creating a file just for the partial class declarations. I use this approach in Protocol Buffers to make the internal representation classes which are autogenerated implement a particular interface. See [PartialClasses.cs](http://github.com/jskeet/dotnet-protobufs/tree/master/src/ProtocolBuffers/DescriptorProtos/PartialClasses.cs) for this example as code. (Ignore the TODO - it's fixed locally, but I haven't pushed for a little while :)
Way to Automatically Add a LinqToSql base class to Entities?
[ "", "c#", "linq-to-sql", "" ]
I'm working on a java SE 1.5+ swing application, in conjunction with others. I'm wondering what the best way of managing string resources is. I understand the principles behind resource bundles etc. I'd like to avoid having one property file for every class that needs a string, as this seems a bit of overkill. Especially when you have a lot of classes that may only make a single reference to a string (say in an error handler). On the other hand it makes it easier when collaborating with others as you reduce the risk of merge conflicts. It seems particularly cumbersome to have to load resource bundles, every time you need to display simple user feedback, likewise in error handlers, when many classes are involved. What is the most effective way to manage strings in a fairly large application with hundreds of classes, many of which aren't GUI related, but need to pass informative messages back up to the GUI when exceptions occur. I'm using NetBeans which generally creates a property file for each GUI class, for all text relating to buttons, labels etc.
What makes you think you have to have a separate properties file for every class? Generally you only need a few (or just one!) properties file (per language, of course). Just call [`ResourceBundle.getBundle()`](http://java.sun.com/javase/6/docs/api/java/util/ResourceBundle.html) with appropriate parameters - you can use the same bundle from multiple classes. EDIT: Having one set of property files per dialog etc makes it easier to see where any particular string is coming from, but it makes it harder to reuse the same messages etc. Quite where the right balance is will depend on the application.
JSR 296 Swing Application Framework has support for resource management (and it looks like will be part of Java 7). SAF aims to pre-build parts of a Swing app that many people frequently need while encapsulating best practices. You probably don't want to tie to it directly but its worth taking a look at what they do to see whether it gives you some ideas. If I recall, they use cascading resource bundles with well-defined naming conventions. The latter means you know where to look and the former means that you can reuse properties across some portion of your package hierarchy. Many [JSR 296 resources collected here](http://tech.puredanger.com/java7#jsr296).
Management of Java string resources
[ "", "java", "" ]
I need to store some data in a Django model. These data are not equal to all instances of the model. At first I thought about subclassing the model, but I’m trying to keep the application flexible. If I use subclasses, I’ll need to create a whole class each time I need a new kind of object, and that’s no good. I’ll also end up with a lot of subclasses only to store a pair of extra fields. I really feel that a dictionary would be the best approach, but there’s nothing in the Django documentation about storing a dictionary in a Django model (or I can’t find it). Any clues?
If it's really dictionary like arbitrary data you're looking for you can probably use a two-level setup with one model that's a container and another model that's key-value pairs. You'd create an instance of the container, create each of the key-value instances, and associate the set of key-value instances with the container instance. Something like: ``` class Dicty(models.Model): name = models.CharField(max_length=50) class KeyVal(models.Model): container = models.ForeignKey(Dicty, db_index=True) key = models.CharField(max_length=240, db_index=True) value = models.CharField(max_length=240, db_index=True) ``` It's not pretty, but it'll let you access/search the innards of the dictionary using the DB whereas a pickle/serialize solution will not.
Another clean and fast solution can be found here: <https://github.com/bradjasper/django-jsonfield> For convenience I copied the simple instructions. **Install** ``` pip install jsonfield ``` **Usage** ``` from django.db import models from jsonfield import JSONField class MyModel(models.Model): json = JSONField() ```
How to store a dictionary on a Django Model?
[ "", "python", "django", "django-models", "orm", "persistence", "" ]
We have a Perl program to validate XML which is invoked from a Java program. It is not able to write to standard error and hanging in the print location. Perl is writing to STDERR and a java program is reading the STDERR using getErrorStream() function. But the Perl program is hanging to write to STDERR. I suspect Java function is blocking the STDERR stream completely and Perl is waiting for this stream to be released. Is there a way in Perl to overcome this blockage and write to standard error forcefully? Since Java is doing only a read the API should not be locking the STDERR stream as per java doc. Perl Code snippet is: ``` sub print_error { print STDERR shift; } ``` Java code snippet is: ``` while ( getErrorStream() != null ) { SOP errorMessage; } ``` Appreciate the help in advance. Thanks, Mathew Liju
getErrorStream does not *read* the error stream, it just obtains a handle to it. As it's a pipe, if you never actually read it, it will fill up and force the Perl program to block. You need something like: ``` Inputstream errors = getErrorStream(); while (errors.read(buffer) > 0) { SOP buffer; } ```
Ideally, I think that to avoid deadlock, in Java you need to spawn separate threads to read the STDERR and the STDOUT. It sounds like Perl is blocking when writing to STDERR because for one reason or another you are never reading from it in Java.
Why can't my Java program read Perl's STDERR?
[ "", "java", "perl", "stderr", "" ]
Since String implements `IEnumerable<char>`, I was expecting to see the Enumerable extension methods in Intellisense, for example, when typing the period in ``` String s = "asdf"; s. ``` I was expecting to see `.Select<char>(...)`, `.ToList<char>()`, etc. I was then suprised to see that the extension methods **do** in fact work on the string class, they just don't show up in Intellisense. Does anyone know why this is? This may be related to [this](https://stackoverflow.com/questions/295287/how-can-i-prevent-a-public-class-that-provides-extension-methods-from-appearing) question.
It's by explicit design. The problem is that while String most definitely implements `IEnumerable<T>`, most people don't think of it, or more importantly use it, in that way. String has a fairly small number of methods. Initially we did not filter extension methods off of String and the result was a lot of negative feedback. It almost tripled the number of methods at times with the right imports. With all of the extension methods displayed, people often couldn't see the String method they were looking for in the noise. String is a ... simple type and it's better to view it that way :) It's still completely possible to call an extension method on string. It's just likely not going to show up in intellisense. EDIT: String actually has quite a few methods. But because many of them are overloads they collapse in intellisense.
For info, this has changed in VS2010 (in beta 2, at least). It looks like this filtering has been removed (presumably it caused too much confusion), and the methods are now visible, along with the extension-method glyph.
Why doesn't VS 2008 display extension methods in Intellisense for String class
[ "", "c#", "visual-studio-2008", "string", "extension-methods", "intellisense", "" ]
How long do you normally test an update for Zend Framework before pushing it out into a productions project. We can break this question up into minor updates 1.6.0 -> 1.6.1 or maybe a major update 1.6.2 -> 1.7.0. Obviously you don't release it if it add bugs to your code. Also, as with most other server software updates normally people have a window of time they like to wait and watch the community before even attempting an update on a development environment. How long do you even wait to start the process?
It seems like the best method would be to have a comprehensive set of tests that exercised all the functionality in your application. With a good method for testing it seems like you could push it into production pretty quickly. Another simple thing you can do to help you make your decision would be to simply do a diff against the repository to see what changes where applied to any modules that you use. If there where no changes, then upgrading shouldn't make any difference. If something underwent a major re-write, you would probably want to investigate a lot deeper.
I'll often jump through update releases (1.7.1 -> 1.7.2) without much hesitation. When the minors roll in, it's another bag of tricks though. For example, there were a lot of changes with Zend's file upload elements, and Zend form in between 1.5, 1.6 and 1.7. Whether or not I even move on a new release depends on what's been done. Checking the update lists provided is pretty important for deciding on whether or not to go. As for timing, it varies. There's no set in stone process. Finding "what breaks" is quickly accomplished with the unit tests. But, who really has a full set of unit tests for their application, right? ;)
Zend Framework Updates?
[ "", "php", "zend-framework", "" ]
As per c99 standard, size of `long long` should be minimum 64 bits. How is this implemented in a 32 bit machine (eg. addition or multiplication of 2 `long long`s). Also, What is the equivalent of `long long` in C++.
On the IA32 architecture, 64-bit integer are implemented in using two 32-bit registers (eax and edx). There are platform specific equivalents for C++, and you can use the stdint.h header where available (boost provides you with [one](http://www.boost.org/doc/libs/1_37_0/boost/cstdint.hpp)).
The equivalent in C++ is long long as well. It's not required by the standard, but most compilers support it because it's so usefull. How is it implemented? Most computer architectures already have built-in support for multi-word additions and subtractions. They don't do 64 bit addititions directly but use the carry flag and a special add-instruction to build a 64 bit add from two 32 bit adds. The same extension exists for subtraction as well (the carry is called borrow in these cases). Longword multiplications and divisions can be built from smaller multiplications without the help of carry-flags. Sometimes simply doing the operations bit by bit is faster though. There are architectures that don't have any flags at all (some DSP chips and simple micros). On these architectures the overflow has to be detected with logic operations. Multi-word arithmetic tend to be slow on these machines.
long long implementation in 32 bit machine
[ "", "c++", "c", "" ]
I would like to stop images from loading, as in not even get a chance to download, using greasemonkey. Right now I have ``` var images = document.getElementsByTagName('img'); for (var i=0; i<images.length; i++){ images[i].src = ""; } ``` but I don't think this actually stops the images from downloading. Anyone know how to stop the images from loading? Thanks for your time and help :)
Almost all images are not downloaded. So your script almost working as is. I've tested the following script: ``` // ==UserScript== // @name stop downloading images // @namespace http://stackoverflow.com/questions/387388 // @include http://flickr.com/* // ==/UserScript== var images = document.getElementsByTagName('img'); for (var n = images.length; n--> 0;) { var img = images[n]; img.setAttribute("src", ""); } ``` Use a dedicated extension to manage images (something like [ImgLikeOpera](https://addons.mozilla.org/en-US/firefox/addon/1672)). If you'd like to filter images on all browser then a proxy with filtering capabilities might help e.g., [Privoxy](http://www.privoxy.org/).
If you want to disable images downloading for all websites (which I guess you might not be doing) and are using firefox, why not just disable them in preferences? Go to the content tab and switch off "Load images automatically".
Removing images with Greasemonkey?
[ "", "javascript", "greasemonkey", "" ]
Can anyone recommend a good application that could be used to convert VB.NET projects to C#, without having to do too much manual work? We've used Reflector to do small libraries manually, but some of the larger projects will be too slow and complex to do this manually.
You can use Lutz Roeders Reflector (<http://www.red-gate.com/products/reflector>) which can decompile whole Assemblies into Visual Studio projects. This way you can convert from ANY .NET Langauge into one of the supported languages of this program (C#.VB.NET,MC++,Delphi,Chrome)
[Tangible Software](http://tangiblesoftwaresolutions.com/) do various converters, including VB to C#. I've played with it a little bit as they're kind enough to give me a copy for free, but I can't say I've stress-tested it. When I've used it it's been fine though - certainly worth a try.
Convert VB.NET --> C# Projects
[ "", "c#", ".net", "vb.net", "" ]
I have a "fat" GUI that it getting fairly complex, and I would like to add links from a place to an other, and add back/forward buttons to ease navigation. It seems to me that this would be easier if my application was addressable: each composite could have its URI, and links would use that URI. Are there design patterns applicable to this problem? I could just look at the source code for Firefox or Eclipse, but these are huge projects and it would take a good amount of time making sense of it, so I'm asking here. Is there a simpler example somewhere? Of course it would be simpler if I had build a web app in the first place, but I'm not going to rewrite this huge app from scratch anytime soon.
In Swing, you might use a [CardLayout](http://java.sun.com/javase/6/docs/api/java/awt/CardLayout.html). You can have each "page" be a card, and the name of the card (chosen when adding cards to the layout) would be equivalent to the URI you want. Example: ``` String PAGE_1_KEY = "page 1"; String PAGE_2_KEY = "page 2"; // as many keys as you need JFrame frame = ...; frame.setLayout(new CardLayout()); frame.add(createPage1(), PAGE_1_KEY); frame.add(createPage2(), PAGE_2_KEY); // etc. ``` Then in your buttons' action listeners, you would call ``` ((CardLayout)frame.getLayout()).show(frame, PAGE_1_KEY); // or whichever ```
My last approach included global manager and registration of links. Each part of UI was able to name yourself uniquely and register. The global manager knows about each one and then use some dirty work to bring this part visible. The back/forward navigation was made by special undo/redo manager. Each "display" was able to obtain navigation manager and register its "undo" event. It was hard work to make it work, but the resulting feature was quite useful. We discussed about using some simple JNDI service to locate and name UI parts. It may be useful in linking too.
How do you make a Swing/JFace/SWT GUI addressable?
[ "", "java", "user-interface", "design-patterns", "swing", "" ]
is there a way to make the datatextfield property of a dropdownlist in asp.net via c# composed of more than one property of an object? ``` public class MyObject { public int Id { get; set; } public string Name { get; set; } public string FunkyValue { get; set; } public int Zip { get; set; } } protected void Page_Load(object sender, EventArgs e) { List<MyObject> myList = getObjects(); ddList.DataSource = myList; ddList.DataValueField = "Id"; ddList.DataTextField = "Name"; ddList.DataBind(); } ``` I want e.g. not use "Name", but "Name (Zip)" eg. Sure, i can change the MyObject Class, but i don't want to do this (because the MyObject Class is in a model class and should not do something what i need in the UI).
Add another property to the MyObject class and bind to that property : ``` public string DisplayValue { get { return string.Format("{0} ({1})", Name, Zip); } } ``` Or if you can not modify MyObject, create a wrapper object in the presentation layer (just for displaying). This can also be done using some LINQ: ``` List<MyObject> myList = getObjects(); ddList.DataSource = (from obj in myList select new { Id = obj.Id, Name = string.Format("{0} ({1})", obj.Name, obj.Zip) }).ToList(); ddList.DataValueField = "Id"; ddList.DataTextField = "Name"; ddList.DataBind(); ``` (sorry I don't have Visual Studio available, so there might be errors in the code)
I would recommend reading this: <http://martinfowler.com/eaaDev/PresentationModel.html> Essentially you want to create a class that represents binding to a particular UI. So you would map your Model (My Object in your example) to a ViewModel object, and then bind the drop down list that way. It's a cool way to think about separation of concerns. EDIT: Here is another blog series on ViewModel: <http://blogs.msdn.com/dancre/archive/2006/10/11/datamodel-view-viewmodel-pattern-series.aspx>
dropdownlist DataTextField composed from properties?
[ "", "c#", "asp.net", "data-binding", "drop-down-menu", "" ]
This is a complex question, please consider carefully before answering. Consider this situation. Two threads (a reader and a writer) access a single global `int`. Is this safe? Normally, I would respond without thought, yes! However, it seems to me that Herb Sutter doesn't think so. In his articles on effective concurrency he discusses a [flawed lock-free queue](http://www.ddj.com/cpp/210600279) and the [corrected version](http://www.ddj.com/hpc-high-performance-computing/210604448). In the end of the first article and the beginning of the second he discusses a rarely considered trait of variables, write ordering. Int's are atomic, good, but ints aren't necessarily ordered which could destroy any lock-free algorithm, including my above scenario. I fully agree that the only way to ***guarantee*** correct multithreaded behavior on all platforms present and future is to use atomics(AKA memory barriers) or mutexes. My question; is write re-odering ever a problem on real hardware? Or is the multithreaded paranoia just being pedantic? What about classic uniprocessor systems? What about simpler RISC processors like an embedded power-pc? *Clarification*: I'm more interested in what Mr. Sutter said about the hardware (processor/cache) reordering variable writes. I can stop the optimizer from breaking code with compiler switches or hand inspection of the assembly post-compilation. However, I'd like to know if the hardware can still mess up the code in practice.
Your idea of inspecting the assembly is not good enough; the reordering can happen at the hardware level. To answer your question "is this ever a problem on read hardware:" **Yes!** In fact I've run into that problem myself. Is it OK to skirt the issue with uniprocessor systems or other special-case situations? I would argue "no" because five years from now you might need to run on multi-core after all, and then finding all these locations will be tricky (impossible?). One exception: Software designed for embedded hardware applications where indeed you have completely control over the hardware. In fact I have "cheated" like this in those situations on e.g. an ARM processor.
Yup - use memory barriers to prevent instruction reordering where needed. In some C++ compilers, the volatile keyword has been expanded to insert implicit memory barriers for every read and write - but this isn't a portable solution. (Likewise with the Interlocked\* win32 APIs). Vista even adds some new finer-grained Interlocked APIs which let you specify read or write semantics. Unfortunately, C++ has such a loose memory model that any kind of code like this is going to be non-portable to some extent and you'll have to write different versions for different platforms.
Multithreaded paranoia
[ "", "c++", "c", "multithreading", "hardware", "" ]
If I would write: ``` int selectedChannels = selector.select(); Set selectedKeys = selector.selectedKeys(); if ( selectedChannels != selectedKeys.size() ) { // Selector.select() returned because of a call to Selector.wakeup() // so do synchronization. } // Continue with handling selected channels. ``` would it correctly detect the wakeup-call? **Backgroundinformation:** I'm writing a server which most of the time just receives packets and stores them in a file. Very rarely the application has the need to send itself a special packet. For this it initiates a connection (from a different thread) to the server socket: ``` SocketChannel channel = SocketChannel.open(); channel.configureBlocking( false ); channel.connect( new InetSocketAddress( InetAddress.getLocalHost(), PORT )); selector.wakeup(); SelectionKey key = channel.register( selector, SelectionKey.OP_CONNECT ); ``` The problem is that SelectableChannel.register() might block if the main thread is already in Selector.select(). To prevent this from happening I'm calling Selector.wakeup() which let's the main thread return prematurely from select(). To make sure the other thread has the chance to complete the register-call, I would have to synchronize the main thread, but I would have to do it after **every** return from select(). If I could detect whether it returned from select() because of a wakeup() call, then I could optimize it for just this case. So, in theory the top code snippet should work, but I was wondering whether it would only do so, because it relies on some unspecified behavior? Thanks for any hints.
I would guess that the proposed snippet would not work at all in principle, per the contracts of `Selector#select()` and `Selector#selectedKeys()`. From [Selector](http://java.sun.com/javase/6/docs/api/java/nio/channels/Selector.html): > * The selected-key set is the set of keys such that each key's channel was detected to be ready for at least one of the operations identified in the key's interest set during a prior selection operation. This set is returned by the selectedKeys method. ``` public abstract int select(long timeout) throws IOException Returns: The number of keys, possibly zero, whose ready-operation sets were updated ``` As I read that, the size of the `selectedKeys` set should always equal the number returned by `select` by definition. I have noticed - as you may have as well - that some implementations don't quite follow the documentation, and in fact `selectedKeys` returns all keys with updated ready-operation sets, even if they were not updated during a call to `select`. The only other indicator that the select woke up due to a call to `wakeup` might be that the number of keys is zero; however either method would be unreliable, at best. The usual way to handle this is, as implied, through concurrency control. I wouldn't worry about execution time here; this is a classic example of [premature optimization](http://en.wikipedia.org/wiki/Optimization_(computer_science)#When_to_optimize). Unless you're really worried about single digit microsecond tolerances, you won't notice any slowdown - and if you are worried about that level of tolerance, a `Selector` isn't going to be reliable enough for you anyway. Here's an example of the usual mechanism for this, using a `ReentrantLock` to accomplish the appropriate concurrency: ``` ReentrantLock selectorGuard; Selector selector; private void doSelect() { // Don't enter a select if another thread is in a critical block selectorGuard.lock(); selectorGuard.unlock(); selector.select(); Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator(); while(keyIter.hasNext()) { SelectionKey key = keyIter.next(); keyIter.remove(); // Process key } } private void addToSelector() { // Lock the selector guard to prevent another select until complete selectorGuard.lock(); try { selector.wakeup(); // Do logic that registers channel with selector appropriately } finally { selectorGuard.unlock(); } } ```
If `select()` returns zero, either it timed out or it was woken up.
How to detect a Selector.wakeup call
[ "", "java", "nio", "" ]
Ok, here is my dilemma I have a database set up with about 5 tables all with the exact same data structure. The data is separated in this manner for localization purposes and to split up a total of about 4.5 million records. A majority of the time only one table is needed and all is well. However, sometimes data is needed from 2 or more of the tables and it needs to be sorted by a user defined column. This is where I am having problems. data columns: ``` id, band_name, song_name, album_name, genre ``` MySQL statment: ``` SELECT * from us_music, de_music where `genre` = 'punk' ``` MySQL spits out this error: ``` #1052 - Column 'genre' in where clause is ambiguous ``` Obviously, I am doing this wrong. Anyone care to shed some light on this for me?
I think you're looking for the [UNION](http://dev.mysql.com/doc/refman/5.1/en/union.html) clause, a la ``` (SELECT * from us_music where `genre` = 'punk') UNION (SELECT * from de_music where `genre` = 'punk') ```
It sounds like you'd be happer with a single table. The five having the same schema, and sometimes needing to be presented as if they came from one table point to putting it all in one table. Add a new column which can be used to distinguish among the five languages (I'm assuming it's language that is different among the tables since you said it was for localization). Don't worry about having 4.5 million records. Any real database can handle that size no problem. Add the correct indexes, and you'll have no trouble dealing with them as a single table.
MySQL - Selecting data from multiple tables all with same structure but different data
[ "", "sql", "mysql", "join", "mysql-error-1052", "" ]
I have a C# (2008/.NET 3.5) class library assembly that supports WPF (based on [this article](http://dotupdate.wordpress.com/2007/12/05/how-to-add-a-wpf-control-library-template-to-visual-c-express-2008/)). I've created several windows, and am now attempting to create a common style set for them. However, as it's a class library (instead of a WPF app), I don't have an app.xaml (and its contained Application & corresponding Application.Resources) in which to store these styles for global access. **So:** How can I create a top-level set of style definitions that'll be seen by all xaml files in the assembly, *given that I do not have app.xaml (see above)*? And/or is it possible to *add* a working app.xaml to a class library? FYI, I did try creating a ResourceDictionary in a ResourceDictionary.xaml file, and include it in each window within a "Window.Resources" block. That turned out to solve the styling of Buttons, etc... but not for the enclosing Window. I can put `Style="{StaticResource MyWindowStyle}"` in the Window's opening block, and it compiles and shows up in the VS Design window fine, but during actual runtime I get a parse exception (MyWindowStyle could not be found; I'm guessing Visual Studio sees the dictionary included after the line in question, but the CRL does things more sequentially and therefore hasn't loaded the ResourceDictionary yet). --- Thanks for the ideas, but still no go... apparently a class library does NOT support the generic.xaml usage implicitly. I added generic.xaml to my class library project and set its Build Action to "Resource". It contains: ``` <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Style TargetType="{x:Type Window}" x:Key="MyWindow"> <Setter Property="Background" Value="Black"/> </Style> </ResourceDictionary> ``` The window xaml that I want to have use the theme looks like this: ``` <Window x:Class="MyAssembly.ConfigureGenericButtons" x:ClassModifier="internal" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Style="{StaticResource MyWindow}" Title="ConfigureGenericButtons"> ...Buttons, etc... </Window> ``` Although the VS Design window doesn't show the window using the MyWindow style (ie black background), it compiles fine and starts up. However, when the app containing this class library makes a call that causes this window to display, I get a XamlParseException: > Cannot find resource named '{MyWindow}'. I also tried leaving out the Style parameter, to see if the window would use the style by default (and I tried that both with the x:Key in generic.xaml included and without). No errors, but anything defined in the generic.xaml didn't show up either. Am I doing something wrong here, or any other ideas on how one might allow for common custom styles to be used on a Window (ie, not have to define the styles in each Window's xaml) -- with the caveat that this is NOT an application?
Try adding ``` Style={DynamicResource MyStyle} ``` You cannot use a StaticResource in this case.
This sounds like a job for theming. 1. Add a `/themes/generic.xaml` ResourceDictionary to your project. 2. Add the following to AssemblyInfo.cs: `[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]` 3. ? 4. Profit! Any resources you add to generic will be used by all controls. Also you can make profile specific themes (Luna, Aero etc.) by including a ResourceDictionary file with the correct theme name in the `themes` directory. Heres a link to more info: [Create and apply custom themes](https://web.archive.org/web/20090124183844/http://blog.rioterdecker.net/blogs/chaz/archive/2006/03/06/100.aspx)
Assembly-wide / root-level styles in WPF class library
[ "", "c#", ".net", "wpf", "xaml", "" ]
Can you recommend a minimalistic python webserver that I can embedded in my Desktop Application.
How minimalistic and for what purpose? [SimpleHTTPServer](https://docs.python.org/2/library/simplehttpserver.html) comes free as part of the standard Python libraries. If you need more features, look into [CherryPy](http://cherrypy.org/) or (at the top end) [Twisted](http://twistedmatrix.com/trac/).
I'm becoming a big fan of the newly released [circuits](http://trac.softcircuit.com.au/circuits "circuits") library. It's a component/event framework that comes with a very nice set of packages for creating web servers & apps. Here's the simple web example from the site: ``` from circuits.lib.web import Server, Controller class HelloWorld(Controller): def index(self): return "Hello World!" server = Server(8000) server += HelloWorld() server.run() ``` Its WSGI support is no more complicated than that, either. Good stuff.
Embedded Web Server in Python?
[ "", "python", "simplehttpserver", "embeddedwebserver", "" ]
I'm a php guy, but I have to do some small project in JSP. I'm wondering if there's an equivalent to htmlentities function (of php) in JSP.
``` public static String stringToHTMLString(String string) { StringBuffer sb = new StringBuffer(string.length()); // true if last char was blank boolean lastWasBlankChar = false; int len = string.length(); char c; for (int i = 0; i < len; i++) { c = string.charAt(i); if (c == ' ') { // blank gets extra work, // this solves the problem you get if you replace all // blanks with &nbsp;, if you do that you loss // word breaking if (lastWasBlankChar) { lastWasBlankChar = false; sb.append("&nbsp;"); } else { lastWasBlankChar = true; sb.append(' '); } } else { lastWasBlankChar = false; // // HTML Special Chars if (c == '"') sb.append("&quot;"); else if (c == '&') sb.append("&amp;"); else if (c == '<') sb.append("&lt;"); else if (c == '>') sb.append("&gt;"); else if (c == '\n') // Handle Newline sb.append("&lt;br/&gt;"); else { int ci = 0xffff & c; if (ci < 160 ) // nothing special only 7 Bit sb.append(c); else { // Not 7 Bit use the unicode system sb.append("&#"); sb.append(new Integer(ci).toString()); sb.append(';'); } } } } return sb.toString(); } ```
> public static String stringToHTMLString(String string) {... The same thing does utility from [commons-lang](http://commons.apache.org/proper/commons-lang/) library: ``` org.apache.commons.lang.StringEscapeUtils.escapeHtml ``` Just export it in custom tld - and you will get a handy method for jsp.
htmlentities equivalent in JSP?
[ "", "java", "jsp", "html-entities", "" ]
What to do when after all probing, a reportedly valid object return 'undefined' for any attribute probed? I use jQuery, `$('selector').mouseover(function() { });` Everything returns 'undefined' for `$(this)` inside the function scope. The selector is a 'area' for a map tag and I'm looking for its parent attributes.
Your question is a bit vague, so maybe you can provide more details? As for finding out about an object and the values of its properties, there are many ways to do it, including using Firebug or some other debug tools, etc. Here is a quick and dirty function that might help get you started until you can provide more details: ``` function listProperties(obj) { var propList = ""; for(var propName in obj) { if(typeof(obj[propName]) != "undefined") { propList += (propName + ", "); } } alert(propList); } ``` That will display a list of the properties of the object that you pass it that are not `undefined`. Hope that helps...
Is `selector` the name of the element? If so then you should reference it as: ``` $('area#selector') ``` or ``` $('#selector') ``` otherwise it will attempt to look for the (non-existent) "selector" HTML tag and, obviously, not find it.
How to do JavaScript object introspection?
[ "", "javascript", "jquery", "introspection", "" ]
I have an datetime object that I want to remove one hour to display the corect time in a different time zone. I am using datetime.addhours(-1) with the -1 being a config value. This works in most cases except when I set the time to 12:59 AM today it displays 11:59 AM today. When it should display 11:59 PM. Is it possible to have addDays() repect the date?
How about using the Subtract function: ``` DateTime.Now.Subtract(new TimeSpan(1, 0, 0)); ```
There's a method that can help you with timezones: ``` TimeZoneInfo.ConvertTime(..) ``` [Linkage](http://msdn.microsoft.com/en-us/library/system.timezoneinfo.converttime.aspx)
Update the date of a datetime object when using datetime.addhours(-1)
[ "", "c#", "" ]
I have an application that uses DataTables to perform grouping, filtering and aggregation of data. I want to replace datatables with my own data structures so we don't have any unnecessary overhead that we get from using datatables. So my question is if Linq can be used to perform the grouping, filtering and aggregation of my data and if it can is the performance comparable to datatables or should I just hunker down and write my own algorithms to do it? Thanks Dan R.
Unless you go for simple classes (POCO etc), your own implementation is likely to have nearly as much overhead as `DataTable`. Personally, I'd look more at using tools like LINQ-to-SQL, Entity Framework, etc. Then you can use either LINQ-to-Objects against local data, or the provider-specific implementation for complex database queries without pulling all the data to the client. LINQ-to-Objects can *do* all the things you mention, but it involves having all the data in memory. If you have non-trivial data, a database is recommended. SQL Server Express Edition would be a good starting point if you look at LINQ-to-SQL or Entity Framework. --- Edited re comment: Regular TSQL commands are fine and dandy, but you ask about the difference... the biggest being that LINQ-to-SQL will provide the entire DAL for you, which is a huge time saver, as well as making it possible to get a lot more compile-time safety. But is also allows you to use the same approach to look at your local objects and your database - for example, the following is valid C# 3.0 (except for [someDataSource], see below): ``` var qry = from row in [someDataSource] group row by row.Category into grp select new {Category = grp.Key, Count = grp.Count(), TotalValue = grp.Sum(x=>x.Value) }; foreach(var x in qry) { Console.WriteLine("{0}, {1}, {2}", x.Category, x.Count, x.TotalValue); } ``` If [someDataSource] is local data, such as a `List<T>`, this will execute locally; but if this is from your LINQ-to-SQL data-context, it can build the appropriate TSQL at the database server. This makes it possible to use a single query mechanism in your code (within the bounds of [LOLA](http://www.joelonsoftware.com/articles/LeakyAbstractions.html), of course).
You'd be better off letting your database handle grouping, filtering and aggregation. DataTables are actually relatively good at this sort of thing (their bad reputation seems to come primarily from inappropriate usage), but not as good as an actual database. Moreover, without a *lot* of work on your part, I would put my money on the DataTable's having better performance than your homegrown data structure.
A Better DataTable
[ "", "c#", "linq", "" ]
Given a method `DoSomething` that takes a (parameterless) function and handles it in some way. Is there a better way to create the "overloads" for functions with parameters than the snippet below? ``` public static TResult DoSomething<TResult>(Func<TResult> func) { //call func() and do something else } public static TResult DoSomething<T0, TResult>( Func<T0, TResult> func, T0 arg0) { return DoSomething(() => func(arg0)); } public static TResult DoSomething<T0, T1, TResult>( Func<T0, T1, TResult> func, T0 arg0, T1 arg1) { return DoSomething(arg => func(arg, arg1), arg0); } public static TResult DoSomething<T0, T1, T2, TResult>( Func<T0, T1, T2, TResult> func, T0 arg0, T1 arg1, T2 arg2) { return DoSomething(arg => func(arg, arg1, arg2), arg0); } ```
EDIT: As noted in comments, this is partial application rather than currying. I wrote a [blog post on my understanding of the difference](http://codeblog.jonskeet.uk/2012/01/30/currying-vs-partial-function-application/), which folks may find interesting. Well, it's not particularly different - but I'd separate out the currying part from the "calling DoSomething" part: ``` public static Func<TResult> Apply<TResult, TArg> (Func<TArg, TResult> func, TArg arg) { return () => func(arg); } public static Func<TResult> Apply<TResult, TArg1, TArg2> (Func<TArg1, TArg2, TResult> func, TArg1 arg1, TArg2 arg2) { return () => func(arg1, arg2); } // etc ``` Then: ``` DoSomething(Apply(foo, 1)); ``` That way you can reuse the currying code in other situations - including cases where you don't want to call the newly-returned delegate immediately. (You might want to curry it more later on, for example.)
The @Jon Skeet answer is right, but write by hand all possibles overload is something insane, so you can use a lib like [Curryfy](https://github.com/leandromoh/Curryfy) that do this job for you. Curryfy lib particularly exposes Curry, UnCurry and ApplyPartial extension methods, with a lot of overloads.
Proper Currying in C#
[ "", "c#", "lambda", "currying", "" ]
Given a table such as: ``` CREATE TABLE dbo.MyTestData (testdata varchar(50) NOT NULL) ALTER TABLE dbo.MyTestData WITH NOCHECK ADD CONSTRAINT [PK_MyTestData] PRIMARY KEY CLUSTERED (testdata) ``` And given that we want a unique list of 'testdata' when we are done gathering items to be added from a list of external data with known duplicates... When performing an insert stored procedure should the procedure be written to test for existence or should it just allow for error? What's the most common practice? I've always performed the test for existence but was debating this last night... ``` CREATE PROCEDURE dbo.dmsInsertTestData @ptestdata VarChar(50) AS SET NOCOUNT ON IF NOT EXISTS(SELECT testdata FROM dbo.MyTestData WHERE testdata=@ptestdata) BEGIN INSERT INTO dbo.MyTestData (testdata ) VALUES (@ptestdata) END RETURN 0 ``` or just capture/ignore PK violation errors when executing this one? ``` CREATE PROCEDURE dbo.dmsInsertTestData @ptestdata VarChar(50) AS SET NOCOUNT ON INSERT INTO dbo.MyTestData (testdata ) VALUES (@ptestdata) RETURN 0 ```
I always do it in one statement: ``` INSERT INTO dbo.MyTestData (testdata ) VALUES (@ptestdata) WHERE NOT EXISTS(SELECT 1 FROM dbo.MyTestData WHERE testdata=@ptestdata) ```
Your check for errors (i.e. "IF NOT EXISTS ...") may or may not work, because there's a potential race condition (if another transaction inserts the record after your IF NOT EXISTS statement but before your INSERT statement). Therefore, whether or not you check before, you ought to code your INSERT statement as if it might fail. Whether you want to check **as well** (not, instead) is up to you and up to your UI.
Inserting data into SQL Table with Primary Key. For dupes - allow insert error or Select first?
[ "", "sql", "insert", "" ]
I am trying to write a textbox that will search on 5 DB columns and will return every result of a given search, ex. "Red" would return: red ball, Red Williams, etc. Any examples or similar things people have tried. My example code for the search. Thanks. ``` ItemMasterDataContext db = new ItemMasterDataContext(); string s = txtSearch.Text.Trim(); var q = from p in db.ITMSTs where p.IMITD1.Contains(s) || p.IMITD2.Contains(s) || p.IMMFNO.Contains(s) || p.IMITNO.Contains(s) || p.IMVNNO.Contains(s) select p; lv.DataSource = q; lv.DataBind(); ```
You can do something like this (syntax may be off ) ``` using(var db = new ItemMasterDataContext()) { var s = txtSearch.Text.Trim(); var result = from p in db.ITMSTs select p; if( result.Any(p=>p.IMITD1.Contains(s)) lv.DataSource = result.Where(p=>p.IMITD1.Contains(s)) else if ( result.Any(p=>p.IMITD2.Contains(s)) lv.DataSource = result.Where(p=>p.IMITD1.Contains(s)) lv.DataBind(); } ``` or you might want to use this [Link](http://msdn.microsoft.com/en-us/library/bb345073.aspx) or this [Link](http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression.orelse.aspx) from MSDN. Happy Coding!!
"q" in your example will be an `IQueryable<ITMST>`. I don't think the Datasource property of WebControl know what to do with that. try writing that line as: ``` lv.DataSource = q.ToList(); ```
LINQ Query to Return multiple results
[ "", "c#", "asp.net", "linq", "sql-server-2000", "" ]
I've written this to try and log onto a forum (phpBB3). ``` import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata]) output = page.read() ``` However when I run it it comes up with; ``` Traceback (most recent call last): File "C:/Users/Mike/Documents/python/test urllib2", line 4, in <module> page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata]) TypeError: string indices must be integers ``` any ideas as to how to solve this? *edit* adding a comma between the string and the data gives this error instead ``` Traceback (most recent call last): File "C:/Users/Mike/Documents/python/test urllib2", line 4, in <module> page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login",[logindata]) File "C:\Python25\lib\urllib.py", line 84, in urlopen return opener.open(url, data) File "C:\Python25\lib\urllib.py", line 192, in open return getattr(self, name)(url, data) File "C:\Python25\lib\urllib.py", line 327, in open_http h.send(data) File "C:\Python25\lib\httplib.py", line 711, in send self.sock.sendall(str) File "<string>", line 1, in sendall TypeError: sendall() argument 1 must be string or read-only buffer, not list ``` *edit2* I've changed the code from what it was to; ``` import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib2.urlopen("http://www.woarl.com/board/ucp.php?mode=login", logindata) output = page.read() ``` This doesn't throw any error messages, it just gives 3 blank lines. Is this because I'm trying to read from the log in page which disappears after logging in. If so how do I get it to display the index which is what should appear after hitting log in.
Your line ``` page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata]) ``` is semantically invalid Python. Presumably you meant ``` page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login", [logindata]) ``` which has a comma separating the arguments. However, what you ACTUALLY want is simply ``` page = urllib2.urlopen("http://www.woarl.com/board/ucp.php?mode=login", logindata) ``` without trying to enclose logindata into a list and using the more up-to-date version of urlopen is the urllib2 library.
Your URL string shouldn't be ``` "http://www.woarl.com/board/ucp.php?mode=login"[logindata] ``` But ``` "http://www.woarl.com/board/ucp.php?mode=login", logindata ``` I think, because [] is for array and it require an integer. I might be wrong cause I haven't done a lot of Python.
python logging into a forum
[ "", "python", "authentication", "phpbb3", "typeerror", "" ]
Take the method System.Windows.Forms.Control.Invoke(Delegate method) Why does this give a compile time error: ``` string str = "woop"; Invoke(() => this.Text = str); // Error: Cannot convert lambda expression to type 'System.Delegate' // because it is not a delegate type ``` Yet this works fine: ``` string str = "woop"; Invoke((Action)(() => this.Text = str)); ``` When the method expects a plain Delegate?
A lambda expression can either be converted to a delegate type or an expression tree - but it has to know *which* delegate type. Just knowing the signature isn't enough. For instance, suppose I have: ``` public delegate void Action1(); public delegate void Action2(); ... Delegate x = () => Console.WriteLine("hi"); ``` What would you expect the concrete type of the object referred to by `x` to be? Yes, the compiler *could* generate a new delegate type with an appropriate signature, but that's rarely useful and you end up with less opportunity for error checking. If you want to make it easy to call `Control.Invoke` with an `Action` the easiest thing to do is add an extension method to Control: ``` public static void Invoke(this Control control, Action action) { control.Invoke((Delegate) action); } ```
Tired of casting lambdas over and over? ``` public sealed class Lambda<T> { public static Func<T, T> Cast = x => x; } public class Example { public void Run() { // Declare var c = Lambda<Func<int, string>>.Cast; // Use var f1 = c(x => x.ToString()); var f2 = c(x => "Hello!"); var f3 = c(x => (x + x).ToString()); } } ```
Why must a lambda expression be cast when supplied as a plain Delegate parameter
[ "", "c#", "c#-3.0", "delegates", "lambda", "" ]
I have an associative array, ie ``` $primes = array( 2=>2, 3=>3, 5=>5, 7=>7, 11=>11, 13=>13, 17=>17, // ...etc ); ``` then I do ``` // seek to first prime greater than 10000 reset($primes); while(next($primes) < 10000) {} prev($primes); // iterate until target found while($p = next($primes)) { $res = doSomeCalculationsOn($p); if( IsPrime($res) ) return $p; } ``` The problem is that IsPrime also loops through the $primes array, ``` function IsPrime($num) { global $primesto, $primes, $lastprime; if ($primesto >= $num) // using the assoc array lets me do this as a lookup return isset($primes[$num]); $root = (int) sqrt($num); if ($primesto < $root) CalcPrimesTo($root); foreach($primes as $p) { // <- Danger, Will Robinson! if( $num % $p == 0 ) return false; if ($p >= $root) break; } return true; } ``` which trashes the array pointer I am iterating on. I would like to be able to save and restore the array's internal pointer in the IsPrime() function so it doesn't have this side effect. Is there any way to do this?
Don't rely on array pointers. Use iterators instead. You can replace your outer code with: ``` foreach ($primes as $p) { if ($p > 10000 && IsPrime(doSomeCalculationsOn($p))) { return $p; } } ```
You can "save" the state of the array: ``` $state = key($array); ``` And "restore" (not sure if there's a better method): ``` reset($array); while(key($array) != $state) next($array); ```
How to store and reset a PHP array pointer?
[ "", "php", "arrays", "loops", "" ]
I need help to replace all \n (new line) caracters for in a String, but not those \n inside [code][/code] tags. My brain is burning, I can't solve this by my own :( Example: ``` test test test test test test test test [code]some test code [/code] more text ``` Should be: ``` test test test<br /> test test test<br /> test<br /> test<br /> <br /> [code]some test code [/code]<br /> <br /> more text<br /> ``` Thanks for your time. Best regards.
I would suggest a (simple) parser, and not a regular expression. Something like this (bad pseudocode): ``` stack elementStack; foreach(char in string) { if(string-from-char == "[code]") { elementStack.push("code"); string-from-char = ""; } if(string-from-char == "[/code]") { elementStack.popTo("code"); string-from-char = ""; } if(char == "\n" && !elementStack.contains("code")) { char = "<br/>\n"; } } ```
You've tagged the question regex, but this may not be the best tool for the job. You might be better using basic compiler building techniques (i.e. a lexer feeding a simple state machine parser). Your lexer would identify five tokens: ("[code]", '\n', "[/code]", EOF, :all other strings:) and your state machine looks like: ``` state token action ------------------------ begin :none: --> out out [code] OUTPUT(token), --> in out \n OUTPUT(break), OUTPUT(token) out * OUTPUT(token) in [/code] OUTPUT(token), --> out in * OUTPUT(token) * EOF --> end ``` EDIT: I see other poster discussing the possible need for nesting the blocks. This state machine won't handle that. For nesting blocks, use a recursive decent parser (not quite so simple but still easy enough and extensible). EDIT: Axeman notes that this design excludes the use of "[/code]" in the code. An escape mechanism can be used to beat this. Something like add '\' to your tokens and add: ``` state token action ------------------------ in \ -->esc-in esc-in * OUTPUT(token), -->in out \ -->esc-out esc-out * OUTPUT(token), -->out ``` to the state machine. The usual arguments in favor of machine generated lexers and parsers apply.
Regex to replace all \n in a String, but no those inside [code] [/code] tag
[ "", "java", "regex", "" ]
I'm trying to do a Data Binding in the C# code behind rather than the XAML. The XAML binding created in Expression Blend 2 to my CLR object works fine. My C# implementation only updates when the application is started after which subsequent changes to the CLR doesn't update my label content. Here's the working XAML binding. First a ObjectDataProvider is made in my Window.Resources. ``` <ObjectDataProvider x:Key="PhoneServiceDS" ObjectType="{x:Type kudu:PhoneService}" d:IsDataSource="True"/> ``` And the label content binding: ``` <Label x:Name="DisplayName" Content="{Binding Path=MyAccountService.Accounts[0].DisplayName, Mode=OneWay, Source={StaticResource PhoneServiceDS}}"/> ``` Works great. But we want this set up in C# so we can independently change the XAML (ie. new skins). My one time working C# as follows: ``` Binding displayNameBinding = new Binding(); displayNameBinding.Source = PhoneService.MyAccountService.Accounts[0].DisplayName; displayNameBinding.Mode = BindingMode.OneWay; this.DisplayName.SetBinding(Label.ContentProperty, displayNameBinding); ``` This is inside my MainWindow after InitializeComponent(); Any insight why this only works on startup?
Your C# version does not match the XAML version. It should be possible to write a code version of your markup, though I am not familiar with ObjectDataProvider. Try something like this: ``` Binding displayNameBinding = new Binding( "MyAccountService.Accounts[0].DisplayName" ); displayNameBinding.Source = new ObjectDataProvider { ObjectType = typeof(PhoneService), IsDataSource = true }; displayNameBinding.Mode = BindingMode.OneWay; this.DisplayName.SetBinding(Label.ContentProperty, displayNameBinding); ```
In the priginal code you have confused the source and path. ``` Binding displayNameBinding = new Binding(); displayNameBinding.Source = PhoneService; displayNameBinding.Path = "MyAccountService.Accounts[0].DisplayName"; displayNameBinding.Mode = BindingMode.OneWay; this.DisplayName.SetBinding(Label.ContentProperty, displayNameBinding); ``` (I assume PhoneService is an object instance, otherwise perhaps PhoneService. MyAccountService.Accounts[0] should be the Source?) From memory, you can pass the path as an argument to the constructor.
C# data binding doesn't update WPF
[ "", "c#", ".net", "data-binding", "xaml", "code-behind", "" ]
I'm looking at building an API and was considering oauth for managing access to the api, but what I'm doing is more of a b2b system allowing businesses to access data to incorporate into their sites. I won't have any b2c at the beginning. So oauth doesn't seem like the right tool for me, I've been looking for sources regarding building a key based system, but haven't come across anything. Is something available out there already? Is it best to just create a hash of some user submitted data or something like that?
What you need is just something that uniquely identifies the user... Just use a UUID or maybe a hash of a UUID. Just make sure that this ID is passed over a secure channel, if you are passing it over an insecure channel you may need to implement some method of securing the ID similar to HTTP digest auth.
Take a look at almost any Web 2.0 site/service. They all have varying degrees of doing auth and managing API keys. Flickr, Twitter, Github, etc.
How do you manage api keys
[ "", "php", "api", "oauth", "key", "" ]
I'm trying to loop through items of a checkbox list. If it's checked, I want to set a value. If not, I want to set another value. I was using the below, but it only gives me checked items: ``` foreach (DataRowView myRow in clbIncludes.CheckedItems) { MarkVehicle(myRow); } ```
``` for (int i = 0; i < clbIncludes.Items.Count; i++) if (clbIncludes.GetItemChecked(i)) // Do selected stuff else // Do unselected stuff ``` If the the check is in indeterminate state, this will still return true. You may want to replace ``` if (clbIncludes.GetItemChecked(i)) ``` with ``` if (clbIncludes.GetItemCheckState(i) == CheckState.Checked) ``` if you want to only include actually checked items.
This will give a list of selected ``` List<ListItem> items = checkboxlist.Items.Cast<ListItem>().Where(n => n.Selected).ToList(); ``` This will give a list of the selected boxes' values (change Value for Text if that is wanted): ``` var values = checkboxlist.Items.Cast<ListItem>().Where(n => n.Selected).Select(n => n.Value ).ToList() ```
How to loop through a checkboxlist and to find what's checked and not checked?
[ "", "c#", ".net", "checkboxlist", "" ]
I have LINQ statement that looks like this: ``` return ( from c in customers select new ClientEntity() { Name = c.Name, ... }); ``` I'd like to be able to abstract out the select into its own method so that I can have different "mapping" option. What does my method need to return? In essence, I'd like my LINQ query to look like this: ``` return ( from c in customers select new Mapper(c)); ``` **Edit:** This is for LINQ to SQL.
New answer now I've noticed that it's Linq to SQL... :) If you look at the version of Select that works on `IQueryable<T>` it doesn't take a `Func<In, Out>`. Instead, it takes an `Expression<Func<In, Out>>`. The compiler knows how to generate such a thing from a lambda, which is why your normal code compiles. So to have a variety of select mapping functions ready to use by passing them to Select, you could declared them like this: ``` private static readonly Expression<Func<CustomerInfo, string>> GetName = c => c.Name; private static readonly Expression<Func<CustomerInfo, ClientEntity>> GetEntity = c => new ClientEntity { Name = c.Name, ... }; ``` You would then use them like this: ``` var names = customers.Select(GetName); var entities = customers.Select(GetEntity); ```
You might have to use chained methods instead of using LINQ syntax, and then you'll be able to pass in any of a variety of [`Expression`](http://msdn.microsoft.com/en-us/library/bb335710.aspx)`<`[`Func<TSource, TResult>`](http://msdn.microsoft.com/en-us/library/bb549151.aspx)`>` values that you specify: ``` Expression<Func<CustomerTable, Customer>> someMappingExpression = c => new Customer { Name = c.Name }; return context.CustomerTable.Select(someMappingExpression); ``` **UPDATE:** [`Select`](http://msdn.microsoft.com/en-us/library/bb548891.aspx) takes a `Func`, not an `Expression` **UPDATE:** The [`Select`](http://msdn.microsoft.com/en-us/library/bb548743.aspx) function that should be used *does* take an `Expression<Func>`, rather than just a `Func`.
Encapsulating LINQ select statement
[ "", "c#", "linq", "linq-to-sql", "" ]
What is the most efficient way to convert data from nested lists to an object array (which can be used i.e. as data for JTable)? ``` List<List> table = new ArrayList<List>(); for (DATAROW rowData : entries) { List<String> row = new ArrayList<String>(); for (String col : rowData.getDataColumn()) row.add(col); table.add(row); } // I'm doing the conversion manually now, but // I hope that there are better ways to achieve the same Object[][] finalData = new String[table.size()][max]; for (int i = 0; i < table.size(); i++) { List<String> row = table.get(i); for (int j = 0; j < row.size(); j++) finalData[i][j] = row.get(j); } ``` Many thanks!
``` //defined somewhere List<List<String>> lists = .... String[][] array = new String[lists.size()][]; String[] blankArray = new String[0]; for(int i=0; i < lists.size(); i++) { array[i] = lists.get(i).toArray(blankArray); } ``` I don't know anything about JTable, but converting a list of lists to array can be done with a few lines.
For `JTable` in particular, I'd suggest subclassing `AbstractTableModel` like so: ``` class MyTableModel extends AbstractTableModel { private List<List<String>> data; public MyTableModel(List<List<String>> data) { this.data = data; } @Override public int getRowCount() { return data.size(); } @Override public int getColumnCount() { return data.get(0).size(); } @Override public Object getValueAt(int row, int column) { return data.get(row).get(column); } // optional @Override public void setValueAt(Object aValue, int row, int column) { data.get(row).set(column, aValue); } } ``` Note: this is the most basic implementation possible; error-checking is omitted for brevity. Using a model like this, you don't have to worry about pointless conversions to `Object[][]`.
Java nested list to array conversion
[ "", "java", "arrays", "list", "jtable", "" ]
I am developing a scientific application used to perform physical simulations. The algorithms used are O(n3), so for a large set of data it takes a very long time to process. The application runs a simulation in around 17 minutes, and I have to run around 25,000 simulations. That is around one year of processing time. The good news is that the simulations are completely independent from each other, so I can easily change the program to distribute the work among multiple computers. There are multiple solutions I can see to implement this: * Get a multi-core computer and distribute the work among all the cores. Not enough for what I need to do. * Write an application that connects to multiple "processing" servers and distribute the load among them. * Get a cluster of cheap linux computers, and have the program treat everything as a single entity. Option number 2 is relatively easy to implement, so I don't look so much for suggestions for how to implement this (Can be done just by writing a program that waits on a given port for the parameters, processes the values and returns the result as a serialized file). That would be a good example of [Grid Computing](http://en.wikipedia.org/wiki/Grid_computing "Grid Computing"). However, I wonder at the possibilities of the last option, a traditional cluster. How difficult is to run a Java program in a linux grid? Will all the separate computers be treated as a single computer with multiple cores, making it thus easy to adapt the program? Is there any good pointers to resources that would allow me to get started? Or I am making this over-complicated and I am better off with option number 2? EDIT: As extra info, I am interested on how to implement something like described in this article from Wired Magazine: [Scientific replaced a supercomputer with a Playstation 3 linux cluster](http://www.wired.com/techbiz/it/news/2007/10/ps3_supercomputer). Definitively number two sounds like the way to go... but the coolness factor. EDIT 2: The calculation is very CPU-Bound. Basically there is a lot of operations on large matrixes, such as inverse and multiplication. I tried to look for better algorithms for these operations but so far I've found that the operations I need are 0(n3) (In libraries that are normally available). The data set is large (for such operations), but it is created on the client based on the input parameters. --- I see now that I had a misunderstanding on how a computer cluster under linux worked. I had the assumption that it would work in such a way that it would just appear that you had all the processors in all computers available, just as if you had a computer with multiple cores, but that doesn't seem to be the case. It seems that all these supercomputers work by having nodes that execute tasks distributed by some central entity, and that there is several different libraries and software packages that allow to perform this distribution easily. So the question really becomes, as there is no such thing as number 3, into: What is the best way to create a clustered java application?
I would very highly recommend the Java Parallel Processing Framework especially since your computations are already independant. I did a good bit of work with this undergraduate and it works very well. The work of doing the implementation is already done for you so I think this is a good way to achieve the goal in "number 2." <http://www.jppf.org/>
Number 3 isn't difficult to do. It requires developing two distinct applications, the client and the supervisor. The client is pretty much what you have already, an application that runs a simulation. However, it needs altering so that it connects to the supervisor using TCP/IP or whatever and requests a set of simulation parameters. It then runs the simulation and sends the results back to the supervisor. The supervisor listens for requests from the clients and for each request, gets an unallocated simulation from a database and updates the database to indicate the item is allocated but unfinished. When the simulation is finished, the supervisor updates the database with the result. If the supervisor stores the data in an actual database (MySql, etc) then the database can be easily queried for the current state of the simulations. This should scale well up to the point where the time taken to provide the simulation data to all the clients is equal to the time required to perform the simulation.
How to create a Linux cluster for running physics simulations in java?
[ "", "java", "linux", "cluster-computing", "grid-computing", "playstation", "" ]
I have a list of booleans where occasionally I reset them all to false. After first writing the reset as: ``` for b in bool_list: b = False ``` I found it doesn't work. I spent a moment scratching my head, then remembered that of course it won't work since I'm only changing a reference to the bool, not its value. So I rewrote as: ``` for i in xrange(len(bool_list)): bool_list[i] = False ``` and everything works fine. But I found myself asking, "Is that really the most pythonic way to alter all elements of a list?" Are there other ways that manage to be either more efficient or clearer?
``` bool_list[:] = [False] * len(bool_list) ``` or ``` bool_list[:] = [False for item in bool_list] ```
If you only have one reference to the list, the following may be easier: ``` bool_list = [False] * len(bool_list) ``` This creates a new list populated with `False` elements. See my answer to [Python dictionary clear](https://stackoverflow.com/questions/369898/python-dictionary-clear#369925) for a similar example.
Alter elements of a list
[ "", "python", "coding-style", "" ]