Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
First off, the mousewheel event is not listed in Visual Studio 2008's events pane which is very annoying. I found the correct format online though, and wrote this into my code: ``` private void Form1_MouseWheel(object sender, MouseEventArgs e) { Debug.WriteLine("Foo"); } ``` ...from which I'm getting no response when the mousewheel is rotated. I'm doing this in my code's main class area, and the designer contains only the one form/window/whatever so the mouse isn't losing focus. ``` namespace BlahBlah { public partial class Form1 : Form { ``` And by contrast, I have this method right above the mousewheel one and it works fine: ``` private void Form1_MouseClick(object sender, MouseEventArgs e) { Debug.WriteLine("Foo"); } ``` If I had to guess, I'm thinking I'm not correctly linking the code to the form (aka: all the stuff that visual studio would do for me if I added this event through the designer's events panel). But I could be wrong or just be making some silly error. Can you help me get ANY kind of response when the mouse wheel is rotated? Thanks!
The mousewheel event needs to be set up. Add this to Form1's constructor (After InitalizeComponents();) ``` this.MouseWheel+= new MouseEventHandler(Form1_MouseWheel); ```
I don't have enough reputation to respond with a comment, but the answer to your side question is that the delegates do need to be setup. However when you create one by double clicking it in the properties pane the code is automatically generated and placed in the \*.designer.cs file in the InitializeComponent method.
Can't fire MouseWheel event in C# Windows Forms
[ "", "c#", "winforms", "visual-studio-2008", "mousewheel", "" ]
I've been reading about Python's [multiprocessing module](http://docs.python.org/library/multiprocessing.html). I still don't think I have a very good understanding of what it can do. Let's say I have a quadcore processor and I have a list with 1,000,000 integers and I want the sum of all the integers. I could simply do: ``` list_sum = sum(my_list) ``` But this only sends it to one core. Is it possible, using the multiprocessing module, to divide the array up and have each core get the sum of it's part and return the value so the total sum may be computed? Something like: ``` core1_sum = sum(my_list[0:500000]) #goes to core 1 core2_sum = sum(my_list[500001:1000000]) #goes to core 2 all_core_sum = core1_sum + core2_sum #core 3 does final computation ``` Any help would be appreciated.
Yes, it's possible to do this summation over several processes, very much like doing it with multiple threads: ``` from multiprocessing import Process, Queue def do_sum(q,l): q.put(sum(l)) def main(): my_list = range(1000000) q = Queue() p1 = Process(target=do_sum, args=(q,my_list[:500000])) p2 = Process(target=do_sum, args=(q,my_list[500000:])) p1.start() p2.start() r1 = q.get() r2 = q.get() print r1+r2 if __name__=='__main__': main() ``` However, it is likely that doing it with multiple processes is likely slower than doing it in a single process, as copying the data forth and back is more expensive than summing them right away.
Welcome the world of concurrent programming. What Python can (and can't) do depends on two things. 1. What the OS can (and can't) do. Most OS's allocate processes to cores. To use 4 cores, you need to break your problem into four processes. This is easier than it sounds. Sometimes. 2. What the underlying C libraries can (and can't) do. If the C libraries expose features of the OS AND the OS exposes features of the hardware, you're solid. To break a problem into multiple processes -- especially in GNU/Linux -- is easy. Break it into a multi-step pipeline. In the case of summing a million numbers, think of the following shell script. Assuming some hypothetical `sum.py` program that sums either a range of numbers or a list of numbers on stdin. ( sum.py 0 500000 & sum.py 50000 1000000 ) | sum.py This would have 3 concurrent processes. Two are doing sums of a lot of numbers, the third is summing two numbers. Since the GNU/Linux shells and the OS already handle some parts of concurrency for you, you can design simple (very, very simple) programs that read from stdin, write to stdout, and are designed to do small parts of a large job. You can try to reduce the overheads by using [subprocess](http://docs.python.org/library/subprocess.html) to build the pipeline instead of allocating the job to the shell. You may find, however, that the shell builds pipelines very, very quickly. (It was written directly in C and makes direct OS API calls for you.)
Python: Multicore processing?
[ "", "python", "multicore", "multiprocessing", "" ]
I recently downloaded the SO Data Dump and was wondering how I could convert it from XML to a DB that I could use in my .NET applications.
Here's a [wiki article](https://web.archive.org/web/20100304111946/http://sqlserverpedia.com/wiki/How_to_Import_the_StackOverflow_XML_into_SQL_Server) describing the process of converting the XML data dump to a database by using stored procedures. [SQLServerPedia site](http://sqlserverpedia.com/) contains many other articles related to SO - * [Understanding the StackOverflow Database Schema](http://sqlserverpedia.com/wiki/Understanding_the_StackOverflow_Database_Schema) * [Interesting StackOverflow Database Queries](http://sqlserverpedia.com/wiki/Interesting_StackOverflow_Database_Queries), etc.
You could try [XML Bulk Load](http://support.microsoft.com/kb/316005).
How to convert XML file to a Database?
[ "", "c#", ".net", "xml", "database", "data-dump", "" ]
Ok simple enough ``` <?PHP echo $_SERVER[REMOTE_ADDR]; ?> ``` Ok maybe not, I my IP is currently **72.184.212.85** however the code above which I am using on an IP blocking system for a script shows my IP as my home server IP of **127.0.0.1** So when I go to my script my IP is shown as **127.0.0.1** but when I go to other websites it is shown as **72.184.212.85** How can I get the first value to show on my test server?
`$_SERVER['REMOTE_ADDR']` will always show the IP address from which the request came. If you access your own script on your own computer within your own network, your external IP address never comes into play. The request would have to leave your local network and then come back in for the external address to show up, but if it's all local, that'll never happen.
You'll have to make your server publicly accessible and then access it from the public address. I'm guessing you're currently using localhost to access your server? run your server say port 8080 and then forward the port in your router so it's public to the internet. Then visit your webpage/phpscript from <http://72.184.212.85:8080> instead of <http://localhost:8080>.
My IP is showing up wrong in PHP home server
[ "", "php", "ip", "" ]
When using an if() statement is it better from a performance perspective to use == or != ``` if(object==null) ``` or ``` if(object!=null) ``` Should the statement w/ the highest probability of success be first in the if() sequence?
I just analysed the following code in .NET Reflector: ``` public static void Main(string[] args) { object obj2 = null; if (obj2 == null) { Console.WriteLine("Is null"); } if (obj2 != null) { Console.WriteLine("Is not null"); } } ``` and here is the resulting IL: ``` .method public hidebysig static void Main(string[] args) cil managed { .custom instance void [mscorlib]System.STAThreadAttribute::.ctor() .maxstack 1 .locals init ( [0] object obj2) L_0000: ldnull L_0001: stloc.0 L_0002: ldloc.0 L_0003: brtrue.s L_000f L_0005: ldstr "Is null" L_000a: call void [mscorlib]System.Console::WriteLine(string) L_000f: ldloc.0 L_0010: brfalse.s L_001c L_0012: ldstr "Is not null" L_0017: call void [mscorlib]System.Console::WriteLine(string) L_001c: ret } ``` From the above it seems that it makes no difference to performance which if() check you use. But, you could look at it this way - try using the if() check which is most likely to occur. So if the object is rarely going to be null at the point of the if check, then use if(object != null).+
I very much doubt you'd ever notice any tangible difference; not least, there is `brtrue` and `brfalse` IL operators... If you have performance issues, use a profiler, and look at **real** problems; this won't be it... it is premature optimisation.
.NET 3.5/C#: Is there a performance difference between if() == and !=
[ "", "c#", ".net", "" ]
I'm trying to add an onclick event to a table row through Javascript. ``` function addRowHandlers() { var table = document.getElementById("tableId"); var rows = table.getElementsByTagName("tr"); for (i = 1; i < rows.length; i++) { row = table.rows[i]; row.onclick = function(){ var cell = this.getElementsByTagName("td")[0]; var id = cell.innerHTML; alert("id:" + id); }; } } ``` This works as expected in Firefox, but in Internet Explorer (IE8) I can't access the table cells. I believe that is somehow related to the fact that "this" in the onclick function is identified as "Window" instead of "Table" (or something like that). If I could access the the current row I could perform a `getElementById` in the onclick function by I can't find a way to do that. Any suggestions?
Something like this. ``` function addRowHandlers() { var table = document.getElementById("tableId"); var rows = table.getElementsByTagName("tr"); for (i = 0; i < rows.length; i++) { var currentRow = table.rows[i]; var createClickHandler = function(row) { return function() { var cell = row.getElementsByTagName("td")[0]; var id = cell.innerHTML; alert("id:" + id); }; }; currentRow.onclick = createClickHandler(currentRow); } } ``` **EDIT** Working [demo](http://jsfiddle.net/oh16h7cj/).
**Simple way is generating code as bellow:** ``` <!DOCTYPE html> <html> <head> <style> table, td { border:1px solid black; } </style> </head> <body> <p>Click on each tr element to alert its index position in the table:</p> <table> <tr onclick="myFunction(this)"> <td>Click to show rowIndex</td> </tr> <tr onclick="myFunction(this)"> <td>Click to show rowIndex</td> </tr> <tr onclick="myFunction(this)"> <td>Click to show rowIndex</td> </tr> </table> <script> function myFunction(x) { alert("Row index is: " + x.rowIndex); } </script> </body> </html> ```
Adding an onclick event to a table row
[ "", "javascript", "html", "dom", "dom-events", "" ]
The question I have is exactly same in requirement as [How to pass mouse events to applications behind mine in C#/Vista?](https://stackoverflow.com/questions/173579/how-to-pass-mouse-events-to-applications-behind-mine-in-c-vista) , but I need the same for a Transparent Java UI. I can easily create a transparent Java UI using 6.0 but couldn't get any info about passing events through the app to any applications(say a browser) behind.
I believe this will answer your question. To run it you will need Java 6 update 10 and above. I tested it on Windows Vista ``` import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JFrame; import javax.swing.JPanel; public class ClickThrough { public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); JFrame f = new JFrame("Test"); f.setAlwaysOnTop(true); Component c = new JPanel() { @Override public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D)g.create(); g2.setColor(Color.gray); int w = getWidth(); int h = getHeight(); g2.fillRect(0, 0, w,h); g2.setComposite(AlphaComposite.Clear); g2.fillRect(w/4, h/4, w-2*(w/4), h-2*(h/4)); } }; c.setPreferredSize(new Dimension(300, 300)); f.getContentPane().add(c); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.pack(); f.setVisible(true); com.sun.awt.AWTUtilities.setWindowOpaque(f,false); } } ``` Note that you need to either have an undecorated window or one that is decorated by Java alone (not the default OS decoration) otherwise the code won't work.
Savvas' answer helped me perfectly even on MacOS X 10.7.3 using Java 1.6.0\_31. Thanks! The only thing: I additionally had to set ``` f.setUndecorated(true); ```
Pass mouse events to applications behind from a Java UI
[ "", "java", "events", "mouse", "transparency", "" ]
I have a class derived from HttpApplication that adds some extra features. I'm to the point where I need to unit test these features, which means I have to be able to create a new instance of the HttpApplication, fake a request, and retrieve the response object. How exactly do I go about unit testing an HttpApplication object? I'm using Moq at the moment, but I have no idea how to set up the required mock object.
Unfortunately, this isn't particularly easy to do, as the HttpApplication doesn't lend itself to mocking very easily; there is no interface to mock against and most of the methods aren't marked as virtual. I recently had a similar problem with HttpRequest and HttpWebResponse. In the end, the solution I went for was to create a straight "pass-through" wrapper for the methods I wanted to use: ``` public class HttpWebRequestWrapper : IHttpWebRequestWrapper { private HttpWebRequest httpWebRequest; public HttpWebRequestWrapper(Uri url) { this.httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url); } public Stream GetRequestStream() { return this.httpWebRequest.GetRequestStream(); } public IHttpWebResponseWrapper GetResponse() { return new HttpWebResponseWrapper(this.httpWebRequest.GetResponse()); } public Int64 ContentLength { get { return this.httpWebRequest.ContentLength; } set { this.httpWebRequest.ContentLength = value; } } public string Method { get { return this.httpWebRequest.Method; } set { this.httpWebRequest.Method = value; } } public string ContentType { get { return this.httpWebRequest.ContentType; } set { this.httpWebRequest.ContentType = value; } } } ``` etc, etc This let me mock against my own wrapper interface. Not necessarily the most elegant thing in the world, but a very useful way of mocking out some of the less "mockable" parts of the framework. Before you rush off and do this though, it is worth reviewing what you've got and seeing if there is a better approach to your tests that would avoid you having to wrap classes. In the case of HttpWebRequest, HttpApplication et al, there often isn't IMHO. In order to set this wrapper in mock (using my HttpWebRequest example above) you then do stuff like this with Moq: ``` var mockWebRequest = new Mock<IHttpWebRequestWrapper>(); mockWebRequest.SetupSet<string>(c => c.Method = "POST").Verifiable(); mockWebRequest.SetupSet<string>(c => c.ContentType = "application/x-www-form-urlencoded").Verifiable(); mockWebRequest.SetupSet<int>(c => c.ContentLength = 0).Verifiable(); ```
IMHO adding a functionality by extending HttpApplication is not the best thing to do. It is so difficult to mock the HttpContext because of the private/internal/sealed classes that even if you succeed your unit tests will be so cluttered with mocking code that you will no longer be able to understand what you are actually testing. Could you give more details on what functionality you are adding? Maybe there's a better way of adding this functionality to your application.
Unit testing an HttpApplication
[ "", "c#", "asp.net", "unit-testing", "moq", "httpapplication", "" ]
I am wondering how do I extend the membership stuff in asp.net? When a user logs in I want to check the UserName and Password. Of course the standard asp.net membership does this(this it is ValidateUser()). I also want to check another field called "institution". If a user types something in this box I want to verify if the "institution", "userName" and "password" match what is in the database. If a user leaves the "institution" blank then I just want to use it default ValidateUser() method that is provided in asp.net and check only "userName" and "password". So can I overload the ValdiateUser() method? Or will I have to write my own one to handle this new case? Where would I store this "institution" field in the database? I heard something about people recommending the "Profile" table but I am not sure. Also how can I change the membership to treat these as 3 different users Institution: ABC UserName: A09410515 Password: 1234567 Institution: GHA UserName: A09410515 Password: 1234567 UserName: A09410515 Password: 1234567 So as my database should be concerned these should be 3 unique users. Of course in the case that my database already would have the same information stored in it. For example. Institution: ABC UserName: A09410515 Password: 1234567 and someone tries to sign up with the exact same information for "UserName" and "Institution" then it would spit back an error about being duplicate names.
Yes, you can [create a custom membership provider](http://msdn.microsoft.com/en-us/library/f1kyba5e.aspx). Your provider will implement [MembershipProvider](http://msdn.microsoft.com/en-us/library/system.web.security.membershipprovider.aspx) giving you full control over creating an interface between the membership system and extended database schema. [Writing A Custom Membership Provider for your ASP.NET 2.0 Web Site](http://www.devx.com/asp/Article/29256) is a detailed example.
The lazy way of doing this would be to combine institution and username together to create the actual username. Thus you'd have 3 distinct usernames: ABC&A09410515, GHA&A09410515, and &A09410515. Just don't allow a user to use & in a username. Then, before creating the user or logging in you just combine the two strings together. I can't think of any significant problems that can't be fixed with a simple hack (e.g. displaying the username (use *username.split('&')[1]* ), but JP's post is definitely the "right" way to do it. James
How to Extend Membership in Asp.net?
[ "", "c#", "asp.net", "asp.net-mvc", "asp.net-membership", "" ]
I'm trying to remap several navigation keys: * ENTER: to work like standard TAB behavior (focus to next control) * SHIFT+ENTER: to work like SHIFT+TAB behavior (focus to previous control) * UP / DOWN arrows: previous /next control * etc I tried with a couple of options but without luck: ``` from javax.swing import * from java.awt import * class JTextFieldX(JTextField): def __init__(self, *args): # Thanks, Jack!! JTextField.__init__( self, focusGained=self.onGotFocus, focusLost=self.onLostFocus, *args) def onGotFocus (self, event): print "onGotFocus " self.selectionStart = 0 self.selectionEnd = len(self.text) def onLostFocus (self, event): print "onLostFocus ", self.name class Test(JFrame): def __init__(self): JFrame.__init__(self, 'JDesktopPane and JInternalFrame Demo', size=(600, 300), defaultCloseOperation=JFrame.EXIT_ON_CLOSE) self.desktop = JDesktopPane() self.contentPane.add(JScrollPane(self.desktop)) # This is the same as self.getContentPane().add(...) frame = JInternalFrame("Frame", 1, 1, 1, 1, size=(400, 400), visible=1) panel = JPanel() self.label = JLabel('Hello from Jython') panel.add(self.label) self.textfield1 = JTextFieldX('Type something here', 15) panel.add(self.textfield1) self.textfield2 = JTextFieldX('and click Copy', 15) panel.add(self.textfield2) panel.add(copyButton) frame.add(panel) frame.pack() self.desktop.add(frame) # ENTER=SPACE remapping for buttons (works ok, but only for buttons) # inputMap = UIManager.getDefaults().get("Button.focusInputMap") # pressedAction = inputMap.get(KeyStroke.getKeyStroke("pressed SPACE")); # releasedAction = inputMap.get(KeyStroke.getKeyStroke("released SPACE")); # # pressedAction = self.noAction # inputMap.put (KeyStroke.getKeyStroke("pressed ENTER"), pressedAction) # inputMap.put (KeyStroke.getKeyStroke("released ENTER"), releasedAction) # # Attemp to remap ENTER=TAB for TextFields (didn't work, no errors) # inputMap = UIManager.getDefaults().get("TextField.focusInputMap") # pressedAction = inputMap.get(KeyStroke.getKeyStroke("pressed TAB")); # releasedAction = inputMap.get(KeyStroke.getKeyStroke("released TAB")); # inputMap.put (KeyStroke.getKeyStroke("pressed W"), pressedAction) # inputMap.put (KeyStroke.getKeyStroke("released W"), releasedAction) # # Attemp to remap ENTER=TAB for all controls (didn't work, no errors) # spaceMap = self.textfield1.getInputMap().get(KeyStroke.getKeyStroke(event.KeyEvent.VK_TAB, 0, True)); # self.textfield1.getInputMap().put(KeyStroke.getKeyStroke(event.KeyEvent.VK_ENTER, 0, True),spaceMap); frame.setSelected(1) frame.moveToFront() def noAction (self, event): print "noAction" pass if __name__ == '__main__': test = Test() test.setLocation(100, 100) test.show() ```
I made a new post for readability. ``` self.textfield1 = JTextField('Type something here',15,focusGained=self.myOnFocus,keyPressed=self.myOnKey) #create textfield2...must be created before can be referenced below. self.textfield1.setNextFocusableComponent(self.textfield2) ``` then in your event handler: ``` def myOnKey(self,event): print str(event) # see all other info you can get. key_code = event.keyCode if key_code == 10: print "you pressed enter" # simulate the "tab" just focus next textbox... gotFocus = event.getComponent() nextToFocus = gotFocus.nextFocusableComponent nextToFocus.requestFocus() ``` Should do it.
Finally used part of Jack's answer (the keyPressed event) but without manually setting setNextFocusableComponent: ``` keyFocusMgr = KeyboardFocusManager.getCurrentKeyboardFocusManager() keyFocusMgr.focusNextComponent() ```
Remap keyboard navigation with Jython / Swing
[ "", "python", "swing", "jython", "" ]
``` >>> Enter muzzle velocity (m/2): 60 Enter angle (degrees): 45 Traceback (most recent call last): File "F:/Python31/Lib/idlelib/test", line 9, in <module> range() File "F:/Python31/Lib/idlelib/test", line 7, in range Distance = float(decimal((2*(x*x))((decimal(math.zsin(y)))*(decimal(math.acos(y)))))/2) TypeError: can't multiply sequence by non-int of type 'str' ``` I'm only new, so don't be too harsh if this is really obvious, but why am i getting this error?
You should convert the data you get from console to integers: ``` x = int(x) y = int(y) Distance = float(decimal((2*(x*x))((decimal(math.zsin(y)))*(decimal(math.acos(y)))))/2) ```
``` >>> '60' * '60' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can't multiply sequence by non-int of type 'str' ``` You are trying to multiply two strings together. You must convert the string input from the user to a number using `int()` or `float()`. Also, I'm not sure what you're doing with `decimal`; it looks like you're trying to call the module (the type is *in* the module, `decimal.Decimal`) but there's not much point in converting to a Decimal *after* doing some floating point math and *then* converting back to a `float`. In the future, post the code that causes the problem (and keep the interaction and traceback). But first try and shrink the code as much as possible while making sure it still causes the error. This is an important step in debugging.
TypeError: can't multiply sequence by non-int of type 'str'
[ "", "python", "" ]
How can I check whether two file paths point to the same file in Python?
``` $ touch foo $ ln -s foo bar $ python Python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> help(os.path.samefile) Help on function samefile in module posixpath: samefile(f1, f2) Test whether two pathnames reference the same actual file >>> os.path.samefile("foo", "bar") True ```
You want to use [`os.path.abspath(path)`](http://docs.python.org/library/os.path.html) to normalize each path for comparison. ``` os.path.abspath(foo) == os.path.abspath(bar) ```
Check absolute paths in Python
[ "", "python", "path", "" ]
considering that fairly static data should not be re-evaluated but cached instead, I wondered if it is possible to use Reflection to obtain class properties once, and then cache them so that I could dynamically evaluate object properties and read/assign values, but not have the Reflection overhead every time I do that. Is this possible (Sample code?) ? To clarify a bit, lets say I have this class: ``` public class Cloud { Boolean IsWhite; } ``` and I'm trying to now make a method that allows me to do something like this (pseudocode): ``` Update(myCloudInstance, new {IsWhite, true}); ``` Update should now check with the cache first if it knows already the properties of Cloud (typeof(myCloudInstance)), and then use cached information to assign the property "IsWhite" the value "true" instead of doing Reflection again. Any ideas on how to do this?
It's not clear *exactly* what you're doing, but caching can certainly make a difference with reflection. In particular, if you're invoking methods (or property getters/setters) and can do so in a type-safe way as far as the calling code is concerned, it [can make a *huge* difference](https://codeblog.jonskeet.uk/2008/08/09/making-reflection-fly-and-exploring-delegates/) if you convert the `MethodInfo` into a strongly-typed delegate once and then reuse that. If you could give us a complete example of what you're trying to do, that would help us to come up with more specific ideas or even code. If you're just going to cache a `PropertyInfo` that may not have as much (or any) effect - it's possible that the normal `Type.GetProperty` (etc) methods are already pretty fast. As ever with performance questions, the key is to measure what you're actually doing. Make a change and measure again, etc.
The cost of reflection does not need to be as big as you think. In addition to delegates (that Jon discusses) you can also use things like [HyperDescriptor](http://www.codeproject.com/KB/cs/HyperPropertyDescriptor.aspx) to minimise the cost of reflection without changing the code much - it simply becomes `PropertyDescriptor` instead: ``` PropertyDescriptorCollection props = TypeDescriptor.GetProperties(myCloudInstance); // ideally cache props, but not essential ``` then ``` object val = props["IsWhite"].GetValue(myCloudInstance); ``` or if you use it lots, consider storing the `PropertyDescriptor` somewhere, too. However... like Jon, I'm really not 100% sure what you're trying to do!
Cache Reflection Results (Class Properties)
[ "", "c#", ".net", "reflection", "caching", "" ]
Is it possible to have a dynamic operator in c#? ``` string aString = "5"; int a = 5; int b = 6; string op = "<"; //want to do something like dynamically without checking the value of op if( a op b) ```
You can't create dynamic operators - but you can wrap an operator in a delegate. You can use lambdas to simplify the syntax. ``` Func<int,int,int> opPlus = (a,b) => a + b; Func<int,int,int> opMinus = (a,b) => a - b; // etc.. // now you can write: int a = 5, b = 6; Func<int,int,int> op = opPlus; if( op(a,b) > 9 ) DoSomething(); ``` Although it's not definite - the future direction for C# is to implement the compiler as a service. So, at some point, it may be possible to write code that dynamically evaluates an expression.
Piggybacking on LBushkin's response: ``` Func<int, int, bool> AGreaterThanB = (a,b) => a > b; Func<int, int, bool> ALessThanB = (a,b) => a < b; Func< int, int, bool> op = AGreaterThanB; int x = 7; int y = 6; if ( op( x, y ) ) { Console.WriteLine( "X is larger" ); } else { Console.WriteLine( "Y is larger" ); } ``` <http://msdn.microsoft.com/en-us/library/bb549151.aspx>
C# dynamic operator
[ "", "c#", "dynamic", "" ]
If i have 1000 pages of html can i provide option for page range while printing html? Is it possible in javascript? (Ex: print page 100 to 200)
Passing in a page range to the native print dialog... nope. You could dynamically wrap the portions that you don't want to print with a CSS class that you've defined in a print stylesheet... ``` <link rel="stylesheet" type="text/css" media="print" href="print.css" /> /* contents of print.css */ .noprint { display: none; } ``` You'll have to figure out how to get that class onto the appropriate bits of HTML before calling window.print().
You can try using the [`page-break-before`](http://www.w3schools.com/Css/pr_print_pagebb.asp) CSS property to define page breaks in your HTML source. Then allow your user to print a range of pages as he or she normally would.
Option for page range while printing html
[ "", "javascript", "html", "" ]
Just wondering if any of you people use `Count(1)` over `Count(*)` and if there is a noticeable difference in performance or if this is just a legacy habit that has been brought forward from days gone past? The specific database is `SQL Server 2005`.
There is no difference. Reason: > [Books on-line](http://msdn.microsoft.com/en-us/library/ms175997.aspx) says "`COUNT ( { [ [ ALL | DISTINCT ] expression ] | * } )`" "1" is a non-null expression: so it's the same as `COUNT(*)`. The optimizer recognizes it for what it is: trivial. The same as `EXISTS (SELECT * ...` or `EXISTS (SELECT 1 ...` Example: ``` SELECT COUNT(1) FROM dbo.tab800krows SELECT COUNT(1),FKID FROM dbo.tab800krows GROUP BY FKID SELECT COUNT(*) FROM dbo.tab800krows SELECT COUNT(*),FKID FROM dbo.tab800krows GROUP BY FKID ``` Same IO, same plan, the works Edit, Aug 2011 [Similar question on DBA.SE](https://dba.stackexchange.com/questions/2511/what-is-the-difference-between-select-count-and-select-countany-non-null-col/2512#2512). Edit, Dec 2011 `COUNT(*)` is mentioned specifically in [ANSI-92](http://msdn.microsoft.com/en-us/library/ms175997.aspx) (look for "`Scalar expressions 125`") > Case: > > a) If COUNT(\*) is specified, then the result is the cardinality of T. That is, the ANSI standard recognizes it as bleeding obvious what you mean. `COUNT(1)` has been optimized out by RDBMS vendors *because* of this superstition. Otherwise it would be evaluated as per ANSI > b) Otherwise, let TX be the single-column table that is the > result of applying the <value expression> to each row of T > and eliminating null values. If one or more null values are > eliminated, then a completion condition is raised: warning-
I work on the SQL Server team and I can hopefully clarify a few points in this thread (I had not seen it previously, so I am sorry the engineering team has not done so previously). ### TL;DR: There is no semantic and no noticeable difference in performance difference between `select count(1) from table` vs. `select count(*) from table`. ### Explanation First, there is **no semantic difference** between `select count(1) from table` vs. `select count(*) from table`. They return the same results in all cases (and it is a bug if not). As noted in the other answers, `select count(column) from table` is semantically different and does not always return the same results as `count(*)`. Second, with respect to **performance**, there are two aspects that would matter in SQL Server (and SQL Azure): compilation-time work and execution-time work. The **Compilation time work** is a *trivially small amount of extra work* in the current implementation. There is an expansion of the `*` to all columns in some cases followed by a reduction back to `1` column being output due to how some of the internal operations work in binding and optimization. I doubt it would show up in any measurable test, and it would likely get lost in the noise of all the other things that happen under the covers (such as auto-stats, xevent sessions, query store overhead, triggers, etc.). It is maybe a few thousand extra CPU instructions. So, `count(1)` does a tiny bit less work during compilation (which will usually happen once and the plan is cached across multiple subsequent executions). For **execution time**, assuming the plans are the same there should be *no measurable difference*. (One of the earlier examples shows a difference - it is most likely due to other factors on the machine if the plan is the same). ### Disclaimer as to how the plan can potentially be different (very rare) These are *extremely unlikely to happen*, but it is potentially possible in the architecture of the current optimizer. SQL Server's optimizer works as a search program (think: computer program playing chess searching through various alternatives for different parts of the query and costing out the alternatives to find the cheapest plan in reasonable time). This search has a few limits on how it operates to keep query compilation finishing in reasonable time. For queries beyond the most trivial, there are phases of the search and they deal with tranches of queries based on how costly the optimizer thinks the query is to potentially execute. There are 3 main **search phases**, and each phase can run more aggressive(expensive) heuristics trying to find a cheaper plan than any prior solution. Ultimately, there is a decision process at the end of each phase that tries to determine whether it should return the plan it found so far or should it keep searching. This process uses the total time taken so far vs. the estimated cost of the best plan found so far. So, on different machines with different speeds of CPUs it is possible (albeit rare) to get different plans due to timing out in an earlier phase with a plan vs. continuing into the next search phase. There are also a few similar scenarios related to timing out of the last phase and potentially running out of memory on very, very expensive queries that consume all the memory on the machine (not usually a problem on 64-bit but it was a larger concern back on 32-bit servers). Ultimately, if you get a different plan the performance at runtime would differ. *I don't think it is remotely likely that the difference in compilation time would EVER lead to any of these conditions happening*. ### Net-net: Please use whichever of the two you want as none of this matters in any practical form. (There are far, far larger factors that impact performance in SQL beyond this topic, honestly). ### Further Info I hope this helps. I did write a book chapter about how the optimizer works but I don't know if its appropriate to post it here (as I get tiny royalties from it still I believe). So, instead of posting that I'll post a link to a talk I gave at SQLBits in the UK about how the optimizer works at a high level so you can see the different main phases of the search in a bit more detail if you want to learn about that. Here's the video link: [Inside the SQL Server Query Optimizer](https://www.youtube.com/watch?v=cMBHxjnl4NE)
Count(*) vs Count(1) - SQL Server
[ "", "sql", "sql-server", "performance", "" ]
I have a dataset that is populated by reading excel file. The dataset stores the data from the excel. The date in the dataset in in the format *2\2\2009 12:00:00 AM* but i need the data format converted to *2\2\2009* . I want to change the format of all the data in that particular column.
Here's one way: ``` foreach (DataRow row in yourDataTable) { DateTime dt = DateTime.Parse(row["Date"].ToString()); row["Date"] = dt.ToShortDateString(); } ``` This is assuming that the "Date" column is just a text field rather than already a DateTime field.
You can customize the output using a [pattern](http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm) if it is a DateTime object to the format you wanted, "2\2\2009". ``` string output1 = dt.ToString(@"mm\\dd\\yyyy"); string output2 = dt.ToString("mm/dd/yyyy"); //did you mean this? ```
formatting datetime column in a DataSet
[ "", "c#", "asp.net", "dataset", "asp.net-2.0", "" ]
For a static Win32 library, how can I detect that any of the "Use MFC" options is set? i.e. ``` #ifdef ---BuildingForMFC--- .... #else ... #endif ```
I have always checked for the symbol \_MFC\_VER being defined. This is the version number of MFC being used 0x0700 = 7.0 It is in the "Predefined Macros" in MSDN
I've check on Visual Studio 2013, in an original project targeting only Win32 console, so I've to add MFC support (without using of the Project Wizard) in a second time. Following are my findings: * The macro \_MFC\_VER is defined in the afxver\_.h, included by afx.h. So, if you don't include afx.h directly/indirectly in your .cpp file, you don't have the \_MFC\_VER macro defined. For example, including in a project a source .cpp that doesn't include the afx.h, the file will be compiled *WITHOUT* the definition of \_MFC\_VER macro. So it's useless for adapt the c++ code (an external library, for example) to detect usage of MFC library and optionally support the MFC library. * If you manually turn on the use of MFC (Select the project in Solution Explorer, than right click, Configuration Properties -> General -> Use of MFC) you have two possibilities: + A) select "Use MFC in a Shared DLL" option. This actually update the command line parameters adding the definition of \_AFXDLL to the preprocessor macro list. + B) select "Use MFC in a Static Library" options. This actually remove the \_AFXDLL macro defined, but no macro definition is added, so nothing can told you if MFC is actually used. So, during my test activity, only the mode A can be used effectively to understand if the MFC library is included or not in the project under building. I maintain a C++ cross-platform library that support many platforms (Mac OSx, WinX console, WinX MFC, iOS, Unix, Android) and enabling MFC with dynamic DLL is the only way to transparently detect the MFC presence. So for example: ``` #if defined(_AFXDLL) # include <afx.h> #endif ``` Obviusly, you can add manually a macro definition (\_AFX) in the project preprocessor list.
How to detect "Use MFC" in preprocessor
[ "", "c++", "mfc", "visual-c++-2008", "" ]
EDIT: OOPS, sorry I wasn't clear. I have a string that I get from AJAX that is an xhtml document, I need to get the body tag of it, unless I can generate a dom tree from the string? I need to get everything from a body tag in a string, including markup, with a javascript regex. I know that this is a duplicate, but the regexes I found in other questions were for different flavours of regex, and gave me errors. Thank in advance.
`document.getElementsByTagName('body')[0].innerHTML` will return a string of everything in the body tag. It's not a regex, but I'm not sure why you need one...? POST QUESTION EDIT: Your XHR object that you performed your AJAX with has `responseText` and `responseXML` properties. As long as the response is valid xml, which is probably should be, you can get any tag you want using `getElementsByTagName` on the xml object that I mentioned. But if you just want the inner parts of the body, I would do it this way: ``` var inner = myXHR.responseText.split(/(<body>|</body>)/ig)[2]); ```
Regex isn't the ideal tool for parsing the DOM as you will see mentioned throughout this site and others. The most ideal way, as suggested by George IV is to use the JavaScript tools that are more suited to this and that is getElementsByTagName and grab the innerHTML: ``` var bodyText = document.getElementsByTagName("body")[0].innerHTML; ``` **Edit1**: I've not checked it out yet, but Rudisimo suggested a tool that shows a *lot* of promise - the [XRegExp](http://xregexp.com/) Library which is an open sources and extensible library out of MIT. This could potentially be a viable option - I still think the DOM is the better way, but this looks far superior to the standard JavaScript implementation of regex. **Edit2**: I recant my previous statements about the Regex engine [for reasons of accuracy] due to the example provided by Gumbo - however absurd the expression might be. I do, however, stand by my opinion that using regex in this instance is an inherently bad way to go and you should reference the DOM using the aforementioned example.
Regex to match contents of HTML body
[ "", "javascript", "regex", "" ]
I have a class `MyClass`, which contains two member variables `foo` and `bar`: ``` class MyClass: def __init__(self, foo, bar): self.foo = foo self.bar = bar ``` I have two instances of this class, each of which has identical values for `foo` and `bar`: ``` x = MyClass('foo', 'bar') y = MyClass('foo', 'bar') ``` However, when I compare them for equality, Python returns `False`: ``` >>> x == y False ``` How can I make Python consider these two objects equal?
You should implement the method [`__eq__`](https://docs.python.org/3/reference/datamodel.html#object.__eq__): ``` class MyClass: def __init__(self, foo, bar): self.foo = foo self.bar = bar def __eq__(self, other): if not isinstance(other, MyClass): # don't attempt to compare against unrelated types return NotImplemented return self.foo == other.foo and self.bar == other.bar ``` Now it outputs: ``` >>> x == y True ``` Note that implementing `__eq__` will automatically make instances of your class unhashable, which means they can't be stored in sets and dicts. If you're not modelling an immutable type (i.e. if the attributes `foo` and `bar` may change the value within the lifetime of your object), then it's recommended to just leave your instances as unhashable. If you are modelling an immutable type, you should also implement the data model hook [`__hash__`](https://docs.python.org/3/reference/datamodel.html#object.__hash__): ``` class MyClass: ... def __hash__(self): # necessary for instances to behave sanely in dicts and sets. return hash((self.foo, self.bar)) ``` A general solution, like the idea of looping through `__dict__` and comparing values, is not advisable - it can never be truly general because the `__dict__` may have uncomparable or unhashable types contained within. N.B.: be aware that before Python 3, you may need to use [`__cmp__`](https://portingguide.readthedocs.io/en/latest/comparisons.html#rich-comparisons) instead of `__eq__`. Python 2 users may also want to implement [`__ne__`](https://docs.python.org/2/reference/datamodel.html#object.__ne__), since a sensible default behaviour for inequality (i.e. inverting the equality result) will not be automatically created in Python 2.
You override the [rich comparison operators](https://docs.python.org/2.7/reference/datamodel.html#object.__lt__) in your object. ``` class MyClass: def __lt__(self, other): # return comparison def __le__(self, other): # return comparison def __eq__(self, other): # return comparison def __ne__(self, other): # return comparison def __gt__(self, other): # return comparison def __ge__(self, other): # return comparison ``` Like this: ``` def __eq__(self, other): return self._id == other._id ```
Compare object instances for equality by their attributes
[ "", "python", "equality", "" ]
I have a Client Application, a server and another client, lets call it third party. I have a callback interface as part of my contract that is implemented both by the third party and the client. The third party will call a server operation(method) then the server will trigger a callback but instead of calling the callback of the third party, it will call the callback implementation of the client.
I think I found the solution.. Here's the link. <http://msdn.microsoft.com/en-us/magazine/cc163537.aspx> Try to look at figure 6. That's what I'm trying to achieve.
Yes, you can absolutely do that. The easiest way is to implement your service as a PerSession service, and capture the callback context on initialization/construction. Typically I will add the service object (which really represents a connection at that point) to an internal core object. Then, when you get in a message from a client, you can make a call to any of the service objects (not through the contract), and internally forward the data to the associated client. This is a pretty minimal implementation of the concept, without exception handling, and some pretty bad design (static class BAD!). I haven't tested this, but the principles should hold even if I missed crossing an i or dotting a t. This example also forwards the calls to *all* clients, but selecting an individual client follows the same basic pattern. Trying to do this with a singleton service will be more difficult, and a per-call service obviously won't work :) ``` [ServiceContract(CallbackContract = typeof(ICallback))] public interface IContract { [OperationContract(IsOneWay = true)] void SendTheData(string s); } public interface ICallback { [OperationContract(IsOneWay = true)] void ForwardTheData(string s); } [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant, InstanceContextMode = InstanceContextMode.PerSession)] public class ServiceConnection : IContract { private ICallback m_callback; public ServiceConnection() { m_callback = OperationContext.Current.GetCallbackChannel<ICallback>(); ServiceCore.Add(this); } public void SendTheData(string s) { ServiceCore.DataArrived(s); } public void SendToClient(string s) { m_callback.ForwardTheData(s); } } static public class ServiceCore { static private List<ServiceConnection> m_connections = new List<ServiceConnection>(); public static void DataArrived(string s) { foreach(ServiceConnection conn in m_connections) { conn.SendTheData(s); } } public static void Add(ServiceConnection connection) { m_connections.Add(connection); } } ```
Can I use WCF duplex binding to relay message?
[ "", "c#", "wcf", "binding", "callback", "duplex", "" ]
I try to open multiple browser windows using javascript and the window.open() function. I want to pass a parameter through the query string to my new window like this: ``` window.open('http://www.myfoo.com/foopage.aspx?fooparm=1', '_blank'); ``` This opens a new window with the correct address in the address bar but the browser displays a 404-not found. However, if I press enter in this new window, the page loads up correctly. With a bit of trial and error, I found that using window.open without query string parameters works perfectly: ``` window.open('http://www.myfoo.com/foopage.aspx', '_blank'); ``` Is there a limitation I should know about window.open and query string parameters? Is there another way to pass parameters to a new page in a new window? Thank you very much in advance for your insight. (Note: This script is generated server-side in C# and injected into the page using Ajax's ScriptManager.RegisterStartupScript.)
I found why this morning: In web.config, under globalization, the responseEncoding was set to "cp037". I changed it to "ISO-8859-15" and my windows are popping up correctly. ``` <globalization fileEncoding="ISO-8859-15" requestEncoding="ISO-8859-15" responseEncoding="ISO-8859-15" culture="auto" uiCulture="auto"/> ```
One thing for sure: the limitation is not tied to window.open() pre se. My server runs mod\_perl, and I use GET requests in window.open() frequently.
Query string parameters do not seem to work with window.open
[ "", "javascript", "parameters", "query-string", "" ]
I'm running into an issue with a join: getting back too many records. I added a table to the set of joins and the number of rows expanded. Usually when this happens I add a select of all the ID fields that are involved in the join. That way it's pretty obvious where the expansion is happening and I can change the ON of the join to fix it. Except in this case, the table that I added doesn't have an ID field. This is a problem. But perhaps I'm wrong. Should every table in a database have an IDENTITY field that's used as the PK? Are there any drawbacks to having an ID field in every table? What if you're reasonably sure this table will never be used in a PK/FK relationship? [When having an identity column is not a good idea?](https://stackoverflow.com/questions/932913/when-having-an-identity-column-is-not-a-good-idea) [Surrogate vs. natural/business keys](https://stackoverflow.com/questions/63090/surrogate-vs-natural-business-keys) [Wikipedia Surrogate Key article](http://en.wikipedia.org/wiki/Surrogate_key)
There are two concepts that are close but should not be confused: `IDENTITY` and `PRIMARY KEY` Every table (except for the rare conditions) should have a `PRIMARY KEY`, that is a value or a set of values that uniquely identify a row. See [**here**](https://stackoverflow.com/questions/840162/should-each-and-every-table-have-a-primary-key) for discussion why. `IDENTITY` is a property of a column in `SQL Server` which means that the column will be filled automatically with incrementing values. Due to the nature of this property, the values of this column are inherently `UNIQUE`. However, no `UNIQUE` constraint or `UNIQUE` index is automatically created on `IDENTITY` column, and after issuing `SET IDENTITY_INSERT ON` it's possible to insert duplicate values into an `IDENTITY` column, unless it had been explicity `UNIQUE` constrained. The `IDENTITY` column should not necessarily be a `PRIMARY KEY`, but most often it's used to fill the surrogate `PRIMARY KEY`s It may or may not be useful in any particular case. Therefore, the answer to your question: > The question: should every table in a database have an IDENTITY field that's used as the PK? is this: ### No. There are cases when a database table should NOT have an `IDENTITY` field as a `PRIMARY KEY`. Three cases come into my mind when it's not the best idea to have an `IDENTITY` as a `PRIMARY KEY`: * If your `PRIMARY KEY` is composite (like in many-to-many link tables) * If your `PRIMARY KEY` is natural (like, a state code) * If your `PRIMARY KEY` should be unique across databases (in this case you use `GUID` / `UUID` / `NEWID`) All these cases imply the following condition: ### You shouldn't have `IDENTITY` when you care for the values of your `PRIMARY KEY` and explicitly insert them into your table. **Update:** Many-to-many link tables should have the pair of `id`'s to the table they link as the composite key. It's a natural composite key which you already have to use (and make `UNIQUE`), so there is no point to generate a surrogate key for this. I don't see why would you want to reference a `many-to-many` link table from any other table except the tables they link, but let's assume you have such a need. In this case, you just reference the link table by the composite key. This query: ``` CREATE TABLE a (id, data) CREATE TABLE b (id, data) CREATE TABLE ab (a_id, b_id, PRIMARY KEY (a_id, b_id)) CREATE TABLE business_rule (id, a_id, b_id, FOREIGN KEY (a_id, b_id) REFERENCES ab) SELECT * FROM business_rule br JOIN a ON a.id = br.a_id ``` is much more efficient than this one: ``` CREATE TABLE a (id, data) CREATE TABLE b (id, data) CREATE TABLE ab (id, a_id, b_id, PRIMARY KEY (id), UNIQUE KEY (a_id, b_id)) CREATE TABLE business_rule (id, ab_id, FOREIGN KEY (ab_id) REFERENCES ab) SELECT * FROM business_rule br JOIN a_to_b ab ON br.ab_id = ab.id JOIN a ON a.id = ab.a_id ``` , for obvious reasons.
Almost always yes. I generally default to including an identity field unless there's a compelling reason not to. I rarely encounter such reasons, and the cost of the identity field is minimal, so generally I include. Only thing I can think of off the top of my head where I didn't was a highly specialized database that was being used more as a datastore than a relational database where the DBMS was being used for nearly every feature except significant relational modelling. (It was a high volume, high turnover data buffer thing.)
in general, should every table in a database have an identity field to use as a PK?
[ "", "sql", "database", "database-design", "" ]
I needed to add a new NVARCHAR column to a table in my DB. So I added the column, and then fired up Visual Studio to update the EDMX-file for the Entity Framework. I ran update model from database on everything, which only resulted in "data reader is incompatible"-errors. So I renamed the whole table in the DB, updated EDMX from database, renamed the table back to the original name, ran update again, and then created new function imports for all affected stored procedures. But I still get the same error: > The data reader is incompatible with > the specified '[Model].[Entity]'. A > member of the type, > '[Column]', does not have a > corresponding column in the data > reader with the same name. I've looked around a bit, and this seems to be a common error if the column name is different in the database and framework. This is however not the case, they have the same name. I can access the column in the code via [Entity].Context.[Column], so I don't quite see what the data reader is complaining about. I've run out of ideas, so any help welcome.
Turns out the EDMX was fine, but the designer has, for some odd reason, stopped update Designer.cs in my project. Had to go in and manually edit it.
Updating the model replaces the store schema, but not the client schema or the mapping. To start with "a clean slate", *back up your current EDMX*, then open it as XML. Remove all references to the table, then close and open in the graphical error. Build. If you have any errors (perhaps broken links to the deleted table), fix them. Then update model to re-add the table.
Problem with Entity Framework after adding column to DB table
[ "", "c#", "asp.net", "sql-server", "entity-framework", "" ]
How can I tell my TabControl to set the focus to its first TabItem, something like this: *PSEUDO-CODE:* ``` ((TabItem)(MainTabControl.Children[0])).SetFocus(); ```
How about this? ``` MainTabControl.SelectedIndex = 0; ```
``` this.tabControl1.SelectedTab = this.tabControl1.TabPages["tSummary"]; ``` I've found it's usually a best practice to name your tabs and access it via the name so that if/when other people (or you) add to or subtact tabs as part of updating, you don't have to go through your code and find and fix all those "hard coded" indexes. hope this helps.
How can I make a specific TabItem gain focus on a TabControl without click event?
[ "", "c#", "wpf", "xaml", "focus", "tabcontrol", "" ]
Is this good practise? I have 3 DataGridView's and I want to have a facility that allows a user to sort the data by clicking on a column header. I could've had an event handler for the ColumnHeaderMouseClick event for each of these DataGridView's, but instead I made one: ``` private void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { SortDataGridView((sender as DataGridView), e.ColumnIndex); } ``` SortDataGridView looks like this: ``` /// <summary> /// Sorts a given DataGridView by a column given by its columnIndex. /// Default sort (if it isn't currently sorted) is Ascending. If it's /// already sorted Ascending, change it to Descending. If it is Descending, /// change it to Ascending. /// </summary> /// <param name="dataGridViewToSort">The DataGridViewToSort</param> /// <param name="columnIndexToSortBy">The index of the column which we want to sort by in the DataGridView.</param> private void SortDataGridView(DataGridView dataGridViewToSort, int columnIndexToSortBy) { switch (dataGridViewToSort.SortOrder) { case SortOrder.Ascending: dataGridViewToSort.Sort(dataGridViewToSort.Columns[columnIndexToSortBy], ListSortDirection.Descending); break; case SortOrder.Descending: dataGridViewToSort.Sort(dataGridViewToSort.Columns[columnIndexToSortBy], ListSortDirection.Ascending); break; case SortOrder.None: dataGridViewToSort.Sort(dataGridViewToSort.Columns[columnIndexToSortBy], ListSortDirection.Ascending); break; default: break; } } ``` Each of the DataGridView's ColumnHeaderMouseClick event is hooked up to this handler. This implies that in order to realise which one raised the event at runtime, I have to say (sender as DataGridView). Is this safe? Could sender ever be something that's not a DataGridView?
I think this is very acceptable and I use this often for controls that have similar functionality. You can add a check in the event to make sure that sender is of the datagrid type if you are concerned with sender being some other object.
not only is it ok, it is better, because it makes your code more reuseable, maintainable and extensible.
Is it safe to use the same event handler for different Windows Forms Controls?
[ "", "c#", "winforms", "event-handling", "" ]
i am wondering if there is a public database where you can test your SQL and can connect to? i would like to test a connection to a database using vb.net, and would like to run a few sql statements.
Not one I am aware of. As Max said you can install Express edition and try it out locally. If you still want to test with a public DB then drop mean email at shobankr[at]gmail.com .. I have a public DB which I use to test my apps.
Someone may have something like this, but why would you want to use a public database? Normally you would just install something like [Microsoft SQL Express](http://www.microsoft.com/express/sql/default.aspx) and test locally. That way you control the environment.
connecting to a public database through vb.net
[ "", "sql", "vb.net", "" ]
This problem surprises me because it does not work in Chrome as well. Chrome!! Anyways, I have 3 select boxes, A, B, C. On a page load, B and C are hidden. (This is fine in all browsers). Currently, I have an event handler attached to specific values in box A, so that if a value is clicked, B shows itself populated with results according to A. Same thing for C: if a value in B is clicked, C will show itself. However, this "show" effect only occurs in firefox -- Chrome and IE are confused. Any suggestions? hints? Here is some code: ``` $(document).ready(function() { $("#B").hide(); $("#C").hide(); $('select#A option').each(function() { $(this).click(function() { $.getJSON(stuff, callback(data)); }); }); }); function callback(data) { // alert("hi"); // This isn't working for Chrome / IE! so the callback isn't called $("#B").show(); // This isn't working for Chrome / IE! }; ``` EDIT: It Turns out, the 'select#A option' -- the 'option' tag was the buggy one. After changing my handler to "change", I was able to debug and debug till I just removed the option tag -- everything seems to work now. Thanks, Michael
The actual problem is in the following line: ``` //... $.getJSON(stuff, callback(data)); //... ``` You are not passing the callback function, you are actually executing the function and passing `undefined` since it doesn't return anything. You should pass only the reference of the function: ``` //... $.getJSON(stuff, callback); //... ``` Or use an anonymous function in place: ``` //... $.getJSON(stuff, function(data){ $("#B").show(); }); //... ``` **Edit:** I haven't noticed about the click handler that you're trying to assign, I recommend you to use the [change](http://docs.jquery.com/Events/change) event on the select element, to ensure that an option has been selected: ``` $(document).ready(function() { $("#B,#C").hide(); $('select#A').change(function() { $.getJSON(stuff, function(data) { $("#B").show();}); }); }); ```
I think that you might have extra closing brackets at the end of the callback function. **UPDATE:** It seems like firefox can pick the click event for the option but not IE. i don't know for chrome but it might be the same problem. Instead of listening to the click event on the option you could just use the [change](http://docs.jquery.com/Events/change#fn) event to track a change in the select. you could do the following if the change event does correspond to what you are trying to do. ``` $(document).ready(function() { $("#B").hide(); $("#C").hide(); $('select#A').each(function() { $(this).change(function() { $.getJSON(stuff, callback(data)); }); }); ``` }); function callback(data) { ``` $("#B").show(); ``` }; Notice how i am listening to the change event on the Select itself. I hope this helps!
JQuery effect working in firefox; not chrome / ie
[ "", "javascript", "jquery", "firefox", "" ]
I am fairly new to javascript and DOM and I am having a problem with manipulating DOM using javascript for the following html code. ``` <html> <head> <title>Testing</title> </head> <body> <marquee direction=up height=400 scrollAmount=3.7 scrollDelay=70 onmousedown="this.stop()" onmouseover="this.stop()" onmousemove="this.stop()" onmouseout="this.start()"> <a href="#"> <span>Lion</span></a><br><br> <a href="#"> <span>Tiger</span></a><br><br> <a href="#"> <span>Giraffe</span></a><br><br> <a href="#"> <span>Dinosaur</span></a><br><br> <a href="#"> <span>Cat</span></a><br><br> <a href="#"> <span>Dog</span></a><br><br> <a href="#"> <span>Llama</span></a><br><br> <a href="#"> <span>Rat</span></a><br><br> <a href="#"> <span>Rhino</span></a><br><br> <a href="#"> <span>Reindeer</span></a><br><br> <a href="#" ><span >buffalo</span></a><br><br> <a href="#" ><span >Yak</span></a><br><br> <a href="#" ><span >Deer</span></a><br><br> <a href="#" ><span >moose</span></a><br><br> <a href="#" ><span >Rabbit</span></a> <br><br> <a href="#" ><span >Duck</span></a> <br><br> <a href="#" ><span >Peacock</span></a><br><br> <a href="#" ><span >Crow</span></a><br><br> <a href="#" ><span >Raven</span></a><br><br> <a href="#" ><span >Swan</span></a><br><br> </marquee> <input type="button" value="Set Me Fixed" onclick="setMeFixed();" /> </body> </html> ``` Sorry if the above html code is bad.I am writing a greasemonkey script for the same which is produced by a site which i have simplified here. So i have no control over it whatsoever. I want the [marquee] tag to be replaced with the [div] tag so that it becomes static and i don't have to wait forever for the 100th link in the marquee to come up. ;-). So I wrote the following script. (I am new to js programming and yes i know that my script sucks :-) ) ``` function setMeFixed(){ var fixedElement=document.createElement('div'); var marqueeElement=document.getElementsByTagName('marquee')[0]; //var clonedMarqNodes=marqueeElement.cloneNode(true); for(i=0;i<marqueeElement.childNodes.length;i++){ fixedElement.appendChild(marqueeElement.childNodes[i]); } marqueeElement.parentNode.replaceChild(fixedElement,marqueeElement); } ``` Many problems occured. The resulting output did not show few links on it. Peacock, Crow, Swan, Raven are not seen in the output and all the tags are messed up after it becomes static with spaces printed above and no breaks between the links. As a beginner javascript programmer i am stuck here and any assistance in the right direction would be much appreciated. Any way to elegantly solve this problem? Thanks. paul bullard. PS: I am using Fx 3.0.11.
Have you considered using innerHTML? ``` var marq = document.getElementsByTagName('marquee')[0]; var div = document.createElement('div'); div.innerHTML = marq.innerHTML; marq.parentNode.appendChild(div); marq.parentNode.removeChild(marq); ``` Not the most efficient, but straight-forward. See: <http://jquery.nodnod.net/cases/586>
As for the reason that your resultant document ended up missing a few nodes, I can tell you why: When you `appendChild` to another node, the DOM removes it from wherever it used to be. So when you go through the first node, it's removing children at the same time as it advances `i` down the DOM. Assume that `A`, `B`, `C`, etc. are child nodes, and this is what happens at the start of your loop: ``` i=0 ↓ MARQUEE: A B C D E F DIV: i=1 ↓ MARQUEE: B C D E F DIV: A i=2 ↓ MARQUEE: B D E F DIV: A C i=3 ↓ MARQUEE: B D F (accessing this gives you an exception!) DIV: A C E ``` You can fix this in one of two ways. Firstly, you could make this change: ``` fixedElement.appendChild(marqueeElement.childNodes[i]); // becomes fixedElement.appendChild(marqueeElement.childNodes[i].cloneNode()); ``` so you're always manipulating a cloned node, and the original `<marquee>` doesn't have elements removed, or you can make this change: ``` fixedElement.appendChild(marqueeElement.firstChild); ``` so that you always take the first item in the `<marquee>` and don't lose elements that way.
Replacing a html tag with another tag using JS DOM
[ "", "javascript", "html", "dom", "replace", "nodes", "" ]
I have a WinForms application, running on .net 3.5. This Application generates HTML on the fly, which includes the complete document, and also an inline-CSS-Stylesheet (inside the head element). I am using the WebBrowser control and setting browser.DocumentText to my generated HTML, but that does not seem to properly apply styles on the body element (I've set background-color to #000000 in the CSS, but the background is still white). I wonder if a) there are some alternatives to render relatively simple HTML in C# (i.e. a completely managed HTML renderer) or b) what would be the best way to render HTML using the WebBrowser control, including correct handling of inline-css and without using a temporary file on the hard drive. **Edit:** The CSS-not-applying issue was a separate problem. I've put my actual CSS in a CDATA block, which seems to cause it not to apply correctly. That is now fixed, but the question itself still stands.
Stayed with the built-in WebBrowser. The HtmlRenderer from the other answer is great, but renders an image.
For managed HTML renderer see [HtmlRenderer](https://github.com/ArthurHub/HTML-Renderer) on GitHub.
Best Way to Render HTML in WinForms application?
[ "", "c#", "html", ".net", "winforms", "webbrowser-control", "" ]
I have an XML file: ``` <SMS> <Number>+447761692278</Number> <DateTime>2009-07-27T15:20:32</DateTime> <Message>Yes</Message> <FollowedUpBy>Unassigned</FollowedUpBy> <Outcome></Outcome> <Quantity>0</Quantity> <Points>0</Points> </SMS> <SMS> <Number>+447706583066</Number> <DateTime>2009-07-27T15:19:16</DateTime> <Message>STOP</Message> <FollowedUpBy>Unassigned</FollowedUpBy> <Outcome></Outcome> <Quantity>0</Quantity> <Points>0</Points> </SMS> ``` I use an XMLReader to read the file into a dataset and display it in a datagridview. I want to be able to specify a range of dates to display the data for. For example where the element contains a date between INSERT DATE & INSERT DATE. In order to do this I am using a DATAVIEW and then populating the datagridview with the dataview instead of the dataset. Currently I have a method as below: ``` public void DisplayRecSmsByDateRange(string date1,string date2, string readDir) { DataSet ds = new DataSet("SMS DataSet"); XmlDataDocument xmlDatadoc = new XmlDataDocument(); xmlDatadoc.DataSet.ReadXml(readDir); ds = xmlDatadoc.DataSet; DataView custDV = new DataView(ds.Tables["SMS"]); custDV.RowFilter = String.Format("(DateTime >= DateTime LIKE '{0}*' AND DateTime <= DateTime LIKE '{1}*')", EscapeLikeValue(date1), EscapeLikeValue(date2)); this.dataGridView1.DataSource = custDV; } ``` The problem is that if you look at the xml file, the element contains the time as well as the date. Since I am not interested in the time part of this element, I would use the "LIKE" statement to display the data from the xml file based on just the date part of the element. As a result of this, when i try and perform a boolean operation to say for example - "Show me the data for dates between 2009-07-27 and 2009-07-30", I get an error since the compiler does not like that I am trying to combine the LIKE operator with the boolean <=,>= operators (Shown in the above method). Is there a way around this? I need to be able to display data between a range of dates but use the LIKE operator to search based only the first part of the element. Help appreciated greatly, Kind regards.
A slight alteration to the method, removing the LIKE operator worked...... ``` public void DisplayRecSmsByDateRange(string date1,string date2, string readDir) { DataSet ds = new DataSet("SMS DataSet"); XmlDataDocument xmlDatadoc = new XmlDataDocument(); xmlDatadoc.DataSet.ReadXml(readDir); ds = xmlDatadoc.DataSet; DataView custDV = new DataView(ds.Tables["SMS"]); custDV.RowFilter = String.Format("(DateTime >= '{0}*' and DateTime <= '{1}*')", EscapeLikeValue(date1), EscapeLikeValue(date2)); custDV.Sort = "DateTime"; this.dataGridView1.DataSource = custDV; } ```
I'll assume that you can modify/replace the EscapeLikeValue() method so that it returns only date part, e.g. "2009-09-27". This way you can rewrite the filter to something like: ``` custDV.RowFilter = String.Format("(DateTime >= '{0}' AND DateTime <='{1}')", EscapeLikeValue(date1) + "T00:00:00", EscapeLikeValue(date2) + "T23:59:59"); ``` HTH, Dejan
C# DataView Date Range with LIKE Operator?
[ "", "c#", "dataview", "sql-like", "date-range", "" ]
I want to disable the keyboard for an HTML SELECT tag so the user can only use a mouse to select the options. I've tried `event.cancelBubble=true` on the `onkeydown`, `onkeyup` and `onkeypress` events with no luck. Any ideas?
Someone left me the correct answer and then removed it for some reason, so here it is: ``` function IgnoreAlpha(e) { if (!e) { e = window.event; } if (e.keyCode >= 65 && e.keyCode <= 90) // A to Z { e.returnValue = false; e.cancel = true; } } ``` ``` <p> <select id="MySelect" name="MySelect" onkeydown="IgnoreAlpha(event);"> <option selected="selected " value=" " /> <option value="A ">A</option> <option value="B ">B</option> <option value="C ">C</option> </select> </p> ```
In a cross-browser way assuming that the event object has been properly initialized: ``` function disableKey(e) { var ev = e ? e : window.event; if(ev) { if(ev.preventDefault) ev.preventDefault(); else ev.returnValue = false; } } ```
Disable keyboard in HTML SELECT tag
[ "", "javascript", "html", "html-select", "dom-events", "" ]
Hey how do I showcase my themes like [WooThemes](http://www.woothemes.com/demo/?t=40) has done. I don't want to use multiple databases and Wordpress installations? Can you suggest me any reliable solution which lets me use the same database for all themes. Thanks
try the [Theme Switcher](http://plugins.trac.wordpress.org/wiki/ThemeSwitcher) plugin.
If all the themes use the same CSS setup (what I mean by that is all the id's and classes that you use for styling are the same in all the themes) then you could simple have a drop down menu with this JavaScript function: ``` function themeChange(selection) { window.location = "viewtemplate.php?theme=" + selection; } ``` And with this HTML: ``` <select onchange="themeChange(this.options[this.selectedIndex].value)"> <option value="0" selected="selected">Select Theme</option> <option value="1">Theme 1</option> <option value="2">Theme 2</option> </select> ``` Once the page loads you can use PHP to retrieve the theme selection value and then inject the correct CSS style sheet for that theme. PHP: ``` <?php $theme = $_GET['theme']; if ($theme == 1) { ?> <link rel="stylesheet" type="text/css" href="theme1.css"> <?php } else if ($theme == 2) { ?> <link rel="stylesheet" type="text/css" href="theme2.css"> <?php } ?> ``` Hope that helps :) Thanks
Wordpress Theme Demo
[ "", "php", "wordpress", "" ]
I'm C++ begginer. I did this excercise from Deitel's book: > Use a one-dimensional array to solve > the following problem. Read in 20 > numbers, each of which is between 10 > and 100, inclusive. As each number is > read, validate it and store it in the > array only if it is not a duplicate of > a number already read. After reading > all the values, display only the > unique values that the user entered. > Provide for the "worst case" in which > all 20 numbers are different. Use the > smallest possible array to solve this > problem. Here is my code: ``` #include <iostream> using namespace std; bool compare(int arrayNum[],int arraySize,int element); int main() { const int size=20; int i=1; int num[size]; int arrayElement; int counter=0; while(i<=20) { cin>>arrayElement; if(i==1) //stores first element in array num[0]=arrayElement; //compare new element with stored elements //if element is not a duplicate store it in array else if (compare(num,size,arrayElement)) { counter++; num[counter]=arrayElement; } i++; } //displays array elements for(int k=0;k<=counter;k++) cout<<num[k]<<endl; return 0; } //compare elements in array bool compare(int arrayNum[],int arraySize,int element) { for(int j=0;j<arraySize;j++) { if(arrayNum[j]==element) return false; } return true; } ``` It works, but I'm not sure if I have interpreted the task correctly. I assume then I don't have to include conditional statement for range of numbers (10 to 100 inclusive), as this will be read from the keyboard and input by me. Therefore why was this instruction included? Also at the end it says > use the smallest possible array I assume the max size has to be 20,but I don't think there is a way to dynamically expand array size (for example while storing new elements) as array size is const. I would appreciate if someone could help me with this. Any comments regarding code, or better solution are welcome.
> As each number is read, **validate > it** and store it in the array Emphasis mine. The text clearly says that your program has to validate the input. In other words, it has to check that the entered number is between 10 and 100, and if it is not, handle the error appropriately. So yes, you do need a conditional, although exactly what you do to handle the error is up to you. And you're right, since arrays aren't dynamically resizable, the array size has to be at least 20.
You do need a conditional. Basically it's saying to take in a number between 10 and 100. If it's not a number between those ranges, don't store it. Also, if that number already exists in the array, don't store it. Then just print out the values in the array. You assume correct about the array size, it's maximum size would be 20, although you may not store all 20 values (again, because some input might be bad).
C++ array excercise-help needed
[ "", "c++", "arrays", "" ]
I have data which I wish to be pasted into a textbox, it will be in the form E.G ``` Ryu Aiter D78:21:87:13 177 /177 1 / 6 Ryu Chronos D78:21:26:21 182 /182 0 / 6 Ryu Hermes D78:21:26:22 201 /201 0 / 6 Ryu Hefaistos D78:31:75:10 136 /136 1 / 2 Ryu Krotos D78:84:96:11 170 /170 1 / 6 Ryu Heros D78:65:51:31 175 /175 2 / 5 Ryu Arachnos D78:13:84:11 185 /185 0 / 5 ``` its splits up like this Base(max 16 chars) Location(staring D , 12 chars) econ/max econ (int/int) used/Total(int/int) What i wish to do is create a loop for each Row of text, and then inside that loop chop out each part of the row into variables for each component. as far as ideas on separating it i know that the : symbol is banned from names and bases. so if i find the first ":" then step back 2 and take the next 12 chars that is my location i know that can be done with a until loop and if(string[x]=':') But how do i loops through rows? And how can i separate the rest of the data in a row?
This is what regular expressions are for :P try this out: ``` $lines = explode( "\r\n", $data ); $users = array(); foreach( $lines as $line ) { $matches = array(); $user = array(); preg_match( "/([^ ]+) ([^ ]+) ((?:[A-Z])(?:[0-9]+:){3}[0-9]+) ([0-9]+) \/([0-9]+) ([0-9]+) \/ ([0-9]+)/", $line, $matches ); list(,$user['name'],$user['base'],$user['location'],$user['econ'],$user['maxecon'],$user['used'],$user['total']) = $matches; $users[] = $user; } ``` You will have an array called users which contains a series of associative arrays with the components. Like below... ``` Array ( [0] => Array ( [total] => 6 [used] => 1 [maxecon] => 177 [econ] => 177 [location] => D78:21:87:13 [base] => Aiter [name] => Ryu ) [1] => Array ( [total] => 6 [used] => 0 [maxecon] => 182 [econ] => 182 [location] => D78:21:26:21 [base] => Chronos [name] => Ryu ) etc, etc... ``` EDIT: I made a lot of assumptions about the data as you haven't given many details, if you need further help with the expression let me know. UPDATE AS PER YOUR COMMENT: ``` Line 182: $name = htmlspecialchars(mysql_real_escape_string($_POST['name'])); Line 188: $tecon = htmlspecialchars(mysql_real_escape_string($user['econ'])); ``` You should turn on display\_errors as they were simple syntax errors that could easily be debugged.
Extending the same idea i am trying to use preg match for a single line on another page. i use the code ``` $data = $_POST['list']; $matches = array(); $user = array(); preg_match( "/(.+?) ((?:[A-Z])(?:[0-9]+:){3}[0-9]+) ([0-9]+) \/([0-9]+) ([0-9]+) \/ ([0-9]+)/", $data, $matches ); list(,$user['base'],$user['location'],$user['econ'],$user['maxecon'],$user['used'],$user['total']) = $matches; $base = $users['base']; $location = $users['location']; $tecon = $users['econ']; ``` i used echo to print out £data and it contains the data as expected but the same code without the lines loop does not seperate the parts of my data into the array..in fact the array size of $user remains empty, what has gone wroung?
String parser/separation in PHP
[ "", "php", "string", "" ]
I need to show form as top level system-wide, e.g. over /all/ other windows on screen. I do realize this is usually /bad UI practice/, but I have very specific scenario in mind. We intend to use normal Windows PCs for POS cash registrators. There is an option on the screen to open cash drawer. It would be rather bad for someone just to press something on a screen and get access to money when clerk isn't looking. So we equiped PCs with RFID readers and each clerk has his/her own RFID card which will be used for authentication. I need however an mechanism to lock the computer (or make it unusable) when clerk goes away. Logging off seems too much of a nuisance. Any ideas welcome. LP, Dejan
Well, after a day of trial and error I came to sort of solution. It involves the following steps: 1. When "Lock" button is pressed new (empty) /desktop/ is created. Program is run in this desktop with full screen form and login procedure. There is nothing else to switch to or run on this desktop. 2. Task manager is disabled via registry. Of course, somebody uninvited can still access the Ctrl-Alt-Delete menu, but there is nothing of particular harm he can do there. 3. Alt-F4 and such are disabled. 4. When authentication is made, program switches back to original desktop and everything proceeds as normal. There is some P/Invoking required, of course. If someone wants to do something similar, perhaps s/he will find my bare bones example helpful - [link text](http://infoteh.si/LockExample.zip) LP, Dejan
I think you'll need to look into calling down to the Win32 API to achieve this. You'll need to look into: [ShowWindow](http://www.pinvoke.net/default.aspx/user32/ShowWindow.html) and [SetWindowPos](http://www.pinvoke.net/default.aspx/user32/SetWindowPos.html) and invoke them with code similar to the following (note this is pseudo-code): ``` [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); static void ShowTopmost(Form frm) { ShowWindow(frm.Handle, SW_SHOWMAXIMIZED); SetWindowPos(frm.Handle.ToInt32(), HWND_TOPMOST, 0, 0, [width of desktop], [height of desktop], SWP_SHOWWINDOW); } ```
How to make form system modal using C#?
[ "", "c#", ".net", "security", "" ]
I am doing RSA encryption and I have to split my long string into small byte[] and encrypt them. I then combine the arrays and convert to string and write to a secure file. Then encryption creates byte[128] I use this the following to combine: ``` public static byte[] Combine(params byte[][] arrays) { byte[] ret = new byte[arrays.Sum(x => x.Length)]; int offset = 0; foreach (byte[] data in arrays) { Buffer.BlockCopy(data, 0, ret, offset, data.Length); offset += data.Length; } return ret; } ``` When I decrypt I take the string, convert it to a byte[] array and now need to split it to decode the chunks and then convert to string. Any ideas? Thanks **EDIT:** I think I have the split working now however the decryption fails. Is this because of RSA keys etc? At TimePointA it encrypts it, then at TimePointB it tries to decrypt and it fails. The public keys are different so not sure if that is the issue.
When you decrypt, you can create one array for your decrypt buffer and reuse it: Also, normally RSA gets used to encrypt a symmetric key for something like AES, and the symmetric algorithm is used to encrypt the actual data. This is *enormously* faster for anything longer than 1 cipher block. To decrypt the data, you decrypt the symmetric key with RSA, followed by decrypting the data with that key. ``` byte[] buffer = new byte[BlockLength]; // ASSUMES SOURCE IS padded to BlockLength for (int i = 0; i < source.Length; i += BlockLength) { Buffer.BlockCopy(source, i, buffer, 0, BlockLength); // ... decode buffer and copy the result somewhere else } ``` Edit 2: If you are storing the data as strings and not as raw bytes, use `Convert.ToBase64String()` and `Convert.FromBase64String()` as the safest conversion solution. Edit 3: From his edit: ``` private static List<byte[]> splitByteArray(string longString) { byte[] source = Convert.FromBase64String(longString); List<byte[]> result = new List<byte[]>(); for (int i = 0; i < source.Length; i += 128) { byte[] buffer = new byte[128]; Buffer.BlockCopy(source, i, buffer, 0, 128); result.Add(buffer); } return result; } ```
I'd say something like this would do it: ``` byte[] text = Encoding.UTF8.GetBytes(longString); int len = 128; for (int i = 0; i < text.Length; ) { int j = 0; byte[] chunk = new byte[len]; while (++j < chunk.Length && i < text.Length) { chunk[j] = text[i++]; } Convert(chunk); //do something with the chunk } ```
C# Split byte[] array
[ "", "c#", "c#-3.0", "split", "arrays", "" ]
I'm looking to experiment with developing an Outlook plugin. I'm using the express edition of Visual Studio, and it seems the Outlook integration feature is missing from the Express edition (intentionally). Is that indeed the case? Are there 3rd party libraries that allow connecting to the Outlook model with the Express edition? Thanks
You only need to install the [Office Interop Assemblies](http://msdn.microsoft.com/en-us/library/bb652780.aspx) and reference those.. then you should be good to go.
Have a look at [Hacking Outlook](http://www.i-programmer.info/projects/38-windows/222-hacking-outlook-com-interop.html) The big problem is that OUtlook Express is something that Microsoft really don't want you to extend and the COM interface is far from complete, far from documented and infact definitely not the recommended way to do things. However there isn't a recommended way so the only choice left is to use what you can i.e. the COM interface. So automate the interace you are basically back to old techniques such as using Windows messages and hooking the interface - good luck it isn't easy. PS -- Full Outlook is another matter and is just a matter of creating a standard Office add in.
Developing Outlook plugin with Visual C# 2008 Express?
[ "", "c#", "outlook", "visual-studio-express", "" ]
In ASP.net Generic handler files (.ashx) Sessions are by default not enabled, the sessions collection is empty no matter what. But by simply implementing the "ISessionHandler", sessions are suddenly accessable though the sessions collection.. I really dont understand that, becuase in my head interfaces doesnt do anything other than telling other stuff what methods, properties etc. it needs to have. Does anyone know how that works? Thanks in advance :)
These interfaces are simply used by HttpContext. If you look at the Handler property of that in reflector, you will see the following: ``` set { this._handler = value; this.RequiresSessionState = false; this.ReadOnlySessionState = false; this.InAspCompatMode = false; if (this._handler != null) { if (this._handler is IRequiresSessionState) { this.RequiresSessionState = true; } if (this._handler is IReadOnlySessionState) { this.ReadOnlySessionState = true; } Page page = this._handler as Page; if ((page != null) && page.IsInAspCompatMode) { this.InAspCompatMode = true; } } } ``` With the key bit being: ``` if (this._handler is IReadOnlySessionState) { this.ReadOnlySessionState = true; } ``` As others have said they are marker interfaces used by HttpContext to establish what capabilities it should have. The IHttpHandler's ProcessRequest takes in a HttpContext, hence the relationship between the two.
These interface are I believe called Marker Interfaces, they "Mark" a purpose. Through reflection (i.e. checking if a class implements an Interface) or by chcking if class x is of type IInterface, you can enable certain functionality. **Edit:** Here's some more on the subject (it's about Java, but related) [link text](http://forums.sureshkumar.net/java-technologies/22355-question-marker-interface.html)
How does an Interface implement functionality?
[ "", "c#", "asp.net", "" ]
Assuming I have the following delegate ``` public delegate void ControlInitializer(Control control); ``` Is there a way when specifying the delegate to specify what type of control the input parameter is? e.g. Instead of ``` ControlInitializer one = c => ((TextBox)c).Text = "Init Value" ControlInitializer two = c => ((DropDownList)c).SelectedValue= "-1" ``` Can I do something like ``` ControlInitializer one = (TextBox c) => c.Text = "Init Value" ControlInitializer two = (DropDownList c) => c.SelectedValue= "-1" ``` As Textbox is a sub class of Control in this case? Update: I also need to store these 2 ControlInitialiser delegates in a e.g. ``` Dictionary<string, ControlInitializer> ``` will specifying ``` Dictionary<string, ControlInitializer<Control>> ``` Work in this case as I can't seem to get it to work. Thanks in advance.
You can make the delegate generic: ``` public delegate void ControlInitializer<TControl>(TControl control) where TControl : Control; ``` And then use it like this: ``` ControlInitializer<TextBox> one = c => c.Text = "Init Value"; ControlInitializer<DropDownList> two = c => c.SelectedValue = "-1"; ``` --- I guess your aiming for something like this: ``` var init = new Init(); init.RegisterInitializer<TextBox>(c => c.Text = "Init Value"); init.RegisterInitializer<DropDownList>(c => c.SelectValue = "-1"); foreach (var c in Controls) { init.ApplyInitializer(c); } ``` That's a bit difficult due to the reasons mentioned in *David B*'s answer. What you can do, however, is hide the type cast behind an abstraction, like this: ``` public class Init { private readonly Dictionary<Type, Action<Control>> initializers; ... public void RegisterInitializer<TControl>(Action<TControl> i) where T Control : Control { initializers.Add(typeof(TControl), c => i((TControl)c)); } public void ApplyInitializer(Control c) { initializers[c.GetType()](c); } } ```
First of all, use the predefined delegate [`Action`](http://msdn.microsoft.com/en-us/library/018hxwa8.aspx). As regards specifying the type, use generic arguments: ``` Action<TextBox, string> one = (c,v) => c.Text = v; ``` The `Action` delegate takes up to 4 arguments and doesn't return anything (`void`).
Specifying Specific Type of a Delegate Argument
[ "", "c#", "" ]
I'm trying to get my models related using ReferenceProperty, but not have a huge amount of luck. I have 3 levels: Group, Topic, then Pros, and Cons. As in a Group houses many topics, and within each topic could be many Pros and Cons. I am able to store new Groups nice and fine, but I don't have any idea how to store topics underneath these groups. I want to link from a page with a link "New topic" underneath each group, that takes them to a simple form (1 field for now). Obviously the URL will need to have some sort of reference to the id of the group or something. Here are my models: ``` class Groups(db.Model): group_user = db.UserProperty() group_name = db.StringProperty(multiline=True) group_date = db.DateTimeProperty(auto_now_add=True) class Topics(db.Model): topic_user = db.UserProperty() topic_name = db.StringProperty(multiline=True) topic_date = db.DateTimeProperty(auto_now_add=True) topic_group = db.ReferenceProperty(Groups, collection_name='topics') class Pro(db.Model): pro_user = db.UserProperty() pro_content = db.StringProperty(multiline=True) pro_date = db.IntegerProperty(default=0) pro_topic = db.ReferenceProperty(Topics, collection_name='pros') class Con(db.Model): con_user = db.UserProperty() con_content = db.StringProperty(multiline=True) con_date = db.IntegerProperty(default=0) con_topic = db.ReferenceProperty(Topics, collection_name='cons') ``` And one function for the actual page I want to show the list of Groups, and then underneath their topics: ``` class Summary(webapp.RequestHandler): def get(self): groups_query = Groups.all() groups = groups_query.fetch(1000) template_values = { 'groups': groups, } path = os.path.join(os.path.dirname(__file__), 'summary.html') self.response.out.write(template.render(path, template_values)) ``` And finally the html: ``` <html> <body> <a href="/newgroup">New Group</a> <br> {% for group in groups %} <font size="24">{{ group.group_name|escape }}</font><br> by <b>{{ group.group_user }}</b> at <b>{{ group.group_date }}</b> {{ group.raw_id }} <br> <a href="/newtopic?id={{group.key.id}}" >New topice </a> <br> <blockquote> {{ topics.topics_name }} </blockquote> {% endfor %} </body> </html> ```
Something that has side effects, such as altering the store (by creating a new object for example) should *NOT* be an HTTP `GET` -- GET should essentially only do "read" operations. This isn't pedantry, it's a key bit of HTTP semantics -- browsers, caches, proxies, etc, are allowed to act on GET as read-only operations (for example by caching results and not passing a request to the server if they can satisfy it from cache). For modifications, use HTTP verbs such as POST (most popular essentially because all browsers implement it correctly) or for specialized operations PUT (to create new objects) or DELETE (to remove objects). I assume you'll be going to use POST to support a variety of browsers. To get a POST from a browser, you need either Javascript wizardy or a plain old form with method=post -- I'll assume the latter for simplicity. If you're using Django 1.0 (which app engine supports now), it has its own mechanisms to make, validate and accept forms based on models. Other frameworks have their own similarly advanced layers. If you want to avoid "rich" frameworks you'll have to implement by hand templates for your HTML forms, direct them (via some kind of URL dispatching, e.g. in app.yaml) to a handler of yours implementing with a `def post(self):`, get the data from the request, validate it, form the new object, put it, display some acknowledgment page. What part or parts of the procedure are unclear to you? Your question's title focuses specifically on reference properties but I'm not sure what problem they are giving you in particular -- from the text of your question you appear to be on the right tack about them. **Edit**: the OP has now clarified in a comment that his problem is how to make something like: ``` "<a href="/newtopic?id={{group.key.id}}" >New topic </a>" ``` work. There's more than one way to do that. If the newtopic URL is served by a static form, the handler for the post "action" of that form could get back to that `id=` via the `Referer:` header (a notorious but unfixable mis-spelling), but that's a bit clunky and fragile. Better is to have the newtopic URI served by a handler whose `def get` gets the `id=` from the request and inserts it in the resulting form template -- for example, in a hidden input field. Have that form's template contain (among the other fields): ``` <INPUT TYPE=hidden NAME=thegroupid VALUE={{ theid }}> </INPUT> ``` put `theid` in the context with which you render that template, and it will be in the request that the `def post` of the action receiving the form finally gets.
Just to answer the question for others as you probably figured this out: ``` class NewTopic(webapp.RequestHandler): def get(self): groupId = self.request.get('group') # either get the actual group object from the DB and initialize topic with topic_group=object as in 'Nick Johnson's answer, or do as follows topic = Topic() topic.name = self.request.get("topicname") topic.reference = groupId topic.put() ```
Google app engine ReferenceProperty relationships
[ "", "python", "google-app-engine", "django-models", "model", "django-templates", "" ]
In codeigniter, as you know, a page of the form: `/class/function/ID`, where class is the controller name, function is the method within the controller, and ID is the parameter to pass to that method. The typical usage would be (for a book site for example) to pass the book id to the function which would then query the database for appropriate book. My problem is this: I was messing around and randomly (in the url string) typed in an ID that is not present in the database (with normal point and click browsing this would never happen) and I get database errors due to the residual queries I attempt to perform using a non-existent ID. I have written code to check if there are any rows returned before attempting to use the ID, but if the ID is non-existent I would like the user to get a 404 error page rather than a blank page or something (since this seems like proper functionality). This would need to be a true 404 page (not simply loading a view that looks like a 404 page) so as not to screw with search engines. Okay - so my question is this: within normal program logic flow (as described above) how can I force a 404 error using codeigniter? Thanks. **Update**: code igniter has a `show_404('page')` function but I don't think this will generate a true HTTP 404 error...
`show_404()` actually sends the proper headers for a search engine to register it as a 404 page (it sends 404 status). Use a Firefox addon to check the headers received when calling `show_404()`. You will see it sends the proper HTTP Status Code. Check the default `application/errors/error_404.php`. The first line is: ``` <?php header("HTTP/1.1 404 Not Found"); ?> ``` That line sets the HTTP Status as 404. It's all you need for the search engine to read your page as a 404 page.
``` $this->output->set_status_header('404'); ``` to generate 404 headers.
Codeigniter & PHP - forcing a 404?
[ "", "php", "codeigniter", "error-handling", "" ]
I'm looking for an ultra-easy way to generate a list of numbers, 1-200. (it can be a List, Array, Enumerable... I don't really care about the specific type) Apparently .Net 4.0 has a [Sequence.Range(min,max)](http://msdn.microsoft.com/en-us/vcsharp/aa336752.aspx) method. But I'm currently on .Net 3.5. Here is a sample usage, of what I'm after, shown with Sequence.Range. ``` public void ShowOutput(Sequence.Range(1,200)); ``` For the moment, I need consequitive numbers 1-200. In future iterations, I may need arbitrary lists of numbers, so I'm trying to keep the design flexible. Perhaps there is a good LINQ solution? Any other ideas?
.NET 3,5 has `Range` too. It's actually [`Enumerable.Range`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.range(v=vs.100).ASPX) and returns `IEnumerable<int>`. The page you linked to is very much out of date - it's talking about 3 as a "future version" and the `Enumerable` static class was called `Sequence` at one point prior to release. If you wanted to implement it yourself in C# 2 or later, it's easy - here's one: ``` IEnumerable<int> Range(int count) { for (int n = 0; n < count; n++) yield return n; } ``` You can easily write other methods that further filter lists: ``` IEnumerable<int> Double(IEnumerable<int> source) { foreach (int n in source) yield return n * 2; } ``` But as you have 3.5, you can use the extension methods in `System.Linq.Enumerable` to do this: ``` var evens = Enumerable.Range(0, someLimit).Select(n => n * 2); ```
``` var r = Enumerable.Range( 1, 200 ); ```
Simple Sequence Generation?
[ "", "c#", "linq", "sequence", "" ]
Please, help me to create a nested struct with an array. How do I fix this code? ``` class CMain { public: CMain(); ~CMain(); private: struct { CCheckSum() : BufferSize(500) {memset(Buffer, 0, BufferSize);} const int BufferSize; char Buffer[BufferSize]; }SmallBuffer; } ``` Thanks.
Static arrays need to know their length at compile time, or you need to dynamically allocate memory: ``` struct CCheckSum { CCheckSum() : BufferSize(500), Buffer(new char[BufferSize]) { memset(Buffer, 0, BufferSize); } ~CCheckSum() { delete[] Buffer; } // Note the use of delete[]! const int BufferSize; char* Buffer; }SmallBuffer; ``` You're probably better off using [std::vector](http://www.cplusplus.com/reference/stl/vector/) though: ``` struct CCheckSum { CCheckSum() : Buffer(500, 0) {} std::vector<char> Buffer; // A std::vector keeps // track of its size enternally }SmallBuffer; ```
Even though you declared `BufferSize` as `const`, at class scope this does not declare a compile-time constant, which is needed for declaring array sizes in C++, but a constant data member, which, once set in the constructor, cannot be changed anymore for the lifetime of the instance (but can still be different for each instance). Two solutions: Make 1. `BufferSize` `static const` at class scope, or 2. (just) `const` at namespace scope (including global scope).
nested struct with array
[ "", "c++", "initialization", "nested-class", "" ]
How can one get word wrap functionality for a `Label` for text which goes out of bounds?
The quick answer: switch **off** [AutoSize](http://msdn.microsoft.com/en-us/library/system.windows.forms.label.autosize%28v=vs.110%29.aspx). The big problem here is that the label will not change its height automatically (only width). To get this right you will need to subclass the label and include vertical resize logic. Basically what you need to do in OnPaint is: 1. Measure the height of the text (Graphics.MeasureString). 2. If the label height is not equal to the height of the text set the height and return. 3. Draw the text. You will also need to set the [ResizeRedraw](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.resizeredraw%28v=vs.110%29.aspx) style flag in the constructor.
Actually, the accepted answer is unnecessarily complicated. If you set the label to AutoSize, it will automatically grow with whatever text you put in it. (This includes vertical growth.) If you want to make it word wrap at a particular width, you can set the MaximumSize property. ``` myLabel.MaximumSize = new Size(100, 0); myLabel.AutoSize = true; ``` Tested and works.
Word wrap for a label in Windows Forms
[ "", "c#", ".net", "winforms", "label", "controls", "" ]
Using PHP.. Here is what I have.. I'm gonna explain the whole thing and maybe someone can help me with the logic and maybe point me in the right direction. I have a mail system I am working on. In the cc part, I am allowing the user to seperate the values by a semicolon, like so: 1;2;3;4... When these values are passed to my function, I am using explode to get them into an array. What I want to do is some checking first. I want to firstly make certain that the format is correct and that every value is correctly seperated. If not, I should show an error. Once this is done, I want to make certain that every number is actually valid. I can query the database, put the reslts into an array and was thinking to use the in\_array() function to verify this but I'm not certain that it will work. Can someone please help me out with the best way to handle this? Thanks. EDIT: What is the best way to detect a bogus value in the CSV list of values?
In order to verify that each number was correct seperated, you want to check that there is no whitespace in the answer. So something like this should work: ``` $text = trim($id); if(strpos(" ", $id) !== false) { //error } ``` Next, to check for the values, it is very simple ``` if(!in_array($id, $database_ids)) { // error } ``` Finally, if you are only using numeric values, check that the id is numeric ``` if(!is_numeric($id)) { //error } ``` To combine, wrap it into an array ``` foreach($exploded_array as $key => $id) { $id = trim(id); if(!is_numeric($id)) { //error } if(strpos(" ", $id) !== false) { //error } if(!in_array($id, $database_ids)) { // error } } ``` I hope the code was pretty self explanatory where it got the variables, but if you need me to explain more, feel free to ask.
As whichdan suggested, here is an implementation that relies on `array_filter()`: ``` <?php function checkValue($value) { $id = trim(id); if(!is_numeric($id)) { return false; } if(strpos(" ", $id) !== false) { return false; } if(!in_array($id, $database_ids)) { return false; } return true; } $values = '1;2;3;4'; $values_extracted = explode(';', $values); if(count($values) == count(array_filter($values_extracted), 'checkValue')) { // Input was successfully validated } ?> ```
PHP - Is there a way to verify all values in an array
[ "", "php", "" ]
My code looks like: `index.php`: ``` <html>.... <title>My page</title> .... <?php switch ($_GET['id']){ case "tips": include("tips.php"); $title = "Tips"; ... ``` How do I get the title varible to the html `title` tag? All pages pass through `index.php`.
Do your PHP before your HTML output. ``` <?php switch ($_GET["id"]) { case "tips": $title = "Tips"; $page = "tips.php"; } ?> <html> <head> <title><?php print $title; ?></title> </head> <body> <?php include($page); ?> </body> </html> ```
You can also do this with output buffering and a little string replacement. ``` <?php ob_start('ob_process'); ?> <html>.... <title>{{{TITLE}}}</title> .... <?php switch ($_GET['id']){ case "tips": include("tips.php"); $title = "Tips"; break; } function ob_process($buffer) { global $title; $buffer = str_replace('{{{TITLE}}}', $title, $buffer); return $buffer; } ```
How do I dynamically populate the <title> tag in a PHP page?
[ "", "php", "html", "" ]
I have two different WinForms applications, AppA & AppB. Both are running .NET 2.0. In AppA I want to open AppB, but I need to pass command-line arguments to it. How do I consume the arguments that I pass in the command line? This is my current main method in AppB, but I don't think you can change this? ``` static void main() { } ```
``` static void Main(string[] args) { // For the sake of this example, we're just printing the arguments to the console. for (int i = 0; i < args.Length; i++) { Console.WriteLine("args[{0}] == {1}", i, args[i]); } } ``` The arguments will then be stored in the `args` string array: ``` $ AppB.exe firstArg secondArg thirdArg args[0] == firstArg args[1] == secondArg args[2] == thirdArg ```
The best way to work with args for your winforms app is to use ``` string[] args = Environment.GetCommandLineArgs(); ``` You can probably couple this with the use of an **enum** to solidify the use of the array througout your code base. > "And you can use this anywhere in your application, you aren’t just > restricted to using it in the main() method like in a console > application." Found at:[HERE](http://www.howtogeek.com/howto/programming/get-command-line-arguments-in-a-windows-forms-application/)
How do I pass command-line arguments to a WinForms application?
[ "", "c#", "winforms", "command-line", "" ]
JavaScript code I'm starting with: ``` function doSomething(url) { $.ajax({ type: "GET", url: url, dataType: "xml", success: rssToTarget }); } ``` Pattern I would like to use: ``` //where elem is the target that should receive new items via DOM (appendChild) function doSomething(url, elem) { $.ajax({ type: "GET", url: url, dataType: "xml", success: rssToTarget(elem) }); } ``` I don't think I can get the callback to work this way, right? What is the proper pattern? I don't want to use global variables necessarily to temporarily hold the `elem` or elem name.
Like this... ``` function doSomething(url, elem) { $.ajax({ type: "GET", url: url, dataType: "xml", success: function(xml) { rssToTarget(xml, elem); } }); } ``` Answer to your comment: [Does use of anonymous functions affect performance?](https://stackoverflow.com/questions/80802/does-use-of-anonymous-functions-affect-performance)
The pattern you'd like to use could work if you create a [closure](http://www.javascriptkit.com/javatutors/closures.shtml) inside your rssToTarget function: ``` function rssToTarget(element) { return function (xmlData) { // work with element and the data returned from the server } } function doSomething(url, elem) { $.ajax({ type: "GET", url: url, dataType: "xml", success: rssToTarget(elem) }); } ``` When `rssToTarget(elem)` is executed, the element parameter is stored in the [closure](http://www.javascriptkit.com/javatutors/closures.shtml), and the callback function is returned, waiting to be executed.
jQuery / Ajax - $.ajax() Passing Parameters to Callback - Good Pattern to Use?
[ "", "javascript", "jquery", "ajax", "callback", "" ]
What are the advantages of having declarations in a .inl file? When would I need to use the same?
`.inl` files are never mandatory and have no special significance to the compiler. It's just a way of structuring your code that provides a hint to the humans that might read it. I use `.inl` files in two cases: * For definitions of inline functions. * For definitions of function templates. In both cases, I put the declarations of the functions in a header file, which is included by other files, then I `#include` the `.inl` file at the bottom of the header file. I like it because it separates the interface from the implementation and makes the header file a little easier to read. If you care about the implementation details, you can open the `.inl` file and read it. If you don't, you don't have to.
[Nick Meyer](https://stackoverflow.com/questions/1208028/significance-of-a-inl-file-in-c/1208062#1208062) is right: The compiler doesn't care about the extension of the file you're including, so things like ".h", ".hpp", ".hxx", ".hh", ".inl", ".inc", etc. are a simple convention, to make it clear what the files is supposed to contain. The best example is the STL header files which have no extension whatsoever. Usually, ".inl" files do contain *inline* code (hence the ".inl" extension). Those files ".inl" files are a necessity when you have a dependency cycle between **header** code. For example: ``` // A.hpp struct A { void doSomethingElse() { // Etc. } void doSomething(B & b) { b.doSomethingElse() ; } } ; ``` And: ``` // B.hpp struct B { void doSomethingElse() { // Etc. } void doSomething(A & a) { a.doSomethingElse() ; } } ; ``` There's no way you'll have it compile, including using forward declaration. The solution is then to break down definition and implementation into two kind of header files: * `hpp` for header declaration/definition * `inl` for header implementation Which breaks down into the following example: ``` // A.hpp struct B ; struct A { void doSomethingElse() ; void doSomething(B & b) ; } ; ``` And: ``` // A.inl #include <A.hpp> #include <B.hpp> inline void A::doSomethingElse() { // Etc. } inline void A::doSomething(B & b) { b.doSomethingElse() ; } ``` And: ``` // B.hpp struct A ; struct B { void doSomethingElse() ; void doSomething(A & a) ; } ; ``` And: ``` // B.INL #include <B.hpp> #include <A.hpp> inline void B::doSomethingElse() { // Etc. } inline void B::doSomething(A & a) { a.doSomethingElse() ; } ``` This way, you can include whatever ".inl" file you need in your own source, and it will work. Again, the suffix names of included files are not really important, only their uses.
Significance of a .inl file in C++
[ "", "c++", "" ]
I have been trying to learn and apply domain driven concept into my software development. The first thing that I try to do is creating my domain model based on business logic needs. I often also use OR Mapping tool, such as LLBLGen, NHibernate, or Linq to SQL, to create data model and data access layer. The domain model and data model, however, are often very similar which make me wonder what benefit I really get by maintaining two models. Can someone share their practical thoughts about domain driven design? Furthermore, how would you deal with data model or data access layer when applying DDD in your application? Thanks in advance. **EDIT** Found a good [article](https://web.archive.org/web/20110503184234/http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/10/08/the-repository-pattern.aspx), with sample code, about Repository Pattern.
I abstract my data access via the Repository pattern, so keep my domain objects completely POCO and data provider agnostic. This allows me to sculpt my application from a domain perspective, concentrating on the logic, primarily via Unit Tests. Once this has settled I put in the Presentation layer (usually web pages) and then commit to the concrete database schema. I then implement my concrete Repository classes, which can be L2S. I've drafted a couple of articles here - <http://www.duncangunn.me.uk/dasblog/2009/04/11/TheRepositoryPattern.aspx> <http://www.duncangunn.me.uk/dasblog/2009/06/27/MockingLinqToSQLRepositories.aspx> Keep an eye out over the next couple of weeks as I will be documenting and providing sample code of my implementation which uses Unit of Work pattern also.
We map domain objects directly to the database, means that we do not have separate layer for data access, and rather we treat this as infrastructure code. We use [Fluent NHibernate](http://fluentnhibernate.org/) for most of the configuration.
Best practice to apply domain driven design in .NET?
[ "", "c#", ".net", "domain-driven-design", "" ]
I have a bit of XML as follows: ``` <section> <description> <![CDATA[ This is a "description" that I have formatted ]]> </description> </section> ``` I'm accessing it using `curXmlNode.SelectSingleNode("description").InnerText` but the value returns ``` \r\n This is a "description"\r\n that I have formatted ``` instead of ``` This is a "description" that I have formatted. ``` Is there a simple way to get that sort of output from a CDATA section? Leaving the actual CDATA tag out seems to have it return the same way.
You can use Linq to read CDATA. ``` XDocument xdoc = XDocument.Load("YourXml.xml"); xDoc.DescendantNodes().OfType<XCData>().Count(); ``` It's very easy to get the Value this way. Here's a good overview on MSDN: <http://msdn.microsoft.com/en-us/library/bb308960.aspx> for .NET 2.0, you probably just have to pass it through Regex: ``` string xml = @"<section> <description> <![CDATA[ This is a ""description"" that I have formatted ]]> </description> </section>"; XPathDocument xDoc = new XPathDocument(new StringReader(xml.Trim())); XPathNavigator nav = xDoc.CreateNavigator(); XPathNavigator descriptionNode = nav.SelectSingleNode("/section/description"); string desiredValue = Regex.Replace(descriptionNode.Value .Replace(Environment.NewLine, String.Empty) .Trim(), @"\s+", " "); ``` that trims your node value, replaces newlines with empty, and replaces 1+ whitespaces with one space. I don't think there's any other way to do it, considering the CDATA is returning significant whitespace.
I think the best way is... ``` XmlCDataSection cDataNode = (XmlCDataSection)(doc.SelectSingleNode("section/description").ChildNodes[0]); string finalData = cDataNode.Data; ```
Decode CDATA section in C#
[ "", "c#", ".net", "xml", "xmldocument", "cdata", "" ]
I seem to be having problems with my java gui code, and I have no idea why it's not working. What needs to happen is when the mouse is clicked on the **panel** or frame - *for now lets just say panel; as this is just a test eventually this code will be implemented for another gui component, but I'd like to get this working first* - the **popup menu** needs to become visible and the focus needs to be set on the **text field**. Then when the user presses enter or the focus on the text field is lost then the popup menu needs to hide and the text reset to blank or whatever I need it to be. So this is what I wrote: ``` public class Test { private final JFrame frame = new JFrame(); private final JPanel panel = new JPanel(); private final JPopupMenu menu = new JPopupMenu(); private final JTextField field = new JTextField(); private final Obj obj; //... constructor goes here public void test(){ frame.setSize(new Dimension(200,200)); field.setColumns(10); field.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { obj.method(field.getText()); menu.setVisible(false); field.setText(""); } }); field.addFocusListener(new FocusListener() { public void focusLost(FocusEvent e) { menu.setVisible(false); field.setText(""); } //... focus gained event goes here }); panel.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { menu.setLocation(e.getX(), e.getY()); menu.setVisible(true); field.requestFocusInWindow(); } //... other mouse events go here }); menu.add(field); frame.getContentPane().add(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } ``` With the code as it is written here the menu automatically hides right after I click. It just flashes on screen briefly and then hides without me doing anything else. If I change the code to exclude any occurrences of `menu.setVisible(false)` then the text field will never gain focus. Is this due to a misuse of JPopupMenu? Where am I going wrong? Also note that I left out main or Obj. They are in another file and most likely insignificant to this problem. Obj.method() does nothing and main only calls Test's constructor and test() method.
This code should work the way you want it to work (hopefully you follow the use of anonymous classes: ``` public class Test { public static void main(String[] args) { Test test = new Test(); test.test(); } private JFrame frame; private JPanel panel; private JPopupMenu menu; private JTextField field; public Test() { frame = new JFrame(); frame.setSize(new Dimension(200, 200)); frame.getContentPane().add(getPanel()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private JPanel getPanel() { if (panel == null) { panel = new JPanel(); panel.setComponentPopupMenu(getMenu()); panel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { menu.show(panel, e.getX(), e.getY()); } }); } return panel; } private JPopupMenu getMenu() { if (menu == null) { menu = new JPopupMenu() { @Override public void setVisible(boolean visible) { super.setVisible(visible); if (visible) { getField().requestFocus(); } } }; menu.add(getField()); } return menu; } private JTextField getField() { if (field == null) { field = new JTextField(); field.setColumns(10); field.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getMenu().setVisible(false); } }); } return field; } public void test() { frame.setVisible(true); } } ``` The key things to notice are when we setup the pop-up menu: ``` panel.setComponentPopupMenu(getMenu()); panel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent event) { getMenu().show(getPanel(), event.getX(), event.getY()); } }); ``` And how you request focus for the text field when the pop up menu is visible, which is accomplished through the text field requesting focus, but not focus in window since it doesn't exist in the window, only in the menu: ``` menu = new JPopupMenu() { @Override public void setVisible(boolean visible) { super.setVisible(visible); if (visible) { getField().requestFocus(); } } }; ``` And finally how the text field dismisses the pop up menu: ``` field.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getMenu().setVisible(false); } }); ```
I'd like to point out that I'm discovering through usage of the suggested methods that `setComponentPopupMenu()` automatically adds a MouseListener to display the given PopupMenu which then consumes the right-click event. so whatever is inside the `if(e.isPopupTrigger())` structure is never run on right clicks because the event is consumed. So essentially I get the behavour specified in my question just by adding `panel.setComponentPopupMenu(getMenu())`, but the fact that it's consuming all my right-click events, not just mouseClicked, is extremely limiting.
Problems with swing components and awt events
[ "", "java", "user-interface", "swing", "events", "awt", "" ]
Faulty code: ``` pos_1 = 234 pos_n = 12890 min_width = len(str(pos_n)) # is there a better way for this? # How can I use min_width as the minimal width of the two conversion specifiers? # I don't understand the Python documentation on this :( raw_str = '... from %(pos1)0*d to %(posn)0*d ...' % {'pos1':pos_1, 'posn': pos_n} ``` Required output: ``` ... from 00234 to 12890 ... ______________________EDIT______________________ ``` New code: ``` # I changed my code according the second answer pos_1 = 10234 # can be any value between 1 and pos_n pos_n = 12890 min_width = len(str(pos_n)) raw_str = '... from % *d to % *d ...' % (min_width, pos_1, min_width, pos_n) ``` New Problem: There is one extra whitespace (I marked it *\_*) in front of the integer values, for intigers with *min\_width* digits: ``` print raw_str ... from _10234 to _12890 ... ``` Also, I wonder if there is a way to add Mapping keys?
``` pos_1 = 234 pos_n = 12890 min_width = len(str(pos_n)) raw_str = '... from %0*d to %0*d ...' % (min_width, pos_1, min_width, pos_n) ```
``` "1234".rjust(13,"0") ``` Should do what you need addition: ``` a = ["123", "12"] max_width = sorted([len(i) for i in a])[-1] ``` put max\_width instead of 13 above and put all your strings in a single array a (which seems to me much more usable than having a stack of variables). additional nastyness: (Using array of numbers to get closer to your question.) ``` a = [123, 33, 0 ,223] [str(x).rjust(sorted([len(str(i)) for i in a])[-1],"0") for x in a] ``` Who said Perl is the only language to easily produce braindumps in? If regexps are the godfather of complex code, then list comprehension is the godmother. (I am relatively new to python and rather convinced that there must be a max-function on arrays somewhere, which would reduce above complexity. .... OK, checked, there is. Pity, have to reduce the example.) ``` [str(x).rjust(max([len(str(i) for i in a]),"0") for x in a] ``` And please observe below comments on "not putting calculation of an invariant (the max value) inside the outer list comprehension".
python String Formatting Operations
[ "", "python", "string", "formatting", "" ]
I'm trying to create a centralized folder (in some kind of a "meta project" in my eclipse workspace) for commonly used JAR files for referenced projects in this workspace. It should work similar to the WEB-INF/lib folder for web projects but also apply to non web projects, and automatically scan and add all jar files in this folder. I tried to create a user library with these jar files and reference them in the project but I still have to add every new jar manually to the user library (and don't know if it is referenced relative of absoulute) and Tomcat (WTP) doesn't seem to take these files (Run As -> Run on Server) into its classpath (and I don't want to duplicate the jars and put them into WEB-INF/lib). Any ideas?
+1 for Ivy. If you'd rather do it in a separated project in Eclipse: You added the 'common project' as on dependency for other projects (Java Build Path->Projects, then Add). But, have you exported the jars of the 'common project'? (In the common project: Java Build Path->Order and Export, then check all jars).
I would recommend against this, it becomes a pain in the butt when you have lots of projects with overlapping dependencies. What if Project X uses commons-logging-1.0 but someone creates Project Z which really needs commons-logging-1.1 instead? Do you want your central folder to have copies of the same JAR for each possible version number? Use a build tool like Maven or Ivy which will download and handle dependent JARs for you. The maven-eclipse plugin does a pretty good job of generating `.project`/`.classpath` files for Eclipse which will automatically put all dependent JARs on the build path, and m2eclipse is also good at handling dependencies from within Eclipse.
JAR file folder for eclipse projects
[ "", "java", "eclipse", "tomcat", "jar", "" ]
The codebase I've inherited seems to have a bunch of public variables, and as I come across them I tend to convert them into properties, document them, and format them according to our stylecop rules (it's my own little version of kaizen - eventually the codebase will be clean) but I was just wondering if there is a good search string that I could use in vs to find all of the public variables in the project?
I am not a regex expert but you can use RegEx in VS find window. Just Ctrl+Shift+F to open Find in Files and in Find Options check off Use Regular Expressions. this should give you something **public [^(){}]\*[;]**
You can use the following RegEx to find them all: ``` public:b+{{new|static|readonly|volatile|const}:b+}*{:i}:b+{:i}:b+; ``` The first and second capture are the additional field modifiers besides public. The third capture is the type, the fourth is the field name. Keep in mind the standard doesn't require that the access modifier come before any of the other valid field modifiers, so you may want to prepend `{{new|static|readonly|volatile|const}:b+}*` to the beginning for completeness. It isn't really required for most code.
visual studio search string for public variables?
[ "", "c#", "visual-studio", "" ]
Let's say that I've got a : ``` #include <utility> using namespace std; typedef pair<int, int> my_pair; ``` how do I initialize a const my\_pair ?
Use its constructor: ``` const my_pair p( 1, 2 ); ```
With C++11 you can also use one of the following: ``` const my_pair p = {2, 3}; const my_pair p({2, 3}); const my_pair p{2, 3}; ```
How do I initialize a const std::pair?
[ "", "c++", "stl", "std-pair", "" ]
I am having a property of `int` type in my view model which is bound to a `TextBox`. Everything works properly, `TwoWay` binding works fine except in one case - If I clear the value of `TextBox`, property setter doesn't gets called and although value is cleared in `TextBox`, property still holds the previous value. has anyone faced similar issue? is there any workaround for this? Here is the property - ``` public int MaxOccurrences { get { return this.maxOccurrences; } set { if (this.maxOccurrences != value) { this.maxOccurrences = value; base.RaisePropertyChanged("MaxOccurrences"); } } } ``` Here is how I am binding the property in xaml - ``` <TextBox Text="{Binding Path=MaxOccurrences, Mode=TwoWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center" Width="30" Margin="0,0,5,0"/> ```
I had the similar problem. You just need to update the code as: ``` <TextBox Text="{Binding Path=MaxOccurrences, Mode=TwoWay, TargetNullValue={x:Static sys:String.Empty}, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center" Width="30" Margin="0,0,5,0"/> ```
This is partially a guess (I haven't got VS handy right now to try it out), but I think it's because a cleared text box is an empty `string` (`""`), which can't be implicitly converted to an `int`. You should probably implemented a type converter to provide the conversion for you. (you probably want to do something like convert "" to 0)
WPF binding not working properly with properties of int type
[ "", "c#", ".net", "wpf", "xaml", "data-binding", "" ]
Does anyone know if the provided SQL and Active Directory Membership Providers in ASP.NET 2.0+ are HIPAA compliant? Clarification: I understand that HIPAA mandates patient information be secured and that certain policies be put in place to secure access to that information. Can Microsoft's SQL and AD Membership Providers be used for handling the authentication of users accessing this information? I expect there to be some policies that need to be established like password length and complexity but is there anything inherit about the way they store information that would invalidate them for the purposes of authorization? Any gotchas or things to look out for?
It depends on what you want to do with them, but in short, yes. HIPAA is all about standards for securing your data; the standards aren't particularly harsh, so long as you have a way in place to provide for security. In that way, it's a lot like ISO 9001; so long as you define a security policy and stick with it, you're okay. The mentioned providers are effectively tools. That said, you may need to do some additional things with your data to assure that it's only clearly accessible from your application; some level of pre-encryption would probably be appropriate. Just understand that it probably doesn't need to be HEAVY encryption; very light would do, so long as you're consistent with the application of it.
I sure hope it is;) We currently use the 2.0 Membership Provider with an ADAM LDAP at the health insurance company that I work for. HIPAA and PHI are the name of the game here and this set up went through our legal department.
Membership Providers and HIPAA Compliance
[ "", "c#", "asp.net", "membership-provider", "hipaa", "" ]
What is the best strategy to refactor a Singleton object to a cluster environment? We use Singleton to cache some custom information from Database. Its *mostly* read-only but gets refreshed when some particular event occurs. Now our application needs to be deployed in a Clustered environment. By definition, each JVM will have its own Singleton instance. So the cache may be out-of-sync between the JVM's when a refresh event occurs on a single node and its cache is refreshed. What is the best way to keep the cache's in sync? Thanks. Edit: The cache is mainly used to provide an autocomplete list (performance reasons) to UI and we use Websphere. So any Websphere related tips welcome.
The simplest approaches are: 1. Add an expiry timer to your singleton cache so that every so often the cache gets purged and subsquent calls fetch the updated data from source (e.g. a database) 2. Implement a notification mechanism for the cache using something like a JMS topic/tibRV. Get each cache instance to subscribe and react to any change messages broadcast on this topic.
Replace your singleton cache with a distributed cache. One such cache could be [JBoss Infinispan](http://www.jboss.org/infinispan) but I'm sure that other distributed cache and grid technologies exist, including commercial ones which are probably more mature at this point. For singleton objects in general, I'm not sure. I think I'd try to not have singletons in the first place.
Singleton in Cluster environment
[ "", "java", "singleton", "websphere", "cluster-computing", "" ]
I would like to know how you can prevent to use of two same tags in a database table. One said me that use two private keys in a table. However, W3Schools -website says that it is impossible. **My relational table** [alt text http://files.getdropbox.com/u/175564/db/db7.png](http://files.getdropbox.com/u/175564/db/db7.png) **My logical table** [alt text http://files.getdropbox.com/u/175564/db/db77.png](http://files.getdropbox.com/u/175564/db/db77.png) **The context of tables** [alt text http://files.getdropbox.com/u/175564/db/db777.png](http://files.getdropbox.com/u/175564/db/db777.png) **How can you prevent the use of duplicate tags in a question?**
I have updated my NORMA model to more closely match your diagram. I can see where you've made a few mistakes, but some of them may have been due to my earlier model. I have updated this model to prevent duplicate tags. It didn't really matter before. But since you want it, here it is (for Postgres): ``` START TRANSACTION ISOLATION LEVEL SERIALIZABLE, READ WRITE; CREATE SCHEMA so; SET search_path TO SO,"$user",public; CREATE DOMAIN so.HashedPassword AS BIGINT CONSTRAINT HashedPassword_Unsigned_Chk CHECK (VALUE >= 0); CREATE TABLE so."User" ( USER_ID SERIAL NOT NULL, USER_NAME CHARACTER VARYING(50) NOT NULL, EMAIL_ADDRESS CHARACTER VARYING(256) NOT NULL, HASHED_PASSWORD so.HashedPassword NOT NULL, OPEN_ID CHARACTER VARYING(512), A_MODERATOR BOOLEAN, LOGGED_IN BOOLEAN, HAS_BEEN_SENT_A_MODERATOR_MESSAGE BOOLEAN, CONSTRAINT User_PK PRIMARY KEY(USER_ID) ); CREATE TABLE so.Question ( QUESTION_ID SERIAL NOT NULL, TITLE CHARACTER VARYING(256) NOT NULL, WAS_SENT_AT_TIME TIMESTAMP NOT NULL, BODY CHARACTER VARYING NOT NULL, USER_ID INTEGER NOT NULL, FLAGGED_FOR_MODERATOR_REMOVAL BOOLEAN, WAS_LAST_CHECKED_BY_MODERATOR_AT_TIME TIMESTAMP, CONSTRAINT Question_PK PRIMARY KEY(QUESTION_ID) ); CREATE TABLE so.Tag ( TAG_ID SERIAL NOT NULL, TAG_NAME CHARACTER VARYING(20) NOT NULL, CONSTRAINT Tag_PK PRIMARY KEY(TAG_ID), CONSTRAINT Tag_UC UNIQUE(TAG_NAME) ); CREATE TABLE so.QuestionTaggedTag ( QUESTION_ID INTEGER NOT NULL, TAG_ID INTEGER NOT NULL, CONSTRAINT QuestionTaggedTag_PK PRIMARY KEY(QUESTION_ID, TAG_ID) ); CREATE TABLE so.Answer ( ANSWER_ID SERIAL NOT NULL, BODY CHARACTER VARYING NOT NULL, USER_ID INTEGER NOT NULL, QUESTION_ID INTEGER NOT NULL, CONSTRAINT Answer_PK PRIMARY KEY(ANSWER_ID) ); ALTER TABLE so.Question ADD CONSTRAINT Question_FK FOREIGN KEY (USER_ID) REFERENCES so."User" (USER_ID) ON DELETE RESTRICT ON UPDATE RESTRICT; ALTER TABLE so.QuestionTaggedTag ADD CONSTRAINT QuestionTaggedTag_FK1 FOREIGN KEY (QUESTION_ID) REFERENCES so.Question (QUESTION_ID) ON DELETE RESTRICT ON UPDATE RESTRICT; ALTER TABLE so.QuestionTaggedTag ADD CONSTRAINT QuestionTaggedTag_FK2 FOREIGN KEY (TAG_ID) REFERENCES so.Tag (TAG_ID) ON DELETE RESTRICT ON UPDATE RESTRICT; ALTER TABLE so.Answer ADD CONSTRAINT Answer_FK1 FOREIGN KEY (USER_ID) REFERENCES so."User" (USER_ID) ON DELETE RESTRICT ON UPDATE RESTRICT; ALTER TABLE so.Answer ADD CONSTRAINT Answer_FK2 FOREIGN KEY (QUESTION_ID) REFERENCES so.Question (QUESTION_ID) ON DELETE RESTRICT ON UPDATE RESTRICT; COMMIT WORK; ``` Note that there is now a separate Tag table with `TAG_ID` as the primary key. `TAG_NAME` is a separate column with a uniqueness constraint over it, preventing duplicate tags. The `QuestionTaggedTag` table now has (`QUESTION_ID`, `TAG_ID`), which is also its primary key. I hope I didn't go too far in answering this, but when I tried to write smaller answers, I kept having to untangle my earlier answers, and it seemed simpler just to post this.
You can create a unique constraint on (question\_id, tag\_name) in the tags table, which will ensure that the *pair* is unique. That would mean that the same question may not have the same tag attached more than once. However, the same tag could still apply to different questions.
To prevent the use of duplicate Tags in a database
[ "", "sql", "database", "ddl", "" ]
I've seen this "-> " elsewhere used in php. One of the books I used to learn PHP has this in it, but it is never explained. What does it do, how does it work! The redirect bit I know, but what is happening with the $html variable and the redirect function? Thanks in advance!
*Note: If you have no idea what an 'Object' is, the next paragraph might not make sense. I added links at the end to learn more about 'objects' and what they are* This will access the method inside the class that has been assigned to HTML. ``` class html { function redirect($url) { // Do stuff } function foo() { echo "bar"; } } $html = new html; $html->redirect("URL"); ``` When you create a class and assign it to a variable, you use the '->' operator to access methods of that class. Methods are simply functions inside of a class. Basically, 'html' is a type of object. You can create new objects in any variable, and then later use that variable to access things inside the object. Every time you assign the HTML class to a varaible like this: ``` $html = new html; ``` You can access any function inside of it like this ``` $html->redirect(); $html->foo(); // echos "bar" ``` To learn more you are going to want to find articles about Object Oriented Programming in PHP First try the PHP Manual: <https://www.php.net/manual/en/language.oop.php> <https://www.php.net/oop> More StackOverflow Knowledge: [PHP Classes: when to use :: vs. ->?](https://stackoverflow.com/questions/1224789/php-classes-when-to-use-vs/) <https://stackoverflow.com/questions/tagged/oop> <https://stackoverflow.com/questions/249835/book-recommendation-for-learning-good-php-oop> [Why use PHP OOP over basic functions and when?](https://stackoverflow.com/questions/716412/why-use-php-oop-over-basic-functions-and-when) [What are the benefits of OO programming? Will it help me write better code?](https://stackoverflow.com/questions/135535/what-are-the-benefits-of-oo-programming-will-it-help-me-write-better-code)
In addition to what [Chacha102 said](https://stackoverflow.com/questions/1234196/what-does-this-php-constuct-mean-html-redirecturl/1234211#1234211) (which is the explanation for the particular case in the question you are asking), you really might want to takle a look at the PHP Manual, and its [Classes and Objects (PHP 5)](http://php.net/manual/en/language.oop5.php) It will teach you many useful things :-) For instance, you question most certainly has it's answer in the chapter [The Basics](http://www.php.net/manual/en/language.oop5.basic.php) ;-)
What does this php construct mean: $html->redirect("URL")?
[ "", "php", "oop", "" ]
Here's what I want to do: ``` $clsName = substr(md5(rand()),0,10); //generate a random name $cls = new $clsName(); //create a new instance function __autoload($class_name) { //define that instance dynamically } ``` Obviously this isn't what I'm actually doing, but basically I have unknown names for a class and based on the name, I want to generate the class with certain properties etc. I've tried using eval() but it is giving me fits over private and $this-> references... //edit Ok, obviously my short and sweet "here's what I want to do" caused massive strife and consternation amongst those who may be able to provide answers. In the hope of getting an actual answer I'll be more detailed. I have a validation framework using code hints on the site I maintain. Each function has two definitions ``` function DoSomething($param, $param2){ //code } function DoSomething_Validate(vInteger $param, vFloat $param2){ //return what to do if validation fails } ``` I'm looking to add a validator for primary keys in my database. I don't want to create a separate class for EVERY table (203). So my plan was to do something like ``` function DoSomething_Validate(vPrimaryKey_Products $id){ } ``` Where the \_\_autoload would generate a subclass of vPrimaryKey and set the table parameter to Products. Happy now?
This is almost certainly a bad idea. I think your time would be better spent creating a script that would create your class definitions for you, and not trying to do it at runtime. Something with a command-line signature like: ``` ./generate_classes_from_db <host> <database> [tables] [output dir] ```
As of PHP 7.0, with a little creativity and knowledge of some lesser known PHP features, you can absolutely do this without resorting to eval or creating script files dynamically. You just need to use [spl\_autoload\_register()](https://www.php.net/manual/en/function.spl-autoload-register.php) with [anonymous classes](http://php.net/manual/en/language.oop5.anonymous.php) and [class\_alias()](http://php.net/manual/en/function.class-alias.php), like such: ``` spl_autoload_register(function ($unfoundClassName) { $newClass = new class{}; //create an anonymous class $newClassName = get_class($newClass); //get the name PHP assigns the anonymous class class_alias($newClassName, $unfoundClassName); //alias the anonymous class with your class name } ``` This works because anonymous classes are still assigned a name behind the scenes and put in the global scope, so you're free to grab that class name and alias it. Check out the second comment under the anonymous classes link above for more information. Having said that, I feel like all the people in this question who are saying "Eval is always a very bad idea. Just don't use it ever!" are just repeating what they've heard from the hive mind and not thinking for themselves. Eval is in the language for a reason, and there are situations where it can be used effectively. If you're on an older version of PHP, eval might be a good solution here. ***However***, they are correct in that it *can* open up very large security holes and you have to be careful how you use it and understand how to eliminate the risks. The important thing is, much like SQL injection, you have to sanitize any input you put in the eval statement. For example, if your autoloader looked like this: ``` spl_autoload_register(function ($unfoundClassName) { eval("class $unfoundClassName {}"); } ``` A hacker could do something like this: ``` $injectionCode = "bogusClass1{} /*insert malicious code to run on the server here */ bogusClass2"; new $injectionCode(); ``` See how this has the potential to be a security hole? *Anything* the hacker puts between the two bogusClass names will be run on your server by the eval statement. If you adjust your autoloader to check the class name passed in (i.e. doing a preg\_match to make sure there's no spaces or special characters, checking it against a list of acceptable names, etc.), you can eliminate these risks and then eval might be totally fine to use in this situation. If you're on PHP 7 or higher though, I recommend the anonymous class alias method above.
Dynamically generate classes at runtime in php?
[ "", "php", "code-generation", "proxy-classes", "dynamic-compilation", "" ]
i am building a system for automatically parsing incoming emails and populating a database from them initially there will only be 10-20 expected formats coming in, but long term there is the possibility of thousands of different formats the way i see it 1. i need to identify format of email (eg regex on subject line) 2. parse the email with the correct processor 3. check the data is realistic, maybe flag some for manual check 4. populate the database what i am after is suggestions on how to structure this, eg do i store the formats in the database or flat file, the system needs to be flexible, it might be that subject line detection is not enough and i might also have to scan the email headers. the data itself could be in the email body or attachments such as pdf, excel files etc a prime example of this sort of thing is the likes of picasa photo gallery where you can email your photos to a specific email address and it automatically extracts them and puts it in a gallery for you
Probably not the most famous answer, but have you look at standard ways to do so, like procmail? Provides you with a basic understanding of emails and allows you to build filters around everything. (Processing mails through a file-type detector first, applying regexps to all possible headers,...) That way you keep every part of your system in a specialised script/program and produce a modular solution that can easily be extended. Plus you may use any tool that has already been programmed by somebody else. For the file-type filter: I am doing something comparable for broken/old pgp-mails via procmail to add a content type. ``` # repair pgp-encoded messages with missing Content-Type ###################################################################### :0 * !^Content-Type: message/ * !^Content-Type: multipart/ * !^Content-Type: application/pgp { :0 fBw * ^-----BEGIN PGP MESSAGE----- * ^-----END PGP MESSAGE----- | /usr/bin/formail \ -i "Content-Type: application/pgp; format=text; x-action=encrypt" :0 fBw * ^-----BEGIN PGP SIGNED MESSAGE----- * ^-----BEGIN PGP SIGNATURE----- * ^-----END PGP SIGNATURE----- | /usr/bin/formail \ -i "Content-Type: application/pgp; format=text; x-action=sign" } ``` Further processing then could match content types and assign special handlers to special types (and generic handlers to unknown types).
What you probably want to do is first parse through the headers and subject line, then import the correct format via the database. Because there are potentially thousands of formats, a database is going to be the easiest way because it is dynamic. No use creating thousands of files.
email parsing system
[ "", "php", "regex", "email", "parsing", "" ]
In a nutshell on "page1.php" I have a calculator that consists of an HTML form, and then the PHP code totals the input and displays the total price. Below the price, it also displays a link to "page2.php" which contains an HTML form where they can enter their contact information. Upon submitting the form the selections they made on "page1.php" in the pricing calculator as well as the contact info on "page2.php" are emailed to me, and they are redirected to the home page. In the email that is submitted to me, I receive the contact info from "page2.php", but I don't receive anything from "page1.php", so the variables are not getting correctly passed. In addition to the PHP on each page, I am using hidden values in an HTML form on "page2.php" to echo the data that was entered in the HTML form on "page1.php". I know that one of my issues is that I have a couple of `$_GET` fields when my form is "post". However when I change it so that everything is `$_POST`, the calculator no longer works. I tried to put this altogether with different snippets of code suggested by others. The form on "page1.php" has 13 fields, named "one" - "thirteen". $total display the values of 1-13. ``` <?php $submit = $_GET['submit']; if($submit == "true") { $total = ($_POST['one'] + $_POST['two'] + $_POST['three'] + $_POST['four'] + $_POST['five'] + $_POST['six'] + $_POST['seven'] + $_POST['eight']+ $_POST['nine'] + $_POST['ten']+ $_POST['eleven'] + $_POST['twelve']+ $_POST['thirteen']); echo " Your Price is \$ " .number_format ($total, 2, '.', ','). "<BR>"; echo ('">Get Your Project Started</a>'); } ?> ``` The second form uses hidden values to echo the info from page1.php, and has three more fields named "name", "email" and "details". ``` <?php $to = "jessica@designs.com"; $message = "Pages:\t$_POST[one]\n"; $message .= "Pages:\t$_POST[two]\n"; $message .= "Pages:\t$_POST[three]\n"; $message .= "Ecommerce:\t$_POST[four]\n"; $message .= "No Ecommerce:\t$_POST[five]\n"; $message .= "CMS:\t$_POST[six]\n"; $message .= "No CMS:\t$_POST[seven]\n"; $message .= "Audio or Video:\t$_POST[eight]\n"; $message .= "Flash Intro:\t$_POST[nine]\n"; $message .= "Image Gallery:\t$_POST[ten]\n"; $message .= "Graphic Design or Logo:\t$_POST[eleven]\n"; $message .= "Copy:\t$_POST[twelve]\n"; $message .= "Images:\t$_POST[thirteen]\n"; $message .= "Price Total:\t$_POST[total]\n"; $message .= "Name:\t$_POST[name]\n"; $message .= "Email:\t$_POST[email]\n"; $message .= "\n"; $message .= "\n"; $message .= "Details:\t$_POST[details]\n"; mail($to, $subject, $message, $headers) ; } ?> ``` So what would be the correct PHP to put on "page1.php" and "page2.php"? Sorry the code is such a mess, if anyone could point me in the right direction, that would be great.
PHP is stateless unless you save things in session (which isn't secure right?) You would need to make page2.php read all the values from page1.php and store them either in a server side state (session) or a client state (cookies or maybe hidden fields in the form) If you want any of this secure or a secret, then you have to consider all of that as well. Nothing I explained is secret or secure in any way. **EDIT:** here is an example of page1.php that sends the values of page1.php to page2.php as get parameters. You can do this with hidden fields, cookies or sessions as well. What is important to remember is that page2.php is totally unaware of page1.php, and can't get to the values like you could it forms programming. Each page starts and ends it's life by the time you see a full web page, so you have to use some extra tricks to keep values. Those tricks are sessions, cookies, form posts, or gets. ``` <html> <head> <title>Page 1</title> </head> <body> <?php //set defaults assuming the worst $total = 0; $one =0; $two=0; //verify we have that value in $__POST if (isset($_POST['submit'])) { $submit = $_POST['submit']; //If it is true, try some math if($submit == "sub-total") { if (isset($_POST['one'])) { $one = $_POST['one']; //Add checks to see if your values are numbers if ( ! is_numeric($one)) { $one = 0;} } if (isset($_POST['two'])) { $two = $_POST['two']; if ( ! is_numeric($two)) { $two = 0;} } $total = $one + $two; echo " Your Price is \$ " .number_format ($total, 2, '.', ','). "<BR>"; } if($submit == "submit" ) { //go to page two, with the total from page1.php passed as a $__GET value header("Location: page2.php?total=".$total); } } ?> <form method="post" action="page1.php?submit=true"> <input type="text" name="one" id="one" value="<?=$one?>"/> <input type="text" name="two" id="two" value="<?=$two?>"/> <input type="submit" name="submit" value="sub-total" /> <input type="submit" name="submit" value="submit" /> </form> </body> </html> ```
You can try using `$_REQUEST` instead of `$_GET` or `$_POST` - it works for both. Also, if you put `<input type='hidden'` in the form on page 2 with your variables posted from page 1 they should get passed right along.
How do I pass data between pages in PHP?
[ "", "php", "html", "forms", "variables", "" ]
I have a dataset objds. objds contains a table named Table1. Table1 contains column named ProcessName. This ProcessName contains repeated names.So i want to select only distinct names.Is this possible. ``` intUniqId[i] = (objds.Tables[0].Rows[i]["ProcessName"].ToString()); ```
``` DataView view = new DataView(table); DataTable distinctValues = view.ToTable(true, "Column1", "Column2" ...); ```
Following single line of code will avoid the duplicate rows of a `DataTable`: ``` dataTable.DefaultView.ToTable(true, "employeeid"); ``` Where: * first parameter in `ToTable()` is a **boolean** which indicates whether you want distinct rows or not. * second parameter in the `ToTable()` is the column name based on which we have to select distinct rows. Only these columns will be in the returned datatable. The same can be done from a `DataSet`, by accessing a specific `DataTable`: ``` dataSet.Tables["Employee"].DefaultView.ToTable(true, "employeeid"); ```
How to select distinct rows in a datatable and store into an array
[ "", "c#", "select", "datatable", "distinct", "" ]
I'm trying to process incoming JSON/Ajax requests with Django/Python. [`request.is_ajax()`](https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpRequest.is_ajax) is `True` on the request, but I have no idea where the payload is with the JSON data. `request.POST.dir` contains this: ``` ['__class__', '__cmp__', '__contains__', '__copy__', '__deepcopy__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', '__weakref__', '_assert_mutable', '_encoding', '_get_encoding', '_mutable', '_set_encoding', 'appendlist', 'clear', 'copy', 'encoding', 'fromkeys', 'get', 'getlist', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'lists', 'pop', 'popitem', 'setdefault', 'setlist', 'setlistdefault', 'update', 'urlencode', 'values'] ``` There are apparently no keys in the request post keys. When I look at the POST in [Firebug](http://en.wikipedia.org/wiki/Firebug), there is JSON data being sent up in the request.
If you are posting JSON to Django, I think you want `request.body` (`request.raw_post_data` on Django < 1.4). This will give you the raw JSON data sent via the post. From there you can process it further. Here is an example using JavaScript, [jQuery](http://en.wikipedia.org/wiki/JQuery), jquery-json and Django. JavaScript: ``` var myEvent = {id: calEvent.id, start: calEvent.start, end: calEvent.end, allDay: calEvent.allDay }; $.ajax({ url: '/event/save-json/', type: 'POST', contentType: 'application/json; charset=utf-8', data: $.toJSON(myEvent), dataType: 'text', success: function(result) { alert(result.Result); } }); ``` Django: ``` def save_events_json(request): if request.is_ajax(): if request.method == 'POST': print 'Raw Data: "%s"' % request.body return HttpResponse("OK") ``` Django < 1.4: ``` def save_events_json(request): if request.is_ajax(): if request.method == 'POST': print 'Raw Data: "%s"' % request.raw_post_data return HttpResponse("OK") ```
I had the same problem. I had been posting a complex JSON response, and I couldn't read my data using the request.POST dictionary. My JSON POST data was: ``` //JavaScript code: //Requires json2.js and jQuery. var response = {data:[{"a":1, "b":2},{"a":2, "b":2}]} json_response = JSON.stringify(response); // proper serialization method, read // http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/ $.post('url',json_response); ``` In this case you need to use method provided by aurealus. Read the request.body and deserialize it with the json stdlib. ``` #Django code: import json def save_data(request): if request.method == 'POST': json_data = json.loads(request.body) # request.raw_post_data w/ Django < 1.4 try: data = json_data['data'] except KeyError: HttpResponseServerError("Malformed data!") HttpResponse("Got json data") ```
Where's my JSON data in my incoming Django request?
[ "", "python", "ajax", "json", "django", "content-type", "" ]
I have this PHP code that I use to make a dropdown form selection of country's I would like to eliminate this extra mysql query though and just store the output like in code to on the page However I am lost on how I would have the users country SELECTED If I do not use the query to get the data Please advice ``` <select name="country" style="width:180px;" onChange="do_get_rest_popup(this.value)" o> <?PHP $sql="SELECT * FROM users_countries ORDER BY country"; $result_country = executequery($sql); while($line_country = mysql_fetch_array($result_country)){ $db_country_id = $line_country['id']; $country_name = $line_country['country']; ?> <option value="<?=$db_country_id?>"<? if($line_member['country']==$db_country_id){ echo " SELECTED";} ?>><?=$country_name?></option> <? } ?> </select> ``` Code about outputs this on page, I have strunk the quantity of countries down for this post ``` <select name="country" style="width:180px;" onChange="do_get_rest_popup(this.value)" o> <option value="217">Turkmenistan</option> <option value="218">Turks and Caicos Islands</option> <option value="219">Tuvalu</option> <option value="220">Uganda</option> <option value="221">Ukraine</option> <option value="222">United Arab Emirates</option> <option value="223">United Kingdom (Great Britain)</option> <option value="224" SELECTED>United States</option> </select> ```
How about something like this? ``` <? $countries = array( "217" => "Turkenistan", "218" => "Turks and Caicos Islands", "219" => "Tuvalu", "220" => "Uganda", "221" => "Ukraine", "222" => "United Arab Emirates", "223" => "United Kingdom (Great Britain)" "224" => "United States"); ?> <select name="country" style="width:180px;" onChange="do_get_rest_popup(this.value)" /> <?php $countryCounter = 1; $amtOfCountries = count($countries); foreach ($country as $id => $c) { if ($countryCounter == $amtOfCountries) { echo "<option value=\"$id\" SELECTED>$c</option>"; } else { echo "<option value=\"$id\">$c</option>"; $countryCounter++; } } ?> </select> ``` **EDIT: I did not test this but you should get the idea**
You could: * print an array of countries as PHP code using var\_export(), and then hardcode that somewhere. * Cache the values from the database using something like [Pear Cache\_Lite](http://pear.php.net/package/Cache_Lite) - this is very straightforward to use and it means that if you modify the values in the database, all you have to do is delete the cache file to have it regenerated. With both the above options, you then have an array which you can loop over in a similar way to what you are doing now in order to generate the html.
how to pick a country dropdown selection form item without using database?
[ "", "php", "country", "" ]
Suppose that, in C#, `myType` is a reference to some `Type`. Using `myType` only, is it possible to create a `List` of objects of `myType` ? For example, in the code below, although it is erroneous, I'd like to instantiate via `new List <myType> ( )` . ``` using System ; using System.Reflection ; using System.Collections.Generic ; class MyClass { } class MainClass { public static void Main ( string [] args ) { Type myType = typeof ( MyClass ) ; List < myType > myList = new List < myType > ( ) ; } } ```
You can do so using Reflection: ``` Type typeList = typeof(List<>); Type actualType = typeList.MakeGenericType(myType); object obj = Activator.CreateInstance(actualType); ```
[How to dynamically create generic C# object using reflection?](https://stackoverflow.com/questions/1151464/how-to-dynamically-create-generic-c-object-using-reflection)
C# : instantiate a List, given a reference to a Type
[ "", "c#", "list", "" ]
I have an array of double values "vals", I need to randomly index into this array and get a value. GenRandomNumber() returns a number between 0 and 1 but never 0 or 1. I am using Convert.ToInt32 to basically get everything to the left of my decimal place, but there must be a more efficient way of doing this? Here's my code: ``` public double GetRandomVal() { int z = Convert.ToInt32(GenRandomNumber() * (vals.Length)); return vals[z]; } ``` Thanks Update Thanks to all those who have replied, but I am constrained to use a supplied MersenneTwister random number implementation that has method rand.NextDouble() **Update 2** Thinking about this some more, all I need to do is **gen a random number between 0 and array.length-1 and then use that to randomly index into the array**. vals length is 2^20 = 1048576 so generating a random int is sufficient. I notice my MersenneTwister has a method: ``` public int Next(int maxValue) ``` If I call it like **vals[rand.Next(vals.length-1)]** that should do it right? I also see the MersenneTwister has a constructor: ``` public MersenneTwister(int[] init) ``` Not sure what this is for, can I use this to prepopulate the acceptable random numbers for which I provide an array of 0 to vals.length? FYI vals is a double array of length 1048576 partitioning the normal distribution curve. I am basically using this mechanism to create Normally distributed numbers as fast as possible, the **monte carlo simulation uses billions of Normally distributed random numbers every day** so every little bit helps.
Try using a random integer instead: ``` Random random = new Random(); int randomNumber = random.Next(0, vals.Length); return vals[randomNumber]; ```
``` return vals[rng.Next(vals.Length)]; ``` Where rng is ``` Random rng = new Random(); ```
c# Fastest way to randomly index into an array
[ "", "c#", "arrays", "random", "random-access", "" ]
I have an InfoPath form with custom submit code to update a Sharepoint list by calling the Sharepoint Lists web service. The code runs without any exceptions, and I was able to set breakpoints to make sure that the variables contain the correct values before being sent to the web service. The values never get added to the Sharepoint list, though. Here is my code: ``` [InfoPathEventHandler(MatchPath = "Submit", EventType = InfoPathEventType.OnClick)] public void Submit_OnClick(DocActionEvent e) { ListsService.Lists listService = new Risk_Form.ListsService.Lists(); listService.Credentials = System.Net.CredentialCache.DefaultCredentials; string riskID = thisXDocument.DOM.selectSingleNode("//my:myFields/my:RiskID").text; string headline = thisXDocument.DOM.selectSingleNode("//my:myFields/my:RiskHeadline").text; XmlDocument doc = new XmlDocument(); XmlElement batch = doc.CreateElement("Batch"); batch.SetAttribute("OnError", "Continue"); batch.SetAttribute("ListVersion", "1"); batch.InnerXml = "<Method ID='" + riskID + "' Cmd='New'>" + "<Field Name='RiskID'>" + riskID + "</Field>" + "<Field Name='Headline'>" + headline + "</Field>" + "</Method>"; try { // Update list using the list's GUID listService.UpdateListItems("2F6CA5F4-D78A-4716-B111-507917CF89E4", batch); } catch(Exception ex) { thisXDocument.DOM.selectSingleNode("//my:myFields/my:RiskStatement").text = ex.Message; } } ```
Ok, I finally figured this stupid bug out. There was a list on the root Sharepoint site with the same display name as the list I was trying to access on my subsite. Even though my service reference pointed to the Lists web service located on my subsite, it was still returning the wrong list. I used the internal name for my list and now it works.
Two things: 1. You might also need the default View ID in your batch when calling UpdateListItems(). 2. Instead of hardcoding the list guid, you can obtain it programatically by calling listService.GetListAndView(). Here is some code to demonstrate both items: ``` System.Xml.XmlNode ndListView = listService.GetListAndView(DISPLAYNAMEOFLIST, ""); string listGuid = ndListView.ChildNodes[0].Attributes["Name"].Value; string listView = ndListView.ChildNodes[1].Attributes["Name"].Value; batch.SetAttribute("ViewName", listView); ``` You can then just call UpdateListItems() with listGuid and batch.
Accessing the Sharepoint Lists Web Service from .NET
[ "", "c#", ".net", "web-services", "sharepoint", "infopath", "" ]
Currently we are using 4 cpu windows box with 8gb RAM with MySQL 5.x installed on same box. We are using Weblogic application server for our application. We are targeting for 200 concurrent users for our application (Obviously not for same module/screen). So what is optimal number of connections should we configured in connection pool (min and max number) (We are using weblogic AS' connection pooling mechanism) ?
There is a very simple answer to this question: **The number of connections in the connection pool should be equal the number of the exec threads configured in WebLogic**. The rationale is very simple: If the number of the connections is less than the number of threads, some of the thread maybe waiting for a connection thus making the connection pool a bottleneck. So, it should be equal at least the number the exec threads (thread pool size).
Did you really mean 200 *concurrent* users or just 200 logged in users? In most cases, a browser user is not going to be able to do more than 1 page request per second. So, 200 users translates into 200 transactions per second. That is a pretty high number for most applications. Regardless, as an example, let's go with 200 transactions per second. Say each front end (browser) tx takes 0.5 seconds to complete and of the 0.5 seconds, 0.25 are spent in the database. So, you would need 0.5 \* 200, or 100 connections in the WebLogic thead pool and 0.25 \* 200 = 50 connections in the DB connection pool. To be safe, I would set the max thread pool sizes to at least 25% larger than you expect to allow for spikes in load. The minimums can be a small fraction of the max, but the tradeoff is that it could take longer for some users because a new connection would have to be created. In this case, 50 - 100 connections is not that many for a DB so that's probably a good starting number. Note, that to figure out what your average transaction response times are, along with your average DB query time, you are going to have to do a performance test because your times at load are probably not going to be the times you see with a single user.
Optimal number of connections in connection pool
[ "", "java", "mysql", "performance", "weblogic", "connection-pooling", "" ]
I am using [Numeric Library Bindings for Boost UBlas](http://mathema.tician.de/node/391) to solve a simple linear system: ``` #include<boost/numeric/ublas/matrix.hpp> #include<boost/numeric/ublas/io.hpp> #include<boost/numeric/bindings/traits/ublas_matrix.hpp> #include<boost/numeric/bindings/lapack/gesv.hpp> #include <boost/numeric/bindings/traits/ublas_vector2.hpp> namespace ublas = boost::numeric::ublas; namespace lapack= boost::numeric::bindings::lapack; int main() { ublas::matrix<float,ublas::column_major> A(3,3); ublas::vector<float> b(3); for(unsigned i=0;i < A.size1();i++) for(unsigned j =0;j < A.size2();j++) { std::cout << "enter element "<<i << j << std::endl; std::cin >> A(i,j); } std::cout << A << std::endl; b(0) = 21; b(1) = 1; b(2) = 17; lapack::gesv(A,b); std::cout << b << std::endl; return 0; } ``` I tried compiling it with the following command: ``` g++ -I/home/foolb/.boost/include/boost-1_38 -I/home/foolb/.boostnumbind/include/boost-numeric-bindings solve_Axb_byhand.cc -o solve_Axb_byhand ``` but fail with the following error: ``` /media/disk/tmp/ccbd973l.o: In function `boost::numeric::bindings::lapack::detail::gesv(int, int, float*, int, int*, float*, int, int*)': solve_Axb_byhand2.cc:(.text._ZN5boost7numeric8bindings6lapack6detail4gesvEiiPfiPiS4_iS5_[boost::numeric::bindings::lapack::detail::gesv(int, int, float*, int, int*, float*, int, int*)]+0x59): undefined reference to `sgesv_' collect2: ld returned 1 exit status ``` What's wrong with my approach in the code?
sgesv\_ is a symbol from LAPACK library, you'll have to link to that. uBLAS just binds to it I guess. I too don't know the name of the library though :)
Sorry if this is way off track, but I can't see you linking in the boost libraries in your g++ command. I see you including the search paths, but there's no explicit inclusion of the compiled Boost libraries themselves; something like -lboost (I'm afraid I don't know the exact format you'd need, and it may well depend on locations).
Compiling C++ Code With Boost's Numeric Binding Library to Solve Ax=b Linear System
[ "", "c++", "boost", "linear-algebra", "" ]
I have some code written in VB that reads as follows: ``` Return (Not (crc32Result)) ``` I am trying to convert it to C#, and this is what I have: ``` return (!(crc32Result)); ``` However I get a compiler error: > **Compiler Error Message:** CS0023: Operator '!' cannot be applied to operand of type 'uint' Is there a different operator I need to be using instead of this one? Thanks!
It looks like what you are trying to do is reverse the bits of crc32result. If so, you want the tilde operator ~. ``` return (~crc32Result); ``` Reference [this question.](https://stackoverflow.com/questions/387424/what-is-the-tilde-in-a-c-enumeration)
In C#, the bang(!) is used to flip a boolean variable. Are you trying to treat the uInt above as a boolean, or perform some other reversal (reversal of all binary digits, perhaps)? I'd suggest one of these is the solution you're looking for: ``` return (!(bool)crc32Result); // treating as bool (0 = false, anything else is true) return (~crc32Result); //bitwise flipping for all ```
How do you return 'not uint' in C#?
[ "", "c#", "operators", "code-conversion", "" ]
I have this algorithm that are drawing a lot of pixels on a Canvas in an animation. But I have no control of the speed of the animation and it is drawing very fast, so I added a Thread.Sleep(1) but then it is too slow when drawing several thousand pixels. I have tried a Storyboard approach but that ended up to be a very slow. So are there an alternative to the Thread.sleep for slowing down my loop? ``` void DrawGasket(object sender, DoWorkEventArgs e) { Random rnd = new Random(); Color color = Colors.White; while (Counter <= noOfPx) { switch (rnd.Next(3)) { case 0: m_lastPoint.X = (m_top.X + m_lastPoint.X)/2; m_lastPoint.Y = (m_top.Y + m_lastPoint.Y)/2; color = Colors.White; break; case 1: m_lastPoint.X = (m_left.X + m_lastPoint.X)/2; m_lastPoint.Y = (m_left.Y + m_lastPoint.Y)/2; color = Colors.Orange; break; case 2: m_lastPoint.X = (m_right.X + m_lastPoint.X)/2; m_lastPoint.Y = (m_right.Y + m_lastPoint.Y)/2; color = Colors.Purple; break; } Dispatcher.BeginInvoke(() => { var px = new Rectangle { Height = m_pxSize, Width = m_pxSize, Fill = new SolidColorBrush(color) }; Canvas.SetTop(px, m_lastPoint.Y); Canvas.SetLeft(px, m_lastPoint.X); can.Children.Add(px); lblCounter.Text = Counter.ToString(); }); Counter++; Thread.Sleep(1); } } ```
Can't you just sleep every N iterations through the loop rather than every iteration?
Here's the simple method: You want it to draw at a specific time...during each loop have it look to see what time it is. If it's "time" (whatever) rate you determine that to be, then draw/update. Otherwise, just loop. (For example, if you want 10 updates per second, and you just updated, then store the current time in a variable...and then compare against that variable. Until it is a 10th of a second later, don't redraw, just loop.) This isn't bad, so long as you can do anything else you need to do within this loop. If this loop must complete, however, before anything else happens, you'll just be burning a lot of cpu cycles just waiting. If you want to get fancy, and do this right, you can have it see how much time has passed, and then update the visual by the correct amount. So, for example, if you want your object to move 30 pixels per second, you could just update where it is precisely, (if .0047 seconds have gone by, for instance, it should move .141 pixels). You store that value. Of course, visually, it won't have moved at all until another round of the loop, but exactly when it moves and how far will be determined by *time*, rather than the speed of the computer. This way you'll get it moving 30 pixels per second, regardless of the speed of the machine...it will just be jumpier on a slow machine.
Thread.Sleep(1); is too slow for a Silverlight animation, is there an alternative?
[ "", "c#", "silverlight", "" ]
Suppose you are using the ternary operator, or the null coalescing operator, or nested if-else statements to choose assignment to an object. Now suppose that within the conditional statement, you have the evaluation of an expensive or volatile operation, requiring that you put the result into a temporary variable, capturing its state, so that it can be compared, and then potentially assigned. How would a language, such as C#, for consideration, implement a new logic operator to handle this case? Should it? Are there existing ways to handle this case in C#? Other languages? Some cases of reducing the verbosity of a ternary or null coalescing operator have been overcome, when we assume that we are looking for direct comparisons, for example. See [Unique ways to use the Null Coalescing operator](https://stackoverflow.com/questions/278703/unique-ways-to-use-the-null-coalescing-operator), in particular the discussion around how one can extend the usage of the operator to support `String.IsNullOrEmpty(string)`. Note how [Jon Skeet](https://stackoverflow.com/users/22656/jon-skeet) is using the `PartialComparer` from [`MiscUtil`](http://www.yoda.arachsys.com/csharp/miscutil/), to reformat `0`s to `null`s, Why is this possibly necessary? Well, take a look at how we write a comparison method for complex objects without any shortcuts (examples from the cited discussions): ``` public static int Compare( Person p1, Person p2 ) { return ( (result = Compare( p1.Age, p2.Age )) != 0 ) ? result : ( (result = Compare( p1.Name, p2.Name )) != 0 ) ? result : Compare( p1.Salary, p2.Salary ); } ``` Jon Skeet writes a new comparison to fallback the equality case. This allows the expression to extend by writing a new specific method which returns null, allowing us to use the null coalescing operator: ``` return PartialComparer.Compare(p1.Age, p2.Age) ?? PartialComparer.Compare(p1.Name, p2.Name) ?? PartialComparer.Compare(p1.Salary, p2.Salary) ?? 0; ``` The null coalescing operator is more readable because it has two sides, not three. The boolean condition clause is separated into a method, in this case returning `null` if the expression must be continued. What would the above expression look like if we could more easily put the condition in-line? Take the expression from `PartialComparer.Compare` which returns `null`, and place it in a new ternary expression which allows us to use the evaluation of the left-side expression, with an implicit temporary variable `value`: ``` return Compare( p1.Age, p2.Age ) unless value == 0 : Compare( p1.Name, p2.Name ) unless value == 0 : Compare( p1.Salary, p2.Salary ); ``` The basic "flow" of an expression would be: > *expression* **A** unless *boolean* **B** in which case *expression* **C** Rather than being an overloaded comparison operator, I suppose this is more like a short-circuiting **inverted ternary operator**. * Would this type of logic be useful? Currently the null coalescing provides us a way to do this with the conditional expression `(value == null)`. * What other expressions would you want to test against? We've heard of `(String.IsNullOrEmpty(value))`. * What would be the best way to express this in the language, in terms of operators, keywords?
personally I'd avoid the short circuit from operators and just let the methods chain it: ``` public static int CompareChain<T>(this int previous, T a, T b) { if (previous != 0) return previous; return Comparer<T>.Default.Compare(a,b); } ``` use like so: ``` int a = 0, b = 2; string x = "foo", y = "bar"; return a.Compare(b).CompareChain(x,y); ``` can be inlined by the JIT so it can perform just as well as short circuiting built into the language without messing about with more complexity. In response to your asking whether the above 'structure' can apply to more than just comparisons then yes it can, by making the choice of whether to continue or not explict and controllable by the user. This is inherently more complex but, the operation is more flexible so this is unavoidable. ``` public static T ElseIf<T>( this T previous, Func<T,bool> isOK Func<T> candidate) { if (previous != null && isOK(previous)) return previous; return candidate(); } ``` then use like so ``` Connection bestConnection = server1.GetConnection() .ElseIf(IsOk, server2.GetConnection) .ElseIf(IsOk, server3.GetConnection) .ElseIf(IsOk, () => null); ``` This is maximum flexibility in that you can alter the *IsOk* check at any stage and are entirely lazy. For situations where the is OK check is the same in every case you can simplify like so and entirely avoid extensions methods. ``` public static T ElseIf<T>( Func<T,bool> isOK IEnumerable<Func<T>[] candidates) { foreach (var candidate in candidates) { var t = candidate(); if (isOK(t)) return t; } throw new ArgumentException("none were acceptable"); } ``` You could do this with linq but this way gives a nice error message and allows this ``` public static T ElseIf<T>( Func<T,bool> isOK params Func<T>[] candidates) { return ElseIf<T>(isOK, (IEnumerable<Func<T>>)candidates); } ``` style which leads to nice readable code like so: ``` var bestConnection = ElseIf(IsOk, server1.GetConnection, server2.GetConnection, server3.GetConnection); ``` If you want to allow a default value then: ``` public static T ElseIfOrDefault<T>( Func<T,bool> isOK IEnumerable<Func<T>>[] candidates) { foreach (var candidate in candidates) { var t = candidate(); if (isOK(t)) return t; } return default(T); } ``` Obviously all the above can very easily be written using lambdas so your specific example would be: ``` var bestConnection = ElseIfOrDefault( c => c != null && !(c.IsBusy || c.IsFull), server1.GetConnection, server2.GetConnection, server3.GetConnection); ```
You've got lots of good answers to this question already, and I am late to this particular party. However I think it is worthwhile to note that your proposal is a special case of a more generally useful operation which I dearly wish C# had, namely, the ability to in an expression context, give a name to a temporary computation. In fact C# has this operator but *only in query comprehensions*. I wish we had been able to add this as an operator in C# 3: ``` public static int Compare(Person p1, Person p2) => let ages = Compare(p1.Age, p2.Age) in ages != 0 ? ages : let names = Compare(p1.Name, p2.Name) in names != 0 ? names : Compare(p1.Salary, p2.Salary); ``` "Let expressions" are one of those expressions that are *so useful*, and found in *so few languages*, and I genuinely do not understand why language designers do not add it immediately in version one. If C# had this feature then your proposed: ``` A() unless B() : C() ``` is simply ``` let a = A() in B() ? C() : a ``` which is hardly more difficult to understand, and bonus, you get to use `a` in expressions `B()` and `C()` if you like. Let expressions can be emulated in any language that has lambdas; of course `let x = y in z` is simply `(x=>z)(y)`, but there is no concise way to write that in C# either because C# requires a conversion to a delegate type on every lambda. Incidentally, in Roslyn we do not represent temporaries as let-expressions, though we could. Rather, we go even one level below that and have a representation for "sequence of operations that might produce values, one of which will become the value of this expression". "let x = y in z" is simply the sequence "allocate x, x = y, z, deallocate x" where the third element is the value. And in the original pre-roslyn C# compiler we had internal operators "left" and "right", which were binary operators that took two expressions and produced either the left or right side, so we could generate `((allocate x) right ((x = y) right z)) left (deallocate x)`. My point here is: we often get requests for bespoke language features with unusual punctuation, but it would in general have been better to implement the *basic building blocks* that you could build these operators out of in a natural way.
How-to: short-circuiting inverted ternary operator implemented in, e.g. C#? Does it matter?
[ "", "c#", "language-design", "language-features", "" ]
I am trying to read(append incoming data into a local String) from a PrintStram in the following code block: ``` System.out.println("Starting Login Test Cases..."); out = new PrintStream(new ByteArrayOutputStream()); command_feeder = new PipedWriter(); PipedReader in = new PipedReader(command_feeder); main_controller = new Controller(in, out); for(int i = 0; i < cases.length; i++) { command_feeder.write(cases[i]); } ``` main\_controller will be writing some strings to its out(PrintStream), then how can I read from this PrintStream assuming I can't change any code in Controller class? Thanks in advance.
Simply spoken: you can't. A PrintStream is for *outputting*, to read data, you need an InputStream (or any subclass). You already have a ByteArrayOutputStream. Easiest to do is: ``` // ... ByteArrayOutputStream baos = new ByteArrayOutputStream(); out = new PrintStream(baos); // ... ByteArrayInputStream in = new ByteArrayInputStream(baos.toByteArray()); // use in to read the data ```
If you keep a reference to the underlying byte array output stream, you can call [toString(String encoding)](http://java.sun.com/j2se/1.4.2/docs/api/java/io/ByteArrayOutputStream.html#toString%28java.lang.String%29) on it, or [toByteArray()](http://java.sun.com/j2se/1.4.2/docs/api/java/io/ByteArrayOutputStream.html#toByteArray%28%29). I suspect you want the former, and you need to specify the encoding to match how the strings have been written in (you may be able to get away with using the default encoding variant)
Java: How do I read from PrintStream?
[ "", "java", "io", "" ]
Is it possible to extend a dundas chart control or any other propietary (binary distributed) control(s) where we don't have the sources using partial classes? I thought it could be done as long as the dll was referenced, but I've been struggling trying to find a way of doing this. I'm trying to **avoid** the creation of an ASP .NET Server Control which inherits from the Dundas.Charting.WebControl.Chart class.
No, to use a partial class the main declaration of that class must already use the partial keyword, usually not the case. Inheritance is possible if the class is not marked as sealed. You seem not to want that, but it could be the shortest path. The last option, but one that always works, is to embed the control in a Wrapper that extends its functionality.
Nope, this is not possible. All partials definitions must reside in the same assembly. Your way to extend may be to inherit yourself from the Chart class.
Is it possible to extend a dundas chart control using a partial class?
[ "", "c#", "asp.net", "dundas", "" ]
This will convert 1 hex character to its integer value, but needs to construct a (sub) string. ``` Convert.ToInt32(serializedString.Substring(0,1), 16); ``` Does .NET have a built-in way to convert a single hex character to its byte (or int, doesn't matter) value that doesn't involve creating a new string?
``` int value = "0123456789ABCDEF".IndexOf(char.ToUpper(sourceString[index])); ``` Or even faster (subtraction vs. array search), but no checking for bad input: ``` int HexToInt(char hexChar) { hexChar = char.ToUpper(hexChar); // may not be necessary return (int)hexChar < (int)'A' ? ((int)hexChar - (int)'0') : 10 + ((int)hexChar - (int)'A'); } ```
Correct me if im wrong but can you simply use ``` Convert.ToByte(stringValue, 16); ``` as long as the stringValue represents a hex number? Isnt that the point of the base paramter? Strings are immutable, I dont think there is a way to get the substring byte value of the char at index 0 without creating a new string
Convert a single hex character to its byte value in C#
[ "", "c#", ".net", "hex", "" ]
Does anyone know how to get programmatically the absolute path in the filesystem for an EAR deployed in JBoss, from Java code within that same EAR? I need this because I want to copy some files that are inside the EAR to another part of the filesystem, on deploy-time. Thank you everyone!
I do this way. EAR has a service MyService, where I work with EAR contents: ``` import org.jboss.system.ServiceControllerMBean; import org.jboss.system.ServiceMBeanSupport; public class MyService extends ServiceMBeanSupport { public void workWithEar() { ServiceControllerMBean serviceController = (ServiceControllerMBean) MBeanProxy.get( ServiceControllerMBean.class, ServiceControllerMBean.OBJECT_NAME, server); // server is ServiceMBeanSupport member ClassLoader cl = serviceController.getClass().getClassLoader(); String path = cl.getResource("META-INF/jboss-service.xml").getPath() InputStream file = cl.getResourceAsStream("META-INF/jboss-service.xml"); } } ```
you can do you "System.getProperty()" here is the [link](https://community.jboss.org/wiki/JBossProperties) for other the properties you can used ex: ``` String jBossPath = System.getProperty("jboss.server.base.dir") ``` result ``` "/Users/ALL_THE_PATH/JBoss_7-1/standelone" ``` After you just need to add `"/deployments/YOUR_PROJECT_EAR/..."`
How to get current EAR location programmatically with JBoss
[ "", "java", "jboss", "seam", "ear", "" ]
I'm very new with c#, and was previously attempting to ignore classes and build my small program structurally more similar to PHP. After reaching a road block, I'm trying to start over and approach the problem properly OO. I'm taking a long file, and in a loop, every time certain conditions are met, I want to make a new object. How can I have it create a new object, without having to specify a unique name? ``` Referral ObjectName = new Referral(string, string, int); ``` Secondly, once this is done, and the strings & int set their appropriate object properties, how can i unique-ify the class by one property, and then sort the class by another? I'm sorry if these are basic questions, I have spent a large, large amount of time first trying to figure it out on my own with google, and a textbook. If only C# would allow multi-dimensional arrays with different types! Thank you so much! PS. I do mean to extract a list of unique objects. All these answers, while helpful, seem to involve creating a shadow set of IEnumerables. Is there no way to do this with the class itself? Trying the first solution, provided by Earwicker, adding each object to a List from within the loop, when I try to Write a property of the element to the console, i get the ClassName+Referral. What could I be doing wrong?--solved. still needed .property still working. . .
C# does allow untyped arrays. All objects are derived ultimately from `object`, so you use an array or container of `object`s. But it's rarely necessary. How many *types* of object do you have? Within the loop block, you can create an object exactly as you do in that line of code (except with the syntax fixed), and it will be a new object each time around the loop. To keep all the objects available outside the loop, you would add it to a container: ``` List<Referral> referrals = new List<Referral>(); // in the loop: Referral r = new Referral(str1, str2, num1); referrals.Add(r); ``` Suppose `Referral` has a numeric property called `Cost`. ``` referrals.Sort((l, r) => l.Cost - r.Cost); ``` That sorts by the cost. For ensuring uniqueness by some key, you may find it easier to pick a more suitable container. ``` Dictionary<string, Referral> referrals = new List<Referral>(); // in the loop: Referral r = new Referral(str1, str2, num1); referrals[str1] = r; ``` This stores the referral in a "slot" named after the value of `str1`. Duplicates will overwrite each other silently.
First, you're going to need to spend some time familiarizing yourself with the basics of the language to be productive. I recommend you take a little time to read up on C# before getting in too deep - otherwise you'll spend a lot of your time spinning your wheels - or reinventing them :) But here's some info to get you started. Typically, in C# you create classes to represent elements of your program - including those that are used to represent information (data) that your program intends to manipulate. You should really consider using one, as it will make data manipulation clearer and more manageable. I would advise avoiding untyped, multi-dimensions array structures as some may suggest, as these rapidly become very difficult to work with. You can easily create a Referall class in C# using automatic properties and a simple constructor: ``` public class Referall { // these should be named in line with what they represent... public string FirstString { get; set; } public string AnotherString { get; set; } public int SomeValue { get; set; } public Referall( string first, string another, int value ) { FirstString = first; AnotherString = another; SomeValue = value; } } ``` You can add these to a dictionary as you create them - the dictionary can be keyed by which ever property is unique. Dictionaries allow you to store objects based on a unique key: ``` Dictionary<string,Referall> dict = new Dictionary<string,Referall>(); ``` As you process items, you can add them to the dictionary: ``` Referall ref = new Referall( v1, v2, v3 ); // add to the dictionary, keying on FirstString... dict.Add( ref.FirstString, ref ); ``` If you need to sort items in the dictionary when you're done, you can use LINQ in C# 3.0: ``` IEnumerable<Referall> sortedResults = dict.Values.OrderBy( x => x.AnotherString ); ``` You can sort by multiple dimension using ThenBy() as well: ``` IEnumerable<Referall> sortedResults = dict.Values.OrderBy( x => x.AnotherString ) .ThenBy( x => x.SomeValue ); ```
c# looping object creation
[ "", "c#", "variables", "class", "object", "sorting", "" ]
I have an object, dc, of type CDC and I'd like to get an HDC object. I read the MSDN documentation [here](http://msdn.microsoft.com/en-us/library/1yf45f1t%28VS.80%29.aspx), but don't really understand it. Can someone provide me with a brief example/explanation on how to do this?
CDC class has `operator HDC()` defined which allows the compiler to convert a CDC object to HDC implicitly. Hence if you have CDC\* and a function which takes HDC then you just dereference the pointer and send it to the function.
When you have `CDC` object it will be implicitly converted to `HDC` when necessary: ``` CDC dc; HDC hdc = dc; // HDC hdc = dc.operator HDC(); ``` If you have pointer to `CDC` object then using function `GetSafeHdc` will look more clear: ``` CDC* pdc = SOME; HDC hdc = pdc->GetSafeHdc(); ```
How can I get an HDC object from a CDC object?
[ "", "c++", "windows", "mfc", "cdc", "" ]
I am binding things to HTML objects using javascript and need a slightly more sophisticated mechanism than just class names. My first approach was to use class names like structure declarations where the binding is on name position as so: ``` Definition = identifier: foo bar baz ``` Encoding some class name with this definition gives ``` <p id="someid" class="identifier bish bash bosh"> <div id="anotherid" class="identifier heebie jeebie"> ``` This can then be read as: ``` {foo: bish, bar: bash, baz: bosh}; {foo: heebie, bar: jeebie} ``` Note that the bindings have different numbers of parameters. This is very fragile. I can't decorate any html elements with additional names (for instance to add jquery behaviours like drag and drop, etc, etc) and is generally a bit shoddy... What I would like to do is represent them as key value pairs like so: ``` <p id="someid" class="id{foo:bish} id{bar:bash} id{baz:bosh} random class"> <div id="anotherid" class="ui-draggable id{bar:jeebie} id{foo:heebie}"> ``` Which allows me to have random positioning and random length of class names on elements provided my id is a sorta GUID (but I can 'make that so' manually easily enough...) Now, [in theory](http://www.w3.org/TR/REC-html40/struct/global.html#h-7.5.2), classnames are CDATA, so everything should be tickety-boo, but *I hae ma doots!* particularly on the old cross-browser side... Advice, suggestions, prior art, best practice on the best syntax for KV pairs in class names all gratefully received.
HTML5 is going to add data-\* attributes for just this purpose, and these already work in every browser today (but might send some validators for a loop). <http://ejohn.org/blog/html-5-data-attributes/> ``` <li class="user" data-name="John Resig" data-city="Boston" data-lang="js" data-food="Bacon"> <b>John says:</b> <span>Hello, how are you?</span> </li> ```
The [allowed className characters](https://stackoverflow.com/questions/448981/what-characters-are-valid-in-css-class-names) will help you determine what to use. For me, I would lean towards something like: ``` keys: soft, hard, wet, hot values: foo, bar, baz, fuzz class="soft_bar wet_foo hot_fuzz" ``` In particular, the braces {,} won't work as they are used in the CSS stylesheets to mark blocks of style properties.
The Best Way To Represent key/value Pairs In HTML Class Names
[ "", "javascript", "html", "" ]
I have a list of orders with suboperations. How can I create a list of finished orders? Finished order must have finished all suboperations. Table "orders": ``` order_no | suboperation | finished 1 | preparing | 01/01/2009 1 | scrubbing | 01/05/2009 1 | painting | 01/10/2009 2 | preparing | 02/05/09 2 | painting | NULL 3 | preparing | 03/01/2009 3 | scrubbing | 03/15/2009 3 | painting | 03/10/2009 4 | bending | NULL 4 | crashing | NULL 4 | staining | NULL 4 | painting | NULL ``` Desired output (finished orders): ``` order_no 1 3 ```
You'll could also use **count**, **group by** and **having**. This avoids having to do any table joins which is more efficient. ``` create table #Orders ( order_no int, suboperation varchar(30), finished smalldatetime) insert into #Orders values (1 , 'preparing' , '01/01/2009') insert into #Orders values (1 , 'scrubbing' , '01/05/2009') insert into #Orders values (1 , 'painting' , '01/10/2009') insert into #Orders values (2 , 'preparing' , '02/05/09') insert into #Orders values (2 , 'painting' , NULL) insert into #Orders values (3 , 'preparing' , '03/01/2009') insert into #Orders values (3 , 'scrubbing' , '03/15/2009') insert into #Orders values (3 , 'painting' , '03/10/2009') insert into #Orders values (4 , 'bending' , NULL) insert into #Orders values (4 , 'crashing' , NULL) insert into #Orders values (4 , 'staining' , NULL) insert into #Orders values (4 , 'painting' , NULL) select order_no, count(1) As NoOfSubtasks --count(1) gives the number of rows in the group count(finished) As NoFinished, --count will not count nulls from #Stuff group by order_no having count(finished) = count(1) --if finished = number of tasks then it's complete drop table #Orders ```
A good ol' `WHERE NOT EXISTS` clause ought to work here: ``` SELECT DISTINCT o.order_no FROM orders o WHERE NOT EXISTS (SELECT p.order_no FROM orders p WHERE p.order_no = o.order_no AND p.finished IS NULL) ```
SQL Selecting finished orders with multiple operations
[ "", "sql", "ms-access", "select", "jet", "" ]
*(A case of over relying on an IDE)* I have some legacy C code that I compile as C++ for the purpose of Unit testing. The C source is C++ aware in that it conditionally *defines* based on environment. E.g. (`PRIVATE` resolves to `static`): ``` #if!defined __cplusplus #define PRIVATE1 PRIVATE #endif ``` ... ``` PRIVATE1 const int some_var; ``` The problem is I just can't seem to find out what `PRIVATE1` resolves to or is in C++, the compiler complains of redefinition if I add a declaration but doesn't indicate where? I have searched my MinGW/gcc include path, the C++ ISO specification and the C++ books available to me has been to no avail. ***Edit:*** Sure I checked the command line and makefiles before posting.
Eclipse C++ managed project's are a little, well stupid! If a project is declared C++ it still bases it's build on file extension, hence .h file preprocessed as C and not C++ header which pulls in a #define PRIVATE1 from another header file similarly wrapped by: ``` #ifdef __cpluplus. ``` The project is then linked by g++.
There's nothing like this in ISO C++ spec. Most likely, `PRIVATE1` (as well as `PRIVATE`) are defined elsewhere in the project. Note that this doesn't need to be a `#define` in an .h file - it can also be defined via compiler switches in the makefile. I'd suggest doing a full grep on the project directory.
Strange Eclipse C++ #define behaviour
[ "", "c++", "c", "eclipse", "build-error", "" ]
I'm trying to get the absolute path of certain files in a C# class. `Server.MapPath` works great of course for ASPX and their code-behind pages, but that doesn't exist in another class file. I tried `HostingEnvironment.MapPath()`, but that complains that the relative virtual path isn't allowed. Any thoughts? `System.Web` is already imported.
The `ServerUtility` class is available as an instance in your `HttpContext`. If you're in an environment where you know it'll be executed inside the ASP.Net pipeline, you can use ``` HttpContext.Current.Server.MapPath() ``` You'll have to import `System.Web` though.
you can also use: ``` var path = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/myfile.txt") ``` if ``` var path = Server.MapPath("~/App_Data"); var fullpath = Path.Combine(path , "myfile.txt"); ``` is inaccessible
Using Server.MapPath in external C# Classes in ASP.NET
[ "", "c#", "asp.net", "file", "path", "relative-path", "" ]
We are running Eclipse over QNX6 in a VMWare environment and it's very slow. Eclipse is launched like this: ``` /usr/qnx630/host/qnx6/x86/usr/qde/eclipse/eclipse -data /root//workspace /usr/qnx630/host/qnx6/x86/usr/qde/eclipse/jre/bin/pvm -pri 13 -ts 4 -gs 4 -gcperiod 500 -cs 512000 -nojit -numregs 64 -maxmem 256M -Djava.version -classpath /usr/qnx630/host/qnx6/x86/usr/qde/eclipse/startup.jar org.eclipse.core.launcher.Main -os qnx -ws photon -arch x86 -showsplash /usr/qnx630/host/qnx6/x86/usr/qde/eclipse/eclipse -showsplash 600 -exitdata /usr/qnx630/host/qnx6/x86/usr/qde/eclipse/eclipse -exitdata /tmp/eclipse_25b034 -data /root//workspace ``` Any ideas to make it faster? Like turning off some features, tuning the gc, general ideas not specific to QNX or VMWare...
I would bump up the max memory (maxmem, or Xmx) to at least 512M - we run with 512M to 1024M because Eclipse is fairly heavy weight, which is to be expected with all the plugins and features. Also, I would uninstall any end-user plugins you are not using.
The -maxmem 256M argument looks suspiciuos. Try bumping it to 512M or more.
How to improve the performance of Eclipse IDE under QNX6
[ "", "java", "performance", "eclipse", "" ]
I need to format data in a sql column that is currently entered like this: Z04000002003.7 The desired output of this would be: Z04/000/002/003.7 Every time a user enters data like this Z04000002003.7. The next time the user opens the record it would have automatically formatted it to display Z04/000/002/003.7.
If you want to insert the slashes on INSERT or UPDATE (when the string gets into the database) or SELECT, you can do that in TSQL with a somewhat clumsy string expression: ``` SUBSTRING(thestring, 1, 3) + '/' + SUBSTRING(thestring, 4, 6) + '/' + ... ``` and so on, but I agree with other respondents that it may be a better architecture to perform such transformations "closer to the user" (in the UI, or perhaps in a business logic layer if those slashes are in fact part of the business logic, but UI looks likelier).
When you say 'open the record' where exactly is that happening? A web page? Do the formatting as close to the user as you can - UI layer. I don't think this is a SQL problem.
Formatting varchar data into a certain format
[ "", "sql", "sql-server-2005", "string-formatting", "" ]
I'm looking for an equivalent of the `DataContext.GetTable<TEntity>` in Entity Framework. I've found the `ObjectContext.CreateQuery<T>` method but it is different from `DataContext.GetTable<TEntity>` since it needs a querystring to work. Is there a way to get an IQueryable object for a table using the entity type without specifying the querystring? `*EDIT: Added code snippet*` This is a snippet of a Repository class I've implemented that works with linq2sql. I can't use `ObjectContext.[TableName]` because it wouldn't be generic anymore. ``` public class BaseRepository<TClass> : IDisposable where TClass : class { protected BaseRepository(DataContext database) { _database = database; } ... public IQueryable<TClass> GetAllEntities() { IQueryable<TClass> entities = _database.GetTable<TClass>(); return entities; } public IQueryable<TClass> GetEntities(Expression<Func<TClass, bool>> condition) { IQueryable<TClass> table = _database.GetTable<TClass>(); return table.Where(condition); } ``` `*EDIT: Added my solution (so far..)*` This is what I'm using: ``` public IQueryable<TClass> GetEntities(Expression<Func<TClass, bool>> condition) { IQueryable<TClass> table = _database.CreateQuery<TClass>(typeof(TClass).Name); return table.Where(condition); } ``` This works as long as the class name is the same of the table name. This will became a problem for me when I'll start using different objects for the same table. I hope I've been clear, thanks in advance, Marco :)
Actually, the EF designer itself uses `CreateQuery` with hard-coded strings for the static references. If you dig into the designer file you'll see something like this: ``` public global::System.Data.Objects.ObjectQuery<Customers> Customers { get { if ((this._Customers == null)) { this._Customers = base.CreateQuery<Customers>("[Customers]"); } return this._Customers; } } private global::System.Data.Objects.ObjectQuery<Customers> _Customers; ``` Technically there's no perfect solution because you can use the same entity type for different entity sets. But you can give it the old college try: ``` public IQueryable<TEntity> GetEntities<TEntity>() { Type t = typeof(TEntity); var edmAttr = (EdmEntityTypeAttribute)Attribute.GetCustomAttribute(t, typeof(EdmEntityTypeAttribute), false); if (edmAttr == null) // Fall back to the naive way { return context.CreateQuery<TEntity>(t.Name); } var ec = context.MetadataWorkspace.GetEntityContainer( context.DefaultContainerName, DataSpace.CSpace); var entityType = context.MetadataWorkspace.GetType(edmAttr.Name, edmAttr.NamespaceName, DataSpace.CSpace); var es = ec.BaseEntitySets.First(es => es.ElementType == entityType); return context.CreateQuery<TEntity>(es.Name); } ```
``` public IQueryable GetTable<T>(T entity) where T : class { return context.CreateObjectSet<T>(); } ```
Does the Entity Framework have an equivalent of DataContext.GetTable<TEntity> from Linq2Sql (ObjectContext.CreateQuery<T>?)
[ "", "c#", ".net", "entity-framework", "" ]
I'm trying to whip up a skeleton View system in PHP, but I can't figure out how to get embedded views to receive their parent's variables. For example: **View Class** ``` class View { private $_vars=array(); private $_file; public function __construct($file) { $this->_file='views/'.$file.'.php'; } public function set($var, $value=null) { if (is_array($var)) { $this->_vars=array_merge($var, $this->_vars); } else $this->_vars[$var]=$value; return $this; } public function output() { if (count($this->_vars)) extract($this->_vars, EXTR_REFS); require($this->_file); exit; } public static function factory($file) { return new self($file); } } ``` **test.php (top level view)** ``` <html> <body> Hey <?=$name?>! This is <?=$adj?>! <?=View::factory('embed')->output()?> </body> </html> ``` **embed.php (embedded in test.php** ``` <html> <body> Hey <?=$name?>! This is an embedded view file!! </body> </html> ``` **Code:** ``` $vars=array( 'name' => 'ryan', 'adj' => 'cool' ); View::factory('test')->set($vars)->output(); ``` **Output:** ``` Hey ryan! This is cool! Hey [error for $name not being defined] this is an embedded view file!! ``` The problem is the variables I set in the top level view do not get passed to the embedded view. How could I make that happen?
So, I'm not exactly answering your question, but here's my super-simple hand-grown template system. It supports what you're trying to do, although the interface is different. ``` // Usage $main = new SimpleTemplate("templating/html.php"); $main->extract($someObject); $main->extract($someArray); $main->name = "my name"; $subTemplate = new SimpleTemplate("templating/another.php"); $subTemplate->parent($main); $main->placeholderForAnotherTemplate = $subTemplate->run(); echo $main; // or $main->run(); // html.php <html><body><h1>Title <?= $name ?></h1><p><?= $placeHolderForAnotherTemplate ?></p></body></html> <?php // SimpleTemplate.php function object_to_array($object) { $array = array(); foreach($object as $property => $value) { $array[$property] = $value; } return $array; } class SimpleTemplate { public $source; public $path; public $result; public $parent; public function SimpleTemplate($path=false, $source=false) { $this->source = array(); $this->extract($source); $this->path($path); } public function __toString() { return $this->run(); } public function extract($source) { if ($source) { foreach ($source as $property => $value) { $this->source[$property] = $value; } } } public function parent($parent) { $this->parent = $parent; } public function path($path) { $this->path = $path; } public function __set($name, $value) { $this->source[$name] = $value; } public function __get($name) { return isset($this->source[$name]) ? $this->source[$name] : ""; } public function mergeSource() { if (isset($this->parent)) return array_merge($this->parent->mergeSource(), $this->source); else return $this->source; } public function run() { ob_start(); extract ($this->mergeSource()); include $this->path; $this->result = ob_get_contents(); ob_end_clean(); return $this->result; } } ```
well, you create a new instance of the class, so there are no variables defined in the embedded template. you should try to copy the object, rather than creating a new one. edit: I'm talking about the factory method
Templating system scoping issue
[ "", "php", "templates", "scope", "" ]
What are the modules used to write multi-threaded applications in Python? I'm aware of the basic concurrency mechanisms provided by the language and also of [Stackless Python](http://www.stackless.com/), but what are their respective strengths and weaknesses?
In order of increasing complexity: # Use the [threading module](http://docs.python.org/library/threading.html) Pros: * It's really easy to run any function (any callable in fact) in its own thread. * Sharing data is if not easy (locks are never easy :), at least simple. Cons: * As mentioned [by Juergen](https://stackoverflow.com/questions/1190206/threading-in-python/1190428#1190428) Python threads cannot actually concurrently access state in the interpreter (there's one big lock, the infamous [Global Interpreter Lock](http://en.wikipedia.org/wiki/Global_Interpreter_Lock).) What that means in practice is that threads are useful for I/O bound tasks (networking, writing to disk, and so on), but not at all useful for doing concurrent computation. # Use the [multiprocessing](http://docs.python.org/library/multiprocessing.html) module In the simple use case this looks exactly like using `threading` except each task is run in its own process not its own thread. (Almost literally: If you take [Eli's example](https://stackoverflow.com/questions/1190206/threading-in-python/1190232#1190232), and replace `threading` with `multiprocessing`, `Thread`, with `Process`, and `Queue` (the module) with `multiprocessing.Queue`, it should run just fine.) Pros: * Actual concurrency for all tasks (no Global Interpreter Lock). * Scales to multiple processors, can even scale to multiple *machines*. Cons: * Processes are slower than threads. * Data sharing between processes is trickier than with threads. * Memory is not implicitly shared. You either have to explicitly share it or you have to pickle variables and send them back and forth. This is safer, but harder. (If it matters increasingly the Python developers seem to be pushing people in this direction.) # Use an event model, such as [Twisted](http://twistedmatrix.com/) Pros: * You get extremely fine control over priority, over what executes when. Cons: * Even with a good library, asynchronous programming is usually harder than threaded programming, hard both in terms of understanding what's supposed to happen and in terms of debugging what actually is happening. --- In **all** cases I'm assuming you already understand many of the issues involved with multitasking, specifically the tricky issue of how to share data between tasks. If for some reason you don't know when and how to use locks and conditions you have to start with those. Multitasking code is full of subtleties and gotchas, and it's really best to have a good understanding of concepts before you start.
You've already gotten a fair variety of answers, from "fake threads" all the way to external frameworks, but I've seen nobody mention `Queue.Queue` -- the "secret sauce" of CPython threading. To expand: as long as you don't need to overlap pure-Python CPU-heavy processing (in which case you need `multiprocessing` -- but it comes with its own `Queue` implementation, too, so you can with some needed cautions apply the general advice I'm giving;-), Python's built-in `threading` will do... but it will do it much better if you use it *advisedly*, e.g., as follows. "Forget" shared memory, supposedly the main plus of threading vs multiprocessing -- it doesn't work well, it doesn't scale well, never has, never will. Use shared memory only for data structures that are set up once *before* you spawn sub-threads and never changed afterwards -- for everything else, make a *single* thread responsible for that resource, and communicate with that thread via `Queue`. Devote a specialized thread to every resource you'd normally think to protect by locks: a mutable data structure or cohesive group thereof, a connection to an external process (a DB, an XMLRPC server, etc), an external file, etc, etc. Get a small thread pool going for general purpose tasks that don't have or need a dedicated resource of that kind -- *don't* spawn threads as and when needed, or the thread-switching overhead will overwhelm you. Communication between two threads is always via `Queue.Queue` -- a form of message passing, the only sane foundation for multiprocessing (besides transactional-memory, which is promising but for which I know of no production-worthy implementations except In Haskell). Each dedicated thread managing a single resource (or small cohesive set of resources) listens for requests on a specific Queue.Queue instance. Threads in a pool wait on a single shared Queue.Queue (Queue is solidly threadsafe and *won't* fail you in this). Threads that just need to queue up a request on some queue (shared or dedicated) do so without waiting for results, and move on. Threads that eventually DO need a result or confirmation for a request queue a pair (request, receivingqueue) with an instance of Queue.Queue they just made, and eventually, when the response or confirmation is indispensable in order to proceed, they get (waiting) from their receivingqueue. Be sure you're ready to get error-responses as well as real responses or confirmations (Twisted's `deferred`s are great at organizing this kind of structured response, BTW!). You can also use Queue to "park" instances of resources which can be used by any one thread but never be shared among multiple threads at one time (DB connections with some DBAPI compoents, cursors with others, etc) -- this lets you relax the dedicated-thread requirement in favor of more pooling (a pool thread that gets from the shared queue a request needing a queueable resource will get that resource from the apppropriate queue, waiting if necessary, etc etc). Twisted is actually a good way to organize this minuet (or square dance as the case may be), not just thanks to deferreds but because of its sound, solid, highly scalable base architecture: you may arrange things to use threads or subprocesses only when truly warranted, while doing most things normally considered thread-worthy in a single event-driven thread. But, I realize Twisted is not for everybody -- the "dedicate or pool resources, use Queue up the wazoo, never do anything needing a Lock or, Guido forbid, any synchronization procedure even more advanced, such as semaphore or condition" approach can still be used even if you just can't wrap your head around async event-driven methodologies, and will still deliver more reliability and performance than any other widely-applicable threading approach I've ever stumbled upon.
Threading in Python
[ "", "python", "multithreading", "python-stackless", "" ]
I have the following xml snippet: ``` <Configuration> <Config name="SendToAddresses"></Config> <Config name="CCToAddresses"></Config> <Config name="BCCAddresses"></Config> </Configuration> ``` What I would like is to deSerialize to a strongly typed class, with all items of config in an array containing value pair (name|value).
``` class Program { static void Main(string[] args) { XmlSerializer serializer = new XmlSerializer(typeof(Configuration)); var xml = @"<Configuration> <Config name=""SendToAddresses"">some value</Config> <Config name=""CCToAddresses""></Config> <Config name=""BCCAddresses""></Config> </Configuration>"; using (var reader = new StringReader(xml)) { var configuration = (Configuration)serializer.Deserialize(reader); } } } public class Configuration { [XmlElement(ElementName="Config")] public Config[] Configs { get; set; } } public class Config { [XmlAttribute(AttributeName = "name")] public string Name { get; set; } [XmlText] public string Value { get; set; } } ```
There is no point to deserialize an xml file into a strongly typed object to have an array of configuration. If you can afford to alter your xml file to: ``` <Configuration> <SendToAddresses></SendToAddresses> <CCToAddresses></CCToAddresses> <BCCAddresses></BCCAddresses> </Configuration> ``` And follow the simple steps below: 1. First, you need a container (an object) to deserialize your object into. 2. Use XSD.exe too generate the files for you (XSD schema and then CS file from XSD schema). Use XSD.exe and you will be set within 15 minutes and have a nice strongly typed Configuration object.
Serialization, attribute to strong type property
[ "", "c#", "serialization", "" ]
I'm trying to parse some JSON data from the Google AJAX Search API. I have [this URL](http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=cheese&rsz=large) and I'd like to break it down so that the results are displayed. I've currently written this code, but I'm pretty lost in regards of what to do next, although there are a number of examples out there with simplified JSON strings. Being new to C# and .NET in general I've struggled to get a genuine text output for my ASP.NET page so I've been recommended to give JSON.NET a try. Could anyone point me in the right direction to just simply writing some code that'll take in JSON from the Google AJAX Search API and print it out to the screen? --- **EDIT:** ALL FIXED! All results are working fine. Thank you again Dreas Grech! ``` using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.ServiceModel.Web; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.IO; using System.Text; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { GoogleSearchResults g1 = new GoogleSearchResults(); const string json = @"{""responseData"": {""results"":[{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://www.cheese.com/"",""url"":""http://www.cheese.com/"",""visibleUrl"":""www.cheese.com"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:bkg1gwNt8u4J:www.cheese.com"",""title"":""\u003cb\u003eCHEESE\u003c/b\u003e.COM - All about \u003cb\u003echeese\u003c/b\u003e!."",""titleNoFormatting"":""CHEESE.COM - All about cheese!."",""content"":""\u003cb\u003eCheese\u003c/b\u003e - everything you want to know about it. Search \u003cb\u003echeese\u003c/b\u003e by name, by types of milk, by textures and by countries.""},{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://en.wikipedia.org/wiki/Cheese"",""url"":""http://en.wikipedia.org/wiki/Cheese"",""visibleUrl"":""en.wikipedia.org"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:n9icdgMlCXIJ:en.wikipedia.org"",""title"":""\u003cb\u003eCheese\u003c/b\u003e - Wikipedia, the free encyclopedia"",""titleNoFormatting"":""Cheese - Wikipedia, the free encyclopedia"",""content"":""\u003cb\u003eCheese\u003c/b\u003e is a food consisting of proteins and fat from milk, usually the milk of cows, buffalo, goats, or sheep. It is produced by coagulation of the milk \u003cb\u003e...\u003c/b\u003e""},{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://www.ilovecheese.com/"",""url"":""http://www.ilovecheese.com/"",""visibleUrl"":""www.ilovecheese.com"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:GBhRR8ytMhQJ:www.ilovecheese.com"",""title"":""I Love \u003cb\u003eCheese\u003c/b\u003e!, Homepage"",""titleNoFormatting"":""I Love Cheese!, Homepage"",""content"":""The American Dairy Association\u0026#39;s official site includes recipes and information on nutrition and storage of \u003cb\u003echeese\u003c/b\u003e.""},{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://www.gnome.org/projects/cheese/"",""url"":""http://www.gnome.org/projects/cheese/"",""visibleUrl"":""www.gnome.org"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:jvfWnVcSFeQJ:www.gnome.org"",""title"":""\u003cb\u003eCheese\u003c/b\u003e"",""titleNoFormatting"":""Cheese"",""content"":""\u003cb\u003eCheese\u003c/b\u003e uses your webcam to take photos and videos, applies fancy special effects and lets you share the fun with others. It was written as part of Google\u0026#39;s \u003cb\u003e...\u003c/b\u003e""}],""cursor"":{""pages"":[{""start"":""0"",""label"":1},{""start"":""4"",""label"":2},{""start"":""8"",""label"":3},{""start"":""12"",""label"":4},{""start"":""16"",""label"":5},{""start"":""20"",""label"":6},{""start"":""24"",""label"":7},{""start"":""28"",""label"":8}],""estimatedResultCount"":""14400000"",""currentPageIndex"":0,""moreResultsUrl"":""http://www.google.com/search?oe\u003dutf8\u0026ie\u003dutf8\u0026source\u003duds\u0026start\u003d0\u0026hl\u003den-GB\u0026q\u003dcheese""}}, ""responseDetails"": null, ""responseStatus"": 200}"; g1 = JSONHelper.Deserialise<GoogleSearchResults>(json); Response.Write(g1.content); } } public class JSONHelper { public static T Deserialise<T>(string json) { T obj = Activator.CreateInstance<T>(); MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)); DataContractJsonSerializer serialiser = new DataContractJsonSerializer(obj.GetType()); ms.Close(); return obj; } } /// Deserialise from JSON [Serializable] public class GoogleSearchResults { public GoogleSearchResults() { } public GoogleSearchResults(string _unescapedUrl, string _url, string _visibleUrl, string _cacheUrl, string _title, string _titleNoFormatting, string _content) { this.unescapedUrl = _unescapedUrl; this.url = _url; this.visibleUrl = _visibleUrl; this.cacheUrl = _cacheUrl; this.title = _title; this.titleNoFormatting = _titleNoFormatting; this.content = _content; } string _unescapedUrl; string _url; string _visibleUrl; string _cacheUrl; string _title; string _titleNoFormatting; string _content; [DataMember] public string unescapedUrl { get { return _unescapedUrl; } set { _unescapedUrl = value; } } [DataMember] public string url { get { return _url; } set { _url = value; } } [DataMember] public string visibleUrl { get { return _visibleUrl; } set { _visibleUrl = value; } } [DataMember] public string cacheUrl { get { return _cacheUrl; } set { _cacheUrl = value; } } [DataMember] public string title { get { return _title; } set { _title = value; } } [DataMember] public string titleNoFormatting { get { return _titleNoFormatting; } set { _titleNoFormatting = value; } } [DataMember] public string content { get { return _content; } set { _content = value; } } } ``` The code currently compiles and runs perfectly, but isn't returning any results. Could someone help me with returning what I require, the results ready to print out to the screen? **Edit:** Json.NET works using the same JSON and classes as the example above. ``` GoogleSearchResults g1 = JsonConvert.DeserializeObject<GoogleSearchResults>(json); ``` Link: [Serializing and Deserializing JSON with Json.NET](http://james.newtonking.com/projects/json/help/index.html?topic=html/SerializingJSON.htm) ## Related [C# - parsing json formatted data into nested hashtables](https://stackoverflow.com/questions/802766/c-parsing-json-formatted-data-into-nested-hashtables) [Parse JSON array](https://stackoverflow.com/questions/854028/parse-json-array)
**[Update]** I've just realized why you weren't receiving results back... you have a missing line in your `Deserialize` method. You were forgetting to assign the results to your `obj` : ``` public static T Deserialize<T>(string json) { using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); return (T)serializer.ReadObject(ms); } } ``` Also, just for reference, here is the `Serialize` method : ``` public static string Serialize<T>(T obj) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, obj); return Encoding.Default.GetString(ms.ToArray()); } } ``` --- **Edit** If you want to use Json.NET here are the equivalent Serialize/Deserialize methods to the code above.. Deserialize: ``` JsonConvert.DeserializeObject<T>(string json); ``` Serialize: ``` JsonConvert.SerializeObject(object o); ``` This are already part of Json.NET so you can just call them on the JsonConvert class. **Link: [Serializing and Deserializing JSON with Json.NET](http://james.newtonking.com/projects/json/help/index.html?topic=html/SerializingJSON.htm)** --- Now, the reason you're getting a StackOverflow is because of your `Properties`. Take for example this one : ``` [DataMember] public string unescapedUrl { get { return unescapedUrl; } // <= this line is causing a Stack Overflow set { this.unescapedUrl = value; } } ``` Notice that in the `getter`, you are returning the actual property (ie the property's getter is calling itself over and over again), and thus you are creating an infinite recursion. --- Properties (in 2.0) should be defined like such : ``` string _unescapedUrl; // <= private field [DataMember] public string unescapedUrl { get { return _unescapedUrl; } set { _unescapedUrl = value; } } ``` You have a private field and then you return the value of that field in the getter, and set the value of that field in the setter. --- Btw, if you're using the 3.5 Framework, you can just do this and avoid the backing fields, and let the compiler take care of that : ``` public string unescapedUrl { get; set;} ```
I found this approach which [parse JSON into a dynamic object](http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx), it extends a `DynamicObject` and `JavascriptConverter` to turn the string into an object. DynamicJsonObject ``` public class DynamicJsonObject : DynamicObject { private IDictionary<string, object> Dictionary { get; set; } public DynamicJsonObject(IDictionary<string, object> dictionary) { this.Dictionary = dictionary; } public override bool TryGetMember(GetMemberBinder binder, out object result) { result = this.Dictionary[binder.Name]; if (result is IDictionary<string, object>) { result = new DynamicJsonObject(result as IDictionary<string, object>); } else if (result is ArrayList && (result as ArrayList) is IDictionary<string, object>) { result = new List<DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary<string, object>))); } else if (result is ArrayList) { result = new List<object>((result as ArrayList).ToArray()); } return this.Dictionary.ContainsKey(binder.Name); } } ``` Converter ``` public class DynamicJsonConverter : JavaScriptConverter { public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) { if (dictionary == null) throw new ArgumentNullException("dictionary"); if (type == typeof(object)) { return new DynamicJsonObject(dictionary); } return null; } public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) { throw new NotImplementedException(); } public override IEnumerable<Type> SupportedTypes { get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(object) })); } } } ``` Usage ([sample json](http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx)): ``` JavaScriptSerializer jss = new JavaScriptSerializer(); jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() }); dynamic glossaryEntry = jss.Deserialize(json, typeof(object)) as dynamic; Console.WriteLine("glossaryEntry.glossary.title: " + glossaryEntry.glossary.title); Console.WriteLine("glossaryEntry.glossary.GlossDiv.title: " + glossaryEntry.glossary.GlossDiv.title); Console.WriteLine("glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.ID: " + glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.ID); Console.WriteLine("glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.para: " + glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.para); foreach (var also in glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso) { Console.WriteLine("glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso: " + also); } ``` This method has to return true, otherwise it will throw an error. E.g. you can throw an error if a key does not exist. Returning `true` and emptying `result` will return an empty value rather than throwing an error. ``` public override bool TryGetMember(GetMemberBinder binder, out object result) { if (!this.Dictionary.ContainsKey(binder.Name)) { result = ""; } else { result = this.Dictionary[binder.Name]; } if (result is IDictionary<string, object>) { result = new DynamicJsonObject(result as IDictionary<string, object>); } else if (result is ArrayList && (result as ArrayList) is IDictionary<string, object>) { result = new List<DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary<string, object>))); } else if (result is ArrayList) { result = new List<object>((result as ArrayList).ToArray()); } return true; // this.Dictionary.ContainsKey(binder.Name); } ```
Parse JSON in C#
[ "", "c#", "asp.net", "json", "parsing", "json.net", "" ]
Can you create a delegate of an instance method without specifying the instance at creation time? In other words, can you create a "static" delegate that takes as it's first parameter the instance the method should be called on? For example, how can I construct the following delegate using reflection? ``` Func<int, string> = i=>i.ToString(); ``` I'm aware of the fact that I can use methodInfo.Invoke, but this is slower, and does not check for type-correctness until it is called. When you have the `MethodInfo` of a particular *static* method, it is possible to construct a delegate using `Delegate.CreateDelegate(delegateType, methodInfo)`, and all parameters of the static method remain free. As Jon Skeet pointed out, you can simply apply the same to make an open delegate of an instance method if the method is non-virtual on a reference type. Deciding which method to call on a virtual method is tricky, so that's no so trivial, and value-types look like they don't work at all. For value types, `CreateDelegate` exhibits really weird behavior: ``` var func37 = (Func<CultureInfo,string>)(37.ToString); var toStringMethod = typeof(int).GetMethod("ToString", BindingFlags.Instance | BindingFlags.Public, null, new Type[] {typeof(CultureInfo) }, null); var func42 = (Func<CultureInfo,string>)Delegate.CreateDelegate(typeof(Func<CultureInfo,string>), 42, toStringMethod,true); Console.WriteLine( object.ReferenceEquals(func37.Method,func42.Method)); //true Console.WriteLine(func37.Target);//37 Console.WriteLine(func42.Target);//42 Console.WriteLine(func37(CultureInfo.InvariantCulture));//37 Console.WriteLine(func42(CultureInfo.InvariantCulture));//-201040128... WTF? ``` Calling `CreateDelegate` with `null` as the target object throws a binding exception if the instance method belonged to a value type (this works for reference types). *Some follow-up years later:* The incorrectly-bound target that caused `func42(CultureInfo.InvariantCulture);` to return `"-201040128"` instead of `"42"` in my example was memory corruption that could have allowed remote code execution ([cve-2010-1898](http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2010-1898)); this was fixed in 2010 in the [ms10-060](https://learn.microsoft.com/en-us/security-updates/securitybulletins/2010/ms10-060) security update. Current frameworks correctly print 42! That doesn't make answering this question any easier, but explains the particularly weird behavior in the example.
You've actually chosen a particularly tricky example, for two reasons: * ToString() is a virtual method inherited from `object` but overridden in `Int32`. * `int` is a value type, and there are weird rules with `Delegate.CreateDelegate()` when it comes to value types and instance methods - basically the first effective parameter becomes `ref int` rather than `int` However, here's an example for `String.ToUpper`, which doesn't have either of those problems: ``` using System; using System.Reflection; class Test { static void Main() { MethodInfo method = typeof(string).GetMethod ("ToUpper", BindingFlags.Instance | BindingFlags.Public, null, new Type[]{}, null); Func<string, string> func = (Func<string, string>) Delegate.CreateDelegate(typeof(Func<string, string>), null, method); string x = func("hello"); Console.WriteLine(x); } } ``` If that's good enough for you, great... if you really want `int.ToString`, I'll have to try a bit harder :) Here's an example for a value type, using a new delegate type which takes its first parameter by reference: ``` using System; using System.Reflection; public struct Foo { readonly string value; public Foo(string value) { this.value = value; } public string DemoMethod() { return value; } } class Test { delegate TResult RefFunc<TArg, TResult>(ref TArg arg); static void Main() { MethodInfo method = typeof(Foo).GetMethod ("DemoMethod", BindingFlags.Instance | BindingFlags.Public, null, new Type[]{}, null); RefFunc<Foo, string> func = (RefFunc<Foo, string>) Delegate.CreateDelegate(typeof(RefFunc<Foo, string>), null, method); Foo y = new Foo("hello"); string x = func(ref y); Console.WriteLine(x); } } ```
I'm not sure, but may be [Open delegates](http://tips.x-tensive.com/2008/10/open-delegates_8670.html) can help you. Upd: Follow this [link](http://www.google.com/search?q=.NET+tips+tricks+Open+delegates), if first one don't works.
"Uncurrying" an instance method in .NET
[ "", "c#", ".net", "functional-programming", "delegates", "currying", "" ]
I'm using Java's [DecimalFormat](https://stackoverflow.com/questions/168802/where-can-i-find-a-tutorial-to-get-started-learning-jquery) class to print out numbers in Scientific Notation. However, there is one problem that I have. I need the strings to be of fixed length regardless of the value, and the sign on the power of ten is throwing it off. Currently, this is what my format looks like: ``` DecimalFormat format = new DecimalFormat("0.0E0"); ``` This gives me the following combinations: 1.0E1, 1.0E-1, -1.0E1, and -1.0E-1. I can use *setPositivePrefix* to get: +1.0E1, +1.0E-1, -1.0E1, and -1.0E-1, or whatever I like, but it doesn't affect the sign of the power! Is there any way to do this so that I can have fixed length strings? Thanks! Edit: Ah, so there's no way to do it using Java's existing *DecimalFormat* API? Thanks for the suggestions! I think I may have to subclass *DecimalFormat* because I am limited by the interface that is already in place.
Here's one way. Hokey, perhaps, but it works... ``` public class DecimalFormatTest extends TestCase { private static class MyFormat extends NumberFormat { private final DecimalFormat decimal; public MyFormat(String pattern) { decimal = new DecimalFormat(pattern); } public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) { StringBuffer sb = new StringBuffer(); sb.append(modified(Math.abs(number) > 1.0, decimal.format(number, toAppendTo, pos).toString())); return sb; } private String modified(boolean large, String s) { return large ? s.replace("E", "E+") : s; } public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) { StringBuffer sb = new StringBuffer(); sb.append(modified(true, decimal.format(number, toAppendTo, pos).toString())); return sb; } public Number parse(String source, ParsePosition parsePosition) { return decimal.parse(source, parsePosition); } public void setPositivePrefix(String newValue) { decimal.setPositivePrefix(newValue); } } private MyFormat format; protected void setUp() throws Exception { format = new MyFormat("0.0E0"); format.setPositivePrefix("+"); } public void testPositiveLargeNumber() throws Exception { assertEquals("+1.0E+2", format.format(100.0)); } public void testPositiveSmallNumber() throws Exception { assertEquals("+1.0E-2", format.format(0.01)); } public void testNegativeLargeNumber() throws Exception { assertEquals("-1.0E+2", format.format(-100.0)); } public void testNegativeSmallNumber() throws Exception { assertEquals("-1.0E-2", format.format(-0.01)); } } ``` Alternatively you could *subclass* DecimalFormat, but I find it generally cleaner not to subclass from concrete classes.
This worked form me, ``` DecimalFormatSymbols SYMBOLS = DecimalFormatSymbols.getInstance(Locale.US); if (value > 1 || value < -1) { SYMBOLS.setExponentSeparator("e+"); } else { SYMBOLS.setExponentSeparator("e"); } DecimalFormat format = new DecimalFormat(sb.toString(), SYMBOLS); ```
Java DecimalFormat Scientific Notation Question
[ "", "java", "formatting", "decimal", "scientific-notation", "" ]
Given a simple inheritance hierarchy: Person -> Student, Teacher, Staff Say I have a list of Persons, L. In that list are some Students, Teachers, and Staff. Using LINQ and C#, is there a way I could write a method that could retrieve only a particular type of person? I know I can do something like: ``` var peopleIWant = L.OfType< Teacher >(); ``` But I want to be able to do something more dynamic. I would like to write a method that will retrieve results for any type of Person I could think of, without having to write a method for every possible type.
you can do this: ``` IList<Person> persons = new List<Person>(); public IList<T> GetPersons<T>() where T : Person { return persons.OfType<T>().ToList(); } IList<Student> students = GetPersons<Student>(); IList<Teacher> teacher = GetPersons<Teacher>(); ``` EDIT: added the where constraint.
This should do the trick. ``` var students = persons.Where(p => p.GetType() == typeof(Student)); ```
LINQ: From a list of type T, retrieve only objects of a certain subclass S
[ "", "c#", "linq", "typeof", "oftype", "" ]
I dynamically load a css stylesheet (with a little help from jQuery) like this: ``` var head = document.getElementsByTagName('head')[0]; $(document.createElement('link')) .attr({ type: 'text/css', href: '../../mz/mz.css', rel: 'stylesheet' }) .appendTo(head); ``` This works fine in Firefox and Google Chrome, but *not* in IE. Any help? Thanks
Once IE has processed all the styles loaded with the page, the only reliable way to add another stylesheet is with `document.createStyleSheet(url)` See the [MSDN article](http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx) on createStyleSheet for a few more details. ``` url = 'style.css'; if (document.createStyleSheet) { document.createStyleSheet(url); } else { $('<link rel="stylesheet" type="text/css" href="' + url + '" />').appendTo('head'); } ```
You need to set the href attr last and only after the link elem is appended to the head: ``` $('<link>') .appendTo('head') .attr({type : 'text/css', rel : 'stylesheet'}) .attr('href', '/css/your_css_file.css'); ``` **Update** Nowadays the only purpose of IE and Edge is to download Chrome, so I recommend NOT bloating your code with custom support for IE or Edge and rather just ignoring their existence.
Dynamically loading css stylesheet doesn't work on IE
[ "", "javascript", "jquery", "html", "css", "internet-explorer", "" ]
This isn't really an issue, however I am curious. When I save a string in lets say an DataRow, it is cast to Object. When I want to use it, I have to cast it ToString. As far as I know there are several ways of doing this, first is ``` string name = (string)DataRowObject["name"]; //valid since I know it's a string ``` and another one is: ``` string name = DataRowObject["name"].ToString(); ``` I am interested in what is the difference between both? Is the first more efficient? (This is just a speculation, in my head ToString() method is implemented by some looping mechanism where just casting it "could" be faster, however this is just a "gut feeling" I have). Is there even a faster / more elegant way of doing this? Can anyone clear this up for me?
> The two are intended for different > purposes. The ToString method of any > object is supposed to return a string > representation of that object. Casting > is quite different, and the 'as' key > word performs a conditional cast, as > has been said. The 'as' key word > basically says "get me a reference of > this type to that object if that > object is this type" while ToString > says "get me a string representation > of that object". The result may be the > same in some cases but the two should > never be considered interchangeable > because, as I said, they exist for > different purposes. If your intention > is to cast then you should always use > a cast, NOT ToString. from <http://www.codeguru.com/forum/showthread.php?t=443873> see also <http://bytes.com/groups/net-c/225365-tostring-string-cast>
If you know it is a `String` then by all means cast it to a `String`. Casting your object is going to be faster than calling a virtual method. **Edit:** Here are the results of some benchmarking: ``` ============ Casting vs. virtual method ============ cast 29.884 1.00 tos 33.734 1.13 ``` I used Jon Skeet's [`BenchmarkHelper`](https://www.nuget.org/packages/BenchmarkDotNet/) like this: ``` using System; using BenchmarkHelper; class Program { static void Main() { Object input = "Foo"; String output = "Foo"; var results = TestSuite.Create("Casting vs. virtual method", input, output) .Add(cast) .Add(tos) .RunTests() .ScaleByBest(ScalingMode.VaryDuration); results.Display(ResultColumns.NameAndDuration | ResultColumns.Score, results.FindBest()); } static String cast(Object o) { return (String)o; } static String tos(Object o) { return o.ToString(); } } ``` So it appears that casting is in fact *slightly* faster than calling `ToString()`.
Casting vs Converting an object toString, when object really is a string
[ "", "c#", "string", "casting", "parsing", "" ]
I used LaTeX for writing couple of white papers while I was in grad school. From that I have a really good impression about it in terms of what LaTeX allows user to do, especially the fine control it provides over formatting, etc. Now I am debating whether I should actually use LaTeX for our production apps to generate PDFs. I have tried several commercial and free PDF libraries (PDFSharp/MigraDoc, iTextSharp, Expert PDF, etc) and none of them provide the amount of fine control I need without making the code base extremely difficult to maintain in long run. If I do decide to go this route it will be done from C#. Since LaTeX already has command line interface, I should be able to do that pretty easily from C# as an external process forked from my program. But I was looking for some comments from the community. 1. Has anyone tried it? If so, what were some gotchas? 2. What do you think about the idea -- pros and cons (I am more interested in gotachas)? All feedback is welcome.
I have previously built a platform for report generation that uses plain TeX (specifically the [MiKTeX implementation](http://miktex.org/)) to generate reports in PDF format. The platform is used to generate approximately fifty reports per month of varying nature (containing mostly dynamically generated tables and charts). The system is quite flexible. Reports are defined via XML (on an internally-defined report description schema). The platform allows the user to specify a source database table, which fields to extract, the formatting of the fields, a mini query language to filter the appropriate data as well as various formatting elements (page orientation, size, titles, and classifications ("Public", "Internal", "Confidential", etc.). The main "gotcha" is that it takes a ton of work to end up with a code base that is flexible to change and not a total pain to maintain. A second "gotcha" is that knowledge of TeX (outside of academics) is rare so you could end up becoming the de facto maintainer even if that is not part of your usual role. Pros: 1. Beautifully formatted reports. 2. Complete control over layout and look. 3. Free. Cons: 1. Difficult to implement properly. 2. Difficult to maintain. 3. Knowledge transition could be burdensome. 4. Support is effectively non-existant.
I've done a few in-house "production level" documents in LaTeX. Generating LaTeX documents in Windows is an overall horrible experience, to be honest. I was never able to find any solution besides Cygwin. Once you've got the Cygwin environment up and running, it was as simple as picking out the LaTeX and related libraries from Cygwin's `setup.exe`. I haven't tried running LaTeX from a non-Cygwin environment, but in theory you should be able to just run `C:\Cygwin\usr\bin\latex.exe` -- then there's a chance it will be missing paths since you're not in Bash, in which case you might need to just pass the include directories to subsequent programs. If you decide to use Docbook instead of LaTeX for your documentation (and I would recommend at least giving it a look, it's *much* more structured for software-related technical documentaion), I had good experience running [dblatex](http://dblatex.sourceforge.net/) under Cygwin. It's not in the Cygwin repositories, but it's a piece of cake to install from source.
LaTeX for PDF generation in production
[ "", "c#", ".net", "latex", "" ]
I need a way of changing the mouse-cursor on a html-page. I know this can be done with css, but I need to be able to change it at runtime, like for instance having buttons on the page, and when they're clicked they change the cursor to a specific custom graphic. I think the best (or only?) way of doing this is through javascript? I hope there's a way of doing this nicely that will work on all of the major browsers. I would be very grateful if someone could help me with this. Thanks in advance
Thanks for the replies. I finally got it working. Here's how I did it: ``` <html> <head> <script type="text/javascript"> function changeToCursor1(){ document.body.style.cursor="url('cursor1.ani'),url('cursor1.cur'), default"; } function changeToCursor2(){ document.body.style.cursor="url('cursor2.ani'),url('cursor2.cur'), default"; } </script> </head> <body> <form> <input type="button" value="Change to cursor 1" onclick="changeToCursor1()" /><br> <input type="button" value="Change to cursor 2" onclick="changeToCursor2()" /> </form> </body> ``` I found out that to get it to work in Firefox you *must* pass at least 2 choices of cursors, e.g. cursor="url('cursor1.cur'), default" Or else it wont work. Also, in Firefox it doesn't work with ani-cursors, only cur. Which is why I've put a cur after ani. The ani will show up in IE, the cur in Firefox. Does anyone know if it's possible to change the cursor in IE without the active-X warning showing up and the user having to accept?
<http://www.javascriptkit.com/dhtmltutors/csscursors.shtml> Theres an example at the bottom.
Changing mouse-cursor on a html-page
[ "", "javascript", "css", "mouse-cursor", "" ]