Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am trying to make a form move (using the titlebar) from a button click. I thought this would be simple using SendMessage: ``` Const WM_LBUTTONDOWN As Integer = &H201 Button1.Capture = False Cursor.Position = Me.Location + New Size(50, 8) SendMessage(Me.Handle, WM_LBUTTONDOWN, CType(1, IntPtr), IntPtr.Zero) ``` However, although this sends the message if the cursor is in the forms client area, it does not seem to send it to the forms titlebar (the form captures the event somehow, despite the cursor being on the titlebar not in the client area). I have tried the above code in both mousedown and click events on the button, moving the cursor and then pressing on the button1. Any suggestions?
You would need `WM_`**`NC`**`LBUTTONDOWN` (and pass `HTCAPTION` as `wParam`). I'm still not entirely sure this would accomplish what you're trying to do, though. Typically, the way to allow the user to move your form when clicking somewhere other than the title bar is to process the `WM_NCHITTEST` message and return `HTCAPTION` when the cursor is over the area from which you'd like to initiate moving. However, if this area is occupied by a child control, you also have to process `WM_NCHITTEST` from the child control and return `HTTRANSPARENT`. --- Incidentally, an easier—if slightly less correct—way to accomplish this is to do as Mehrdad Afshari [suggested](https://stackoverflow.com/questions/433518/progmatically-start-moving-a-form#433522), and just set the form's `Location` property. You commented to him that "it needs to move on the mouse move", and that's exactly what you can and should do. ``` class MyForm : Form{ Point downAt; MyForm(){ Label lbl = new Label(); lbl.AutoSize = true; lbl.BackColor = Color.Blue; lbl.ForeColor = Color.White; lbl.Location = new Point(50, 50); lbl.Text = "Drag me to move this form."; lbl.Parent = this; lbl.MouseDown += (s, e)=>downAt = e.Location; lbl.MouseMove += (s, e)=>{if(lbl.Capture) Location += (Size)e.Location - (Size)downAt;}; } } ``` The problem with this approach is that it bypasses Windows' code for moving a top-level window. This means that if the user has not selected the "Show window contents while dragging" option in the Display Properties dialog, this will effectively ignore that setting (it won't show a drag outline). There may be other drawbacks that I haven't thought of as well. On the whole, though, this is a simple, easy way to accomplish this that is a fully .NET solution which doesn't rely on any platform invoke (so it should be portable to Mono on Unix). --- Oops. I just realized that I gave you C# example code, but your code seems to be VB.NET. I guess what you would need would be: ``` Sub New() Dim lbl As New Label lbl.AutoSize = True lbl.BackColor = Color.Blue lbl.ForeColor = Color.White lbl.Location = New Point(50, 50) lbl.Text = "Drag me to move this form." lbl.Parent = Me AddHandler lbl.MouseDown, Function(ByVal s As Object, ByVal e As MouseEventArgs) Me.downAt = e.Location End Function AddHandler lbl.MouseMove, Function(ByVal s As Object, ByVal e As MouseEventArgs) If lbl.Capture Then Me.Location = Me.Location + DirectCast(e.Location, Size) - DirectCast(Me.downAt, Size) End If End Function End Sub ``` This may not be the most succinct way to express this in VB.NET. I used [Reflector](http://www.red-gate.com/products/reflector/) to help me translate it.
The `LParam` value for the `wm_LButtonDown` message receives the mouse position in *client* coordinates. The title bar is in the non-client area, so use the [`wm_NCLButtonDown` message](http://msdn.microsoft.com/en-us/library/ms645620.aspx). I've seen that message given as an answer to this question before, but there's a more direct route that I would have expected to work: Send a [`wm_SysCommand` message](http://msdn.microsoft.com/en-us/library/ms646360.aspx) to the window, and specify `sc_Move` flag.
Programmatically start moving a form
[ "", "c#", "vb.net", "winforms", "sendmessage", "" ]
I am trying to create a winForms user control. But I want would like a User control that - when placed on the form -- doesn't take any form space. Instead, it lodges itself nicely below like OpenFileDialog does. First, what kind of user-created thing is this? Is it still called a "user control"? If not, that may explain why all of my searches are in vain. Secondly, what object do I need to start with to create something like this? A gentle shove in the right direction would be VERY appreciated. Thanks. --Jerry
Controls that appear in the "component tray", like the Windows Forms Timer control, inherit from Component. To create one with some automatic boilerplate code, right-click on a project and click Add... | Component
I believe you're talking about creating a [Component](http://msdn.microsoft.com/en-us/library/system.componentmodel.component.aspx).
How to create a specific type of user control
[ "", "c#", "winforms", "user-controls", "controls", "components", "" ]
Problem 1: I have a simple winforms app and I want to DataBind my Person.Name property to a textbox. Name is of type StringField. I originally defined the Name property as String. The data binding works great on value types such as String. I would like the StringField.Value property to be the default property of StringField. I want to see the value of StringField.Value in the textBox rather than the text "FieldApp.StringField". Problem 2: I would like to be able to assign a string to a StringField using operator =. This assignment would result in the StringField.Value member being set. Can this be accomplished? ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace FieldApp { public class StringField { public string Value { get; set; } } public class Person { //private String _Name; //public String Name //{ // get { return _Name; } // set { _Name = value; } //} //public Person(string name) //{ // Name = name; //} private StringField _Name; public StringField Name { get { return _Name; } set { _Name = value; } } public Person(string name) { Name = new StringField(); Name.Value = name; } } public partial class FieldAppForm : Form { Person person = new Person("steve"); public FieldAppForm() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //our form contains a button1 and textBox1 //this compiles person.Name.Value = "steve"; //this does not. Is there anyway to accomplish this? person.Name = "steve"; //steve appears in the textbox textBox1.DataBindings.Add("Text", person, "Name.Value"); //FieldApp.StringField appears in the textbox textBox1.DataBindings.Add("Text", person, "Name"); } } } ```
You could create an implicit operator overload. Then you can create `StringField` from strings like this: ``` StringField field = "value of new object"; string value=(string)field; ``` Know that this creates a new `StringField` object. I wouldn't necessarily advice you to do this. ``` [System.Diagnostics.DebuggerDisplay("{Value}")] public class StringField { public string Value { get; set; } public static implicit operator StringField(string s) { return new StringField { Value = s }; } public static explicit operator string(StringField f) { return f.Value; } public override string ToString() { return Value; } } ```
Re data-binding, for *some* binding targets (`PropertyGrid`, `DataGridView`, etc), you can do this with a `TypeConverter` (see below). Unfortunately, this doesn't seem to work with `TextBox`, so I think your best option is to simply add a shim property (as already suggested): ``` string NameString { get { return Name.Value; } set { Name.Value = value; } // or new blah... } ``` (and bind to `NameString`) In the past, I have used custom `PropertyDescriptor` implementations to side-step this, but it isn't worth it *just* for this. Anyway, a `TypeConverter` example (works with `PropertyGrid` and `DataGridView`): ``` [TypeConverter(typeof(StringFieldConverter))] public class StringField { public StringField() : this("") { } public StringField(string value) { Value = value; } public string Value { get; private set; } } class StringFieldConverter : TypeConverter { public override bool CanConvertFrom( ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); } public override object ConvertFrom( ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { string s = value as string; if (s != null) return new StringField(s); return base.ConvertFrom(context, culture, value); } public override bool CanConvertTo( ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof(string) || base.CanConvertTo(context, destinationType); } public override object ConvertTo( ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string) && value != null && value is StringField) { return ((StringField)value).Value; } return base.ConvertTo(context, culture, value, destinationType); } } ```
C# Assigning default property for class and operator =
[ "", "c#", "properties", "default", "" ]
Basic premise: I have a Room which publishes an event when an Avatar "enters" to all Avatars within the Room. When an Avatar leaves the Room I want it to remove all subscriptions for that room. How can I best unsubscribe the Avatar from all events in the room before I add the Avatar to a new Room and subscribe to the new Room's events? The code goes something like this: ``` class Room { public event EventHandler<EnterRoomEventArgs> AvatarEntersRoom; public event EvnetHandler<LeaveRoomEventArgs> AvatarLeavesRoom; public event EventHandler<AnotherOfManyEventArgs> AnotherOfManayAvatarEvents; public void AddPlayer(Avatar theAvatar) { AvatarEntersRoom(this, new EnterRoomEventArgs()); AvatarEntersRoom += new EventHandler<EnterRoomEventArgs>(theAvatar.HandleAvatarEntersRoom); AvatarLeavesRoom += new EventHandler<EnterRoomEventArgs>(theAvatar.HandleAvatarEntersRoom); AnotherOfManayAvatarEvents += new EventHandler<EnterRoomEventArgs>(theAvatar.HandleAvatarEntersRoom); } } class Avatar { public void HandleAvatarEntersRoom(object sender, EnterRoomEventArgs e) { Log.Write("avatar has entered the room"); } public void HandleAvatarLeaveRoom(object sender, LeaveRoomEventArgs e) { Log.Write("avatar has left room"); } public void HandleAnotherOfManayAvatarEvents(object sender, AnotherOfManyEventArgs e) { Log.Write("another avatar event has occurred"); } } ```
Each delegate has a method named `GetInvocationList()` that returns all the actual delegates that have been registered. So, assuming the delegate Type (or event) is named say `MyDelegate`, and the handler instance variable is named `myDlgHandler`, you can write: ``` Delegate[] clientList = myDlgHandler.GetInvocationList(); foreach (var d in clientList) myDlgHandler -= (d as MyDelegate); ``` to cover the case where it might be null, ``` if(myDlgHandler != null) foreach (var d in myDlgHandler.GetInvocationList()) myDlgHandler -= (d as MyDelegate); ```
Probably the simplest way to accomplish this would be to store all of your subscribed events for an avatar in an `ArrayList` of delegates to the events. When the avatar leaves the room, simply loop through the list of delegates performing a standard remove (`-=`).
How do I unsubscribe all handlers from an event for a particular class in C#?
[ "", "c#", ".net", "events", "" ]
I used to code in C language in the past and I found the `scanf` function very useful. Unfortunately, there is no equivalent in C#. I am using using it to parse semi-structured text files. I found an interresting example of `scanf` implementation [here](http://www.codeproject.com/KB/recipes/csscanf.aspx). Unfortunately, it looks old and incomplete. Does anyone know a `scanf` C# implementation ? Or at least something that would work as a reversed `string.Format`?
If regular expressions aren't working for you, I've just posted a `sscanf()` replacement for .NET. The code can be viewed and downloaded at <http://www.blackbeltcoder.com/Articles/strings/a-sscanf-replacement-for-net>.
Since the files are "semi-structured" can't you use a combination of ReadLine() and TryParse() methods, or the Regex class to parse your data?
Looking for C# equivalent of scanf
[ "", "c#", "scanf", "" ]
I've got a problem with inheritance and generics. This is the code that illustrates my problem: ``` namespace TestApplication { public class MyClass<T> { private T field; public MyClass(T field) { this.field = field; } } public class MyIntClass : MyClass<int> { public MyIntClass(int field) : base(field) { } } } ``` And when I try to do something like this: ``` MyClass<int> sth = new MyClass<int>(10); MyIntClass intsth = (MyIntClass) sth; ``` I receive cast exception: Invalid cast exception. Unable to cast 'TestApplication.MyClass`1[System.Int32]' to 'TestApplication.MyIntClass'. What is more I cannot create cast operator: ``` public static implicit operator MyIntClass(MyClass<int> myClass) ``` because: 'TestApplication.MyIntClass.implicit operator TestApplication.MyIntClass(TestApplication.MyClass)': user-defined conversions to or from a base class are not allowed I need to create casts as described above. I don't know why I cannot cast from a type that is the base class. How can I solve this problem? Thanks in advance. **Edit** Thanks for Your answers. Now I see that i cannot convert from a base class to derived class and i see that it doesn't have anything to do with generics. But why i cannot create user-defined conversions from a base class? I have a method that returns the base class. I am able to define a conversion method but creating a cast operator imho would be a better solution.
You can only cast from a base class to a derived class if the object is actually of type derived class. I mean, you can't cast an instance of base (`MyClass<int>`) to `MyIntClass`. You can, however cast it if it was actually of type `MyIntClass` stored as an `MyClass<int>` instance. ``` MyClass<int> foo = new MyIntClass(); MyIntClass bar = (MyIntClass)foo; // this works. ``` Assume: ``` class Base { int x; } class Derived : Base { int y; } Base foo = new Base(); Derived bar = (Derived)foo; ``` if it was allowed, what would the value of `bar.y` be? In fact, converting from `Derived` to `Base` is not a conversion at all. It's just telling the compiler to let the variable of type `Base` to point to an object of type `Derived`. It is possible since derived has more or equal features than `Base` which is not the case in the other way around. If you were able to create a conversion operator between base and derived classes, the C# compiler would be unable to distinguish it from the built in relationships defined for them. This is why you cannot create cast operators along inheritance hierarchies.
The other answers so far are correct, but I'd like to point out that your example has *nothing* to do with generics. It's the equivalent of: ``` using System; class Base {} class Child : Base {} class Test { static void Main() { Base b = new Base(); // This will throw an exception Child c = (Child) b; } } ```
C# - Problem with generics and inheritance
[ "", "c#", "generics", "inheritance", "casting", "" ]
I'm looking for something similar to the [Proxy pattern](http://en.wikipedia.org/wiki/Proxy_pattern) or the [Dynamic Proxy Classes](http://java.sun.com/j2se/1.3/docs/guide/reflection/proxy.html), only that I don't want to intercept method calls before they are invoked on the real object, but rather I'd like to intercept properties that are being changed. I'd like the proxy to be able to represent multiple objects with different sets of properties. Something like [the Proxy class in Action Script 3](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/utils/Proxy.html) would be fine. Here's what I want to achieve in general: I have a thread running with an object that manages a list of values (numbers, strings, objects) which were handed over by other threads in the program, so the class can take care of creating regular persistent snapshots on disk for the purpose of checkpointing the application. This persistor object manages a "dirty" flag that signifies whether the list of values has changed since the last checkpoint and needs to lock the list while it's busy writing it to disk. The persistor and the other components identify a particular item via a common name, so that when recovering from a crash, the other components can first check if the persistor has their latest copy saved and continue working where they left off. During normal operation, in order to work with the objects they handed over to the persistor, I want them to receive a reference to a proxy object that looks as if it were the original one, but whenever they change some value on it, the persistor notices and acts accordingly, for example by marking the item or the list as dirty before actually setting the real value. --- **Edit**: Alternatively, are there generic setters (like in PHP 5) in Java, that is, a method that gets called if a property doesn't exist? Or is there a type of object that I can add properties to at runtime?
If with "properties" you mean JavaBean properties, i.e. represented bay a getter and/or a setter method, then you can use a dynamic proxy to intercept the set method. If you mean instance variables, then no can do - not on the Java level. Perhaps something could be done by [manipulations on the byte code level](http://java-source.net/open-source/bytecode-libraries) though. Actually, the easiest way to do it is probably by using [AspectJ](http://www.eclipse.org/aspectj/) and defining a set() pointcut (which will intercept the field access on the byte code level).
The design pattern you are looking for is: Differential Execution. I do believe. [How does differential execution work?](https://stackoverflow.com/questions/371898/how-does-differential-execution-work#381861) Is a question I answered that deals with this. However, may I suggest that you use a callback instead? You will have to read about this, but the general idea is that you can implement interfaces (often called listeners) that active upon "something interesting" happening. Such as having a data structure be changed. Obligitory links: [Wiki Differential execution](http://en.wikipedia.org/wiki/Differential_execution) [Wiki Callback](http://en.wikipedia.org/wiki/Callback_(computer_science)) Alright, here is the answer as I see it. Differential Execution is O(N) time. This is really reasonable, but if that doesn't work for ya Callbacks will. Callbacks basically work by passing a method by parameter to your class that is changing the array. This method will take the value changed and the location of the item, pass it back by parameter to the "storage class" and change the value approipriately. So, yes, you have to back each change with a method call. I realize now this is not what you want. What it appears that you want is a way that you can supply some kind of listener on each variable in an array that would be called when that item is changed. The listener would then change the corresponding array in your "backup" to refect this change. Natively I can't think of a way to do this. You can, of course, create your own listeners and events, using an interface. This is basically the same idea as the callbacks, though nicer to look at. Then there is reflection... Java has reflection, and I am positive you can write something using it to do this. However, reflection is notoriously slow. Not to mention a pain to code (in my opinion). Hope that helps...
In Java, how can I construct a "proxy wrapper" around an object which invokes a method upon changing a property?
[ "", "java", "design-patterns", "proxy-classes", "" ]
I am storing objects in a buffer. Now I know that I cannot make assumptions about the memory layout of the object. If I know the overall size of the object, is it acceptible to create a pointer to this memory and call functions on it? e.g. say I have the following class: ``` [int,int,int,int,char,padding*3bytes,unsigned short int*] ``` 1) if I know this class to be of size 24 and I know the address of where it starts in memory whilst it is not safe to assume the memory layout is it acceptible to cast this to a pointer and call functions on this object which access these members? (Does c++ know by some magic the correct position of a member?) 2) If this is not safe/ok, is there any other way other than using a constructor which takes all of the arguments and pulling each argument out of the buffer one at a time? Edit: Changed title to make it more appropriate to what I am asking.
You can create a constructor that takes all the members and assigns them, then use placement new. ``` class Foo { int a;int b;int c;int d;char e;unsigned short int*f; public: Foo(int A,int B,int C,int D,char E,unsigned short int*F) : a(A), b(B), c(C), d(D), e(E), f(F) {} }; ... char *buf = new char[sizeof(Foo)]; //pre-allocated buffer Foo *f = new (buf) Foo(a,b,c,d,e,f); ``` This has the advantage that even the v-table will be generated correctly. Note, however, if you are using this for serialization, the unsigned short int pointer is not going to point at anything useful when you deserialize it, unless you are very careful to use some sort of method to convert pointers into offsets and then back again. Individual methods on a `this` pointer are statically linked and are simply a direct call to the function with `this` being the first parameter before the explicit parameters. Member variables are referenced using an offset from the `this` pointer. If an object is laid out like this: ``` 0: vtable 4: a 8: b 12: c etc... ``` `a` will be accessed by dereferencing `this + 4 bytes`.
Non-virtual function calls are linked directly just like a C function. The object (this) pointer is passed as the first argument. No knowledge of the object layout is required to call the function.
Managing C++ objects in a buffer, considering the alignment and memory layout assumptions
[ "", "c++", "runtime", "compiler-construction", "" ]
I don't mean "Basic SQL", but strongly the specs and the difference between the specs and the implementations between great databases (like SQL Server, Oracle, etc).
[![](https://i.stack.imgur.com/yYGdf.jpg)](https://i.stack.imgur.com/yYGdf.jpg) (source: [amazon.com](http://images-eu.amazon.com/images/P/0596004818.01.jpg)) --- [SQL In a Nutshell](https://shop.oreilly.com/product/9780596518851.do) by O'Reilly and Associates. It covers all 5 major SQL Dialects, the differences between them, and does that for each function/feature listed. (ANSI SQL99, Oracle, MySql, Postgres, and SQL Server).
The number one way of learning the differences is to work in the various databases. SQL Server, Oracle, and MySql all offer free (express) editions. Also, if you want to step up a bit you can get the developer version of SQL Server for about $50. Oracle: <http://www.oracle.com/technology/products/database/xe/index.html> SQL Server <http://www.microsoft.com/express/sql/default.aspx> MySQL <http://dev.mysql.com/downloads/> Simple things to do: * create a database * create a table * do simple insert/update/delete (CRUD) operations * do inner / outer joins.
What the best resource to learn ANSI SQL?
[ "", "sql", "sql-server", "specifications", "ansi-sql", "" ]
I'm just beginning to use Regex so bear with my terminology. I have a regex pattern that is working properly on a string. The string could be in the format "text [pattern] text". Therefore, I also have a regex pattern that negates the first pattern. If I print out the results from each of the matches everything is shown correctly. The problem I'm having is I want to add text into the string and it changes the index of matches in a regex MatchCollection. For example, if I wanted to enclose the found match in "td" match "/td"" tags I have the following code: ``` Regex r = new Regex(negRegexPattern, RegexOptions.IgnoreCase | RegexOptions.Singleline); MatchCollection mc = r.Matches(text); if (mc.Count > 0) { for (int i = 0; i < mc.Count; i++) { text = text.Remove(mc[i].Index, mc[i].Length); text = text.Insert(mc[i].Index, "<td>" + mc[i].Value + "</td>"); } } ``` This works great for the first match. But as you'd expect the mc[i].Index is no longer valid because the string has changed. Therefore, I tried to search for just a single match in the for loop for the amount of matches I would expect (mc.Count), but then I keep finding the first match. So hopefully without introducing more regex to make sure it's not the first match and with keeping everything in one string, does anybody have any input on how I could accomplish this? Thanks for your input. Edit: Thank you all for your responses, I appreciate all of them.
It can be as simple as:- ``` string newString = Regex.Replace("abc", "b", "<td>${0}</td>"); ``` Results in `a<td>b</td>c`. In your case:- ``` Regex r = new Regex(negRegexPattern, RegexOptions.IgnoreCase | RegexOptions.Singleline); text = r.Replace(text, "<td>${0}</td>"); ``` Will replace all occurance of negRegexPattern with the content of that match surrounded by the td element.
Although I agree that the Regex.Replace answer above is the best choice, just to answer the question you asked, how about replacing from the last match to the first. This way your string grows beyond the "previous" match so the earlier matches indexes will still be valid. ``` for (int i = mc.Count - 1; i > 0; --i) ```
Using Regex to edit a string in C#
[ "", "c#", ".net", "regex", "" ]
Please pardon my C#.Net newbie status. If this is obvious and I missed it from the docs, a link to the relevant page or sample code would be appreciated. I am working on an application that will accept a TCP socket connection from a Java application. (Yes, Java is required on that part. It's a Sun SPOT device and Java is the only option.) The Java app will be periodically writing new data to the socket, and my app's job is to take in the byte[], convert it to a string, process the data (update UI, etc), and possibly forward the data on to another computer running a similar C#.NET app. Here's what I've done so far: Right now the app spins up a thread on launch that opens a socket. The Java app can successfully connect to the socket so that is working. I was looking at the NetworkStream's `beginRead` method and the `dataAvailable`, `length`, and `CanRead` properties, but I am not entirely sure how to ascertain when I've read one packet of data, usually about 512 bytes but could vary. If the Java app writes data to the stream or there is a backlog of data (The Java app will be passing data rather quickly.) how can I make sure that I am reading only one packet of data at a time? If the Java app null terminates the data when it writes, will that help? Is it enough? Lastly, the socket will only receive one connection, but I need to keep it open until there is an error or the connection is terminated. What is the most graceful way to handle this aspect? I don't think close and reopen with each data packet will work because of the rapid fire (nearly realtime) aspect of the Java app that is running on the Sun SPOT base station. Right now, when the base station terminates, my app dies a loud and painful death. :) Thanks for reading and for any help you can offer.
The way we've solved this is to have a combination of sentinel characters and fixed width fields. The first two bytes are a length header for the entire packet. Then, I read the packet into a byte[] buffer and then rely on our own packet structure to know that, for instance, the first two bytes are each to be interpreted as individual fields and then string fields are terminated with the \n character (0x0A if you're scoring at home). Then, long data fields are processed by reading in 8 consecutive bytes, etc. It seems to be working pretty well for us, but it's obviously a solution for a situation where one has control over both ends of the socket and not where one is only able to control the one end. Hope this helps someone else, too.
"If the Java app writes data to the stream or there is a backlog of data (The Java app will be passing data rather quickly.) how can I make sure that I am reading only one packet of data at a time?" Be careful not to assume that you have any control over what data ends up in which packet. If you try to send the byte data `{ 'H', 'e', 'l', 'l', 'o' }` there is no guarantee that all this data will be sent in a single packet. While it's extremely unlikely it is still possible that each packet could only contain a single byte so you'd receive all five bytes in 5 different events. The point being, do not rely on the packets in this manner. Instead, define your own End Of Message terminators and simply toss all incoming data into a byte buffer of some kind and have another function coming in detecting if there are any of these terminators present. If so read up to that terminator. So say for example you call the respective send method from your Java application twice containing the following data: ``` { 'H', 'e', 'l', 'l', 'o', '\0' } { 'W', 'o', 'r', 'l', 'd', '\0' } ``` How your application should be prepared to receive the data should be something like this: ``` Server receives { 'H', 'e', 'l' } Data stored in byte buffer { 'H', 'e', 'l' } Check byte buffer for message terminator '\0'. None found. Buffer unchanged, no message processed. Server receives { 'l', 'o', '\0', 'W' } Data stored in byte buffer { 'H', 'e', 'l', 'l', 'o', '\0', 'W' } Check byte buffer for message terminator '\0'. 1 found, extracted message { 'H', 'e', 'l', 'l', 'o' } and buffer updated { 'W' } ``` So while that wasn't exactly an answer to your original question I think it should give you a push in the right direction. One thing you may run into is that there simply aren't any characters that couldn't be data instead of message terminators. For instance, many files contain the data \0 so these would wreck your message detection. How this is usually handled is by creating a header spec for your protocol and detecting whether you're expecting a header (In which case looking for \0 will denote the end of a message) or if you're waiting for a certain amount of data (Which could be specified by the last header received.) If this doesn't make sense and you think you might need to use this technique let me know and I'll add to this answer.
What's the best way to monitor a socket for new data and then process that data?
[ "", "c#", "multithreading", ".net-3.5", "sockets", "sunspot", "" ]
As a sort of follow up to the question called [Differences between MSIL and Java bytecode?](https://stackoverflow.com/questions/95163/differences-between-msil-and-java-bytecode), what is the (major) differences or similarity in how the Java Virtual Machine works versus how the ~~.NET Framework~~ Common Language Runtime (CLR) works? Also, is the ~~.NET framework~~ CLR a "virtual machine" or does it not have the attributes of a virtual machine?
There are a lot of similarities between both implementations (and in my opinion: yes, they're both "virtual machines"). For one thing, they're both stack-based VM's, with no notion of "registers" like we're used to seeing in a modern CPU like the x86 or PowerPC. The evaluation of all expressions ((1 + 1) / 2) is performed by pushing operands onto the "stack" and then popping those operands off the stack whenever an instruction (add, divide, etc) needs to consume those operands. Each instruction pushes its results back onto the stack. It's a convenient way to implement a virtual machine, because pretty much every CPU in the world has a stack, but the number of registers is often different (and some registers are special-purpose, and each instruction expects its operands in different registers, etc). So, if you're going to model an abstract machine, a purely stack-based model is a pretty good way to go. Of course, real machines don't operate that way. So the JIT compiler is responsible for performing "enregistration" of bytecode operations, essentially scheduling the actual CPU registers to contain operands and results whenever possible. So, I think that's one of the biggest commonalities between the CLR and the JVM. As for differences... One interesting difference between the two implementations is that the CLR includes instructions for creating generic types, and then for applying parametric specializations to those types. So, at runtime, the CLR considers a List<int> to be a completely different type from a List<String>. Under the covers, it uses the same MSIL for all reference-type specializations (so a List<String> uses the same implementation as a List<Object>, with different type-casts at the API boundaries), but each value-type uses its own unique implementation (List<int> generates completely different code from List<double>). In Java, generic types are a purely a compiler trick. The JVM has no notion of which classes have type-arguments, and it's unable to perform parametric specializations at runtime. From a practical perspective, that means you can't overload Java methods on generic types. You can't have two different methods, with the same name, differing only on whether they accept a List<String> or a List<Date>. Of course, since the CLR knows about parametric types, it has no problem handling methods overloaded on generic type specializations. On a day-to-day basis, that's the difference that I notice most between the CLR and the JVM. Other important differences include: * The CLR has closures (implemented as C# delegates). The JVM does support closures only since Java 8. * The CLR has coroutines (implemented with the C# 'yield' keyword). The JVM does not. * The CLR allows user code to define new value types (structs), whereas the JVM provides a fixed collection of value types (byte, short, int, long, float, double, char, boolean) and only allows users to define new reference-types (classes). * The CLR provides support for declaring and manipulating pointers. This is especially interesting because both the JVM and the CLR employ strict generational compacting garbage collector implementations as their memory-management strategy. Under ordinary circumstances, a strict compacting GC has a really hard time with pointers, because when you move a value from one memory location to another, all of the pointers (and pointers to pointers) become invalid. But the CLR provides a "pinning" mechanism so that developers can declare a block of code within which the CLR is not allowed to move certain pointers. It's very convenient. * The largest unit of code in the JVM is either a 'package' as evidenced by the 'protected' keyword or arguably a JAR (i.e. Java ARchive) as evidenced by being able to specifiy a jar in the classpath and have it treated like a folder of code. In the CLR, classes are aggregated into 'assemblies', and the CLR provides logic for reasoning about and manipulating assemblies (which are loaded into "AppDomains", providing sub-application-level sandboxes for memory allocation and code execution). * The CLR bytecode format (composed of MSIL instructions and metadata) has fewer instruction types than the JVM. In the JVM, every unique operation (add two int values, add two float values, etc) has its own unique instruction. In the CLR, all of the MSIL instructions are polymorphic (add two values) and the JIT compiler is responsible for determining the types of the operands and creating appropriate machine code. I don't know which is the preferably strategy, though. Both have trade-offs. The HotSpot JIT compiler, for the JVM, can use a simpler code-generation mechanism (it doesn't need to determine operand types, because they're already encoded in the instruction), but that means it needs a more complex bytecode format, with more instruction types. I've been using Java (and admiring the JVM) for about ten years now. But, in my opinion, the CLR is now the superior implementation, in almost every way.
Your first question is comparing the JVM with the .NET Framework - I assume you actually meant to compare with the CLR instead. If so, I think you could write a small book on this (**EDIT:** looks like Benji already has :-) One important difference is that the CLR is designed to be a language-neutral architecture, unlike the JVM. Another important difference is that the CLR was specifically designed to allow for a high level of interoperability with native code. This means that the CLR must manage reliability and security when native memory is accessed and modified, and also [manage marshalling](http://msdn.microsoft.com/en-us/magazine/cc163910.aspx) between CLR-based data structures and native data structures. To answer your second question, the term “virtual machine” is an older term from the hardware world (e.g. IBM’s virtualisation of the 360 in the 1960s) that used to mean a software/hardware emulation of the underlying machine to accomplish the same sort of stuff that VMWare does. The CLR is often referred to as an "execution engine". In this context, that's an implementation of an IL Machine on top of an x86. This is also what the JVM does, although you can argue that there's an important difference between the CLR's polymorphic bytecodes and the JVM's typed bytecodes. So the pedantic answer to your second question is "no". But it really comes down to to how you define these two terms. **EDIT:** One more difference between the JVM and the CLR is that the JVM (version 6) is [very reluctant](https://stackoverflow.com/questions/366658/java-6-excessive-memory-usage/#366776) to release allocated memory back to the operating system, even where it can. For example, let's say that a JVM process starts and allocates 25 MB of memory from the operating system initially. The app code then attempts allocations that require an additional 50 MB. The JVM will allocate an additional 50 MB from the operating system. Once the application code has stopped using that memory, it is garbage-collected and the JVM heap size will decrease. However, the JVM will only free the allocated operating system memory under certain [very specific circumstances](https://stackoverflow.com/questions/366658/java-6-excessive-memory-usage#367933). Otherwise, for the rest of the process lifetime that memory will remain allocated. The CLR, on the other hand, releases allocated memory back to the operating system if it's no longer needed. In the example above, the CLR would have released the memory once the heap had decreased.
Java's Virtual Machine and CLR
[ "", "java", ".net", "bytecode", "cil", "vm-implementation", "" ]
I have a table, with 2 important columns DocEntry, WebId Sample data is like ``` DocEntry WebId 1 S001 2 S002 3 S003 4 S005 ``` Now as we can notice here, in column WebId, S004 is missing. How can we locate such missing numbers, with a query. Further explanation: The web id should be in increasing order like, S001, S002, S003, S004, S005 if any number in between is missing, than that is the missing number. I do not have any separate table for the possible entries, as that is not practical. I've to find the missing numbers on a month to month basis, taking the starting and ending value of each month as the boundaries and than finding the missing numbers, if any.
A very simple approach :) ``` mysql> select * from test; +----------+-------+ | DocEntry | WebId | +----------+-------+ | 1 | S001 | | 2 | S002 | | 3 | S003 | | 4 | S005 | | 5 | S006 | | 6 | S007 | | 7 | S008 | | 8 | S010 | +----------+-------+ 8 rows in set (0,00 sec) mysql> SELECT right(t1.webid,3) +1 as missing_WebId FROM test t1 left join test t2 on right(t1.webid,3)+1 = right(t2.webid,3) where t2.webid is null; +---------------+ | missing_WebId | +---------------+ | 4 | | 9 | | 11 | +---------------+ 3 rows in set (0,01 sec) ``` good luck, Maurice
There's a standard trick for generating integers that requires you to create a 10 row utility table viz: ``` create table Pivot (i int) insert into Pivot values (0) insert into Pivot values (1) insert into Pivot values (2) /* ... down to */ insert into Pivot values (9) ``` Once you've done this, then, for example ``` select u.i + 10*t.i + 100*h.i from Pivot u, Pivot t, Pivot h ``` will get you all the numbers 0 to 999. Add a where clause to restrict you between a range, and some string functions will get you to the PossibleEntries table in Robs answer above.
Find missing values
[ "", "sql", "" ]
Do Pagemethods and Json have security risks?(I dont use cookies).Forexample i have a pagemethod and i am sending user id as a parameter but i dont want to show it to user.Can user get user id from pagemethod?
yes they can (see the user id). Any communication between the server and client can be seen by the user. Take a look with fiddler or firebug to see what goes on. You can treat it the same as any regular get or post request. I know of no reason why not to use it. Without knowing any of the background I can't give a definitive answer on whether I would choose it but in general there is no reason not to use it just apply the same security you would use for HTTP get and post requests like in regular form submissions.
It has the same security risks as a regulat GET and POST, it is just another format to send the data back and forth. If you were using a regular POST, anyone would be able to see the userid just the same. So if you don't want to have people messing up with the userid you could add some sort of encrypted string dependent on the userid to go along with it, for validation, to name one of many possible solutions.
JSON Security
[ "", "asp.net", "javascript", "security", "json", "" ]
I'm writing (in C#) a simple parser to process a scripting language that looks a lot like classic C. On one script file I have, the regular expression that I'm using to recognize /\* block comments \*/ is going into some kind of infinite loop, taking 100% CPU for ages. The Regex I'm using is this: ``` /\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/ ``` Any suggestions on why this might get locked up? Alternatively, what's another Regex I could use instead? More information: * Working in C# 3.0 targeting .NET 3.5; * I'm using the Regex.Match(string,int) method to start matching at a particular index of the string; * I've left the program running for over an hour, but the match isn't completed; * Options passed to the Regex constructor are `RegexOptions.Multiline` and `RegexOptions.IgnorePatternWhitespace`; * The regex works correctly for 452 of my 453 test files.
Some problems I see with your regex: There's no need for the `|[\r\n]` sequences in your regex; a negated character class like `[^*]` matches everything except `*`, including line separators. It's only the `.` (dot) metacharacter that doesn't match those. Once you're inside the comment, the only character you have to look for is an asterisk; as long as you don't see one of those, you can gobble up as many characters you want. That means it makes no sense to use `[^*]` when you can use `[^*]+` instead. In fact, you might as well put that in an atomic group -- `(?>[^*]+)` -- because you'll never have any reason to give up any of those not-asterisks once you've matched them. Filtering out extraneous junk, the final alternative inside your outermost parens is `\*+[^*/]`, which means "one or more asterisks, followed by a character that isn't an asterisk or a slash". That will always match the asterisk at the end of the comment, and it will always have to give it up again because the next character is a slash. In fact, if there are twenty asterisks leading up to the final slash, that part of your regex will match them all, then it will give them all up, one by one. Then the final part -- `\*+/` -- will match them for keeps. For maximum performance, I would use this regex: ``` /\*(?>(?:(?>[^*]+)|\*(?!/))*)\*/ ``` This will match a well-formed comment very quickly, but more importantly, if it starts to match something that *isn't* a valid comment, it will fail as quickly as possible. --- Courtesy of [David](https://stackoverflow.com/questions/462843/improving-fixing-a-regex-for-c-style-block-comments/463339?noredirect=1#comment55996077_463339), here's a version that matches nested comments with any level of nesting: ``` (?s)/\*(?>/\*(?<LEVEL>)|\*/(?<-LEVEL>)|(?!/\*|\*/).)+(?(LEVEL)(?!))\*/ ``` It uses .NET's Balancing Groups, so it won't work in any other flavor. For the sake of completeness, here's another version (from RegexBuddy's Library) that uses the Recursive Groups syntax supported by Perl, PCRE and Oniguruma/Onigmo: ``` /\*(?>[^*/]+|\*[^/]|/[^*])*(?>(?R)(?>[^*/]+|\*[^/]|/[^*])*)*\*/ ```
No no no! Hasn't anyone else read Mastering Regular Expressions (3rd Edition)!? In this, Jeffrey Friedl examines this exact problem and uses it as an example (pages 272-276) to illustrate his "unrolling-the-loop" technique. His solution for most regex engines is like so: `/\*[^*]*\*+(?:[^*/][^*]*\*+)*/` However, if the regex engine is optimized to handle lazy quantifiers (like Perl's is), then the most efficient expression is much simpler (as suggested above): `/\*.*?\*/` (With the equivalent 's' "dot matches all" modifier applied of course.) Note that I don't use .NET so I can't say which version is faster for that engine.
Improving/Fixing a Regex for C style block comments
[ "", "c#", "c", "regex", "parsing", "comments", "" ]
I have an extension method on the HttpApplicationState object for getting my IoC container out of the application. This same code will also create the container if it doesn't exist. I have 2 questions: 1. Is my code actually thread safe as I intend it to be 2. Is this considered the best practice for dealing with the application state Code as follows: ``` private const string GlobalContainerKey = "UnityContainerKey"; public static IUnityContainer GetContainer(this HttpApplicationState application) { var container = application[GlobalContainerKey] as IUnityContainer; if (container == null) { try { application.Lock(); container = application[GlobalContainerKey] as IUnityContainer; if (container == null) { container = new UnityContainer(); application[GlobalContainerKey] = container; } } finally { application.UnLock(); } } return container; } ```
You need to put ``` var container = application[GlobalContainerKey] as IUnityContainer; ``` in the lock as well, otherwise many threads may create a new container in sequence. ``` private const string GlobalContainerKey = "UnityContainerKey"; private const object lockObject = new object(); public static IUnityContainer GetContainer(this HttpApplicationState application) { var IUnityContainer container = null; lock (lockObject) { container = application[GlobalContainerKey] as IUnityContainer; if (container == null) { container = new UnityContainer(); application[GlobalContainerKey] = container; } } return container; } ```
Technically, that won't work given the EMCA specification. Jon Skeet goes into this in his C# FAQ: <http://www.yoda.arachsys.com/csharp/singleton.html> Specifically, see the section with the "Third version" I would read further down and use his suggestion for how to implement the singleton to see how to implement what you are trying to do.
ASP.NET Threading - Double checked locking
[ "", "c#", "asp.net", "multithreading", "" ]
There are essentially 2 places to define JavaScript functions in Grails, directly in a element on the GSP, and within a separate javascript source file under /web-app/js (for example, application.js). We have defined a commonly reused javascript function within application.js, but we also need to be able to generate parts of the function dynamically using groovy code. Unfortunately, ${some groovy code} does not appear to be processed within separate javascript source files. Is the only way to do this by defining the javascript function within a script tag on a GSP page, or is there a more general solution? Obviously we could define the javascript function in a script tag within a template GSP file which would be reused, but there is a lot of push to keep our javascript functions defined all together in one place (i.e. the external javascript source file). This has performance benefits as well (the javascript source files are usually just downloaded once by each client's browser, instead of reloading the same javascript functions within the source of every html page they visit). I have toyed around with the idea of breaking the function up into static and dynamic pieces, putting the static ones in the external source and putting the dynamic ones in the template GSP, then gluing them together, but this seems like an unnecessary hack. Any ideas? (edit: It may sound like the idea of dynamically generating parts of a JavaScript function, which is then downloaded once and used over and over again by the client, would be a bad idea. However, the piece which is "dynamic" only changes perhaps once a week or month, and then only very slightly. Mostly we just want this piece generated off the database, even if only once, instead of hard coded.)
An easy solution to keep your JavaScript unobtrusive is to create a JavaScriptController and map its actions "/js/\*" by adding this to your `UrlMappings.groovy` file: ``` "/js/$action"{ controller = "javascript" } ``` then just create an action for each dynamic JS file you want, include in in your layout <HEAD>, and presto, you've got a JS file that you can insert Grails snippets into! :) **Note:** I've found that there's currently a bug in Grails that doesn't map file extensions to content-types properly, so you'll need to include `<%@ page contentType="text/javascript; UTF-8" %>` at the top of your view files.
This is a great solution. I would like to offer a suggestion to use somthing other then a mapping of ``` "/js/$action" ``` because this is no longer going to allow you to access you javascript files in /web-app/js/. All your javascript files would have to be moved to a the directory your controller would point to. I would use something like ``` "/dynjs/$action" ``` This way you still can point to files in the /web-app/js/ files with out conflict and enjoy the benifits of gsp tags in javascript files Please correct me if I'm wrong.
Executing groovy statements in JavaScript sources in Grails
[ "", "javascript", "grails", "groovy", "" ]
I'm not considering this - I'm comfortable with C# and VB, but an expert in neither. But, some on my team have expressed an intention to do this since we're moving toward C# as a standard.
Hell's no. Just an absolute waste of time. I would use VB over C# (or C# over VB) only if the language enabled functionality that was not available in the other. For example, making late bound calls to COM interop objects is much easier in VB than it is in C# (although that is going to change in C# 4.0). That being said, I'd stick with the language that your team is using, or what you prefer (if that is an option).
Sounds like a recipe for disaster or at least countless WTF-moments with no actual gains. .net Assemblies are compatible regardless of language (it's all IL at the end anyway), so there is no gain from that.
Would you develop in VB and then convert your code to C# just to have your entire team use one language?
[ "", "c#", "vb.net", "preferences", "" ]
I'm using SQL Server 2005. The query would look like this ``` Select col1, col2, col3 from <subquery> where (col1,col2) in <subquery> ``` SQL Server doesn't seem to like that. Any way of implementing that that anyone knows of that doesn't involve converting to varchars or anything else messy? This is the actual query. ``` SELECT * FROM ( SELECT NEWID() AS guid, UserID, RoleId, ClubId, 0 AS GroupRole FROM dbo.Portal_UserRoles UNION SELECT NEWID() AS guid, dbo.Portal_UserGroups.UserId, dbo.Portal_GroupRoles.RoleId, dbo.Portal_UserGroups.ClubId, dbo.Portal_GroupRoles.GroupId AS GroupRole FROM dbo.Portal_GroupRoles INNER JOIN dbo.Portal_UserGroups ON dbo.Portal_GroupRoles.GroupId = dbo.Portal_UserGroups.GroupId ) AS derivedtbl_1 WHERE (derivedtbl_1.RoleId,derivedtbl_1.ClubId) IN ( SELECT Portal_GroupRoles.RoleId, Portal_ClubGroups.ClubId FROM Portal_GroupRoles INNER JOIN Portal_ClubGroups ON Portal_GroupRoles.GroupId = Portal_ClubGroups.GroupId ) ```
You have to separate in two clauses ``` where col1 in (...) AND col2 in (...) ``` or you could refactor it a little bit ``` select * FROM ( SELECT NEWID() AS guid, UserID, RoleId, ClubId, 0 AS GroupRole FROM dbo.Portal_UserRoles UNION SELECT NEWID() AS guid, dbo.Portal_UserGroups.UserId, dbo.Portal_GroupRoles.RoleId, dbo.Portal_UserGroups.ClubId, dbo.Portal_GroupRoles.GroupId AS GroupRoles FROM dbo.Portal_GroupRoles INNER JOIN dbo.Portal_UserGroups ON dbo.Portal_GroupRoles.GroupId = dbo.Portal_UserGroups.GroupId) AS derivedtbl_1, Portal_GroupRoles, Portal_ClubGroup where derivedtbl_1.RoleId = Portal_GroupRoles.RoleId and derivedtbl_1.ClubId = Portal_ClubGroups.ClubId and Portal_GroupRoles.GroupId = Portal_ClubGroups.GroupId ```
The standard, classic way to do what you seek is an EXISTS clause: ``` SELECT * FROM ( SELECT NEWID() AS guid, UserID, RoleId, ClubId, 0 AS GroupRole FROM dbo.Portal_UserRoles UNION SELECT NEWID() AS guid, dbo.Portal_UserGroups.UserId, dbo.Portal_GroupRoles.RoleId, dbo.Portal_UserGroups.ClubId, dbo.Portal_GroupRoles.GroupId AS GroupRole FROM dbo.Portal_GroupRoles INNER JOIN dbo.Portal_UserGroups ON dbo.Portal_GroupRoles.GroupId = dbo.Portal_UserGroups.GroupId ) AS derivedtbl_1 WHERE EXISTS ( SELECT Portal_GroupRoles.RoleId, Portal_ClubGroups.ClubId FROM (Portal_GroupRoles INNER JOIN Portal_ClubGroups ON Portal_GroupRoles.GroupId = Portal_ClubGroups.GroupId) AS cgr WHERE derivedtbl_1.RoleID = cgr.RoleId AND derivedtbl_1.ClubId = cgr.ClubId ) ``` Be wary of splitting the two-column condition into two separate IN clauses; it does not give you the same answer (in general) as the applying the two-column condition in one EXISTS clause.
"Where IN" with multiple columns (SQL Server)
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I have two JSON objects with the same structure and I want to concat them together using Javascript. Is there an easy way to do this?
Based on your description in the comments, you'd simply do an array concat: ``` var jsonArray1 = [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23}]; var jsonArray2 = [{'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}]; jsonArray1 = jsonArray1.concat(jsonArray2); // jsonArray1 = [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23}, //{'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}]; ```
The actual way is using JS Object.assign. ``` Object.assign(target, ...sources) ``` [MDN Link](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) There is another object spread operator which is proposed for ES7 and can be used with Babel plugins. ``` Obj = {...sourceObj1, ...sourceObj2} ```
Concatenate two JSON objects
[ "", "javascript", "json", "" ]
Does anyone know of a c++ library for taking an image and performing image recognition on it such that it can find letters based on a given font and/or font height? Even one that doesn't let you select a font would be nice (eg: readLetters(Image image).
I've been looking into this a lot lately. Your best is simply Tesseract. If you need layout analysis on top of the OCR than go with Ocropus (which in turn uses Tesseract to do the OCR). Layout analysis refers to being able to detect position of text on the image and do things like line segmentation, block segmentation, etc. I've found some really good tips through experimentation with Tesseract that are worth sharing. Basically I had to do a lot of preprocessing for the image. 1. Upsize/Downsize your input image to 300 dpi. 2. Remove color from the image. Grey scale is good. I actually used a dither threshold and made my input black and white. 3. Cut out unnecessary junk from your image. For all three above I used netbpm (a set of image manipulation tools for unix) to get to point where I was getting pretty much 100 percent accuracy for what I needed. If you have a highly customized font and go with tesseract alone you have to "Train" the system -- basically you have to feed a bunch of training data. This is well documented on the tesseract-ocr site. You essentially create a new "language" for your font and pass it in with the -l parameter. The other training mechanism I found was with Ocropus using nueral net (bpnet) training. It requires a lot of input data to build a good statistical model. In terms of invoking Tesseract/Ocropus are both C++. It won't be as simple as ReadLines(Image) but there is an API you can check out. You can also invoke via command line.
While I cannot recommend one in particular, the term you are looking for is OCR (Optical Character Recognition).
C++ Library for image recognition: images containing words to string
[ "", "c++", "fonts", "ocr", "image-recognition", "" ]
I was browsing around for programming troubleshooters, and I was wondering what the alternate would be for Socket Programming; if there is one.
Assuming you have control over the protocol being used, you could go for a higher level of abstraction like .NET's Remoting or WCF.
[TCPClient](https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx) and [UDPClient](http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.aspx) abstract you from the underlying sockets to some degree. They're nice to work with.
What are the alternatives to Socket Programming?
[ "", "c#", "sockets", "" ]
When programming in C++ against the browser's [DOM](http://www.google.co.il/url?sa=t&source=web&ct=res&cd=1&url=http%3A%2F%2Fwww.w3.org%2FDOM%2F&ei=eUhrSaTCDpyY9QSMr5imBw&usg=AFQjCNH0daWhsLwlt2sAqQJ71Vx8WtrHug&sig2=9eYS8DOTG8VOj3tJSKjyvg) each engine has a different set of interfaces, IE has the COM based [MSHTML](<http://msdn.microsoft.com/en-us/library/aa752279(VS.85).aspx)>, Mozilla has the [XPCOM](http://en.wikipedia.org/wiki/XPCOM) based [Gecko DOM](http://www.xulplanet.com/references/xpcomref/ifaces/nsIDOMNSHTMLElement.html) etc. Is there a common API that has [adapters](http://en.wikipedia.org/wiki/Adapter_pattern "Adapter Pattern") for major browsers (and versions)? --- As a clarification, the application in question is a desktop application written in C++ which interacts with browsers, currently we have separate code bases for support of IE and Mozilla and I'm trying to reduce duplications of logic and allow adding new browsers with less effort. A concrete example can be getting the innerHTML property of an HTML element. ``` // Firefox nsAutoString html; nsCOMPtr<nsIDOMNSHTMLElement> elem = do_QueryInterface(obj); if (elem) elem->GetInnerHTML(html); // IE CComBSTR html; MSHTML::IHTMLElementPtr elem = obj; if (elem) elem->get_innerHTML(&html); ```
Your best bet seems to be to define your own interface and write different adapters. In the likeliness that your C++ code won't be employing all DOM traversing capabilities, your interface will only have to define a compact set of traversal functions. As a bonus of defining your own interface, you can easily write a mock adapter for your unit testing.
I've never seen one. For my software, I simple wrote the extension in Firefox's javascript, and then created an Internet Explorer BHO (which I haven't finished yet).
Browser agnostic C++ DOM interface
[ "", "c++", "dom", "cross-browser", "" ]
I want to be able to pass something into an SQL query to determine if I want to select only the ones where a certain column is null. If I was just building a query string instead of using bound variables, I'd do something like: ``` if ($search_undeleted_only) { $sqlString .= " AND deleted_on IS NULL"; } ``` but I want to use bound queries. Would this be the best way? ``` my $stmt = $dbh->prepare(... "AND (? = 0 OR deleted_on IS NULL) "); $stmt->execute($search_undeleted_only); ```
Yes; a related trick is if you have X potential filters, some of them optional, is to have the template say `" AND ( ?=-1 OR some_field = ? ) "`, and create a special function that wraps the execute call and binds all the second ?s. (in this case, -1 is a special value meaning 'ignore this filter'). Update from Paul Tomblin: I edited the answer to include a suggestion from the comments.
So you're relying on short-circuiting semantics of boolean expressions to invoke your `IS NULL` condition? That seems to work. One interesting point is that a constant expression like `1 = 0` that did not have parameters should be factored out by the query optimizer. In this case, since the optimizer doesn't know if the expression is a constant `true` or `false` until execute time, that means it can't factor it out. It must evaluate the expression for every row. So one can assume this add a minor cost to the query, relative to what it would cost if you had used a non-parameterized constant expression. Then combining with `OR` with the `IS NULL` expression may also have implications for the optimizer. It might decide it can't benefit from an index on `deleted_on`, whereas in a simpler expression it would have. This depends on the RDBMS implementation you're using, and the distribution of values in your database.
How can I select rows that are null using bound queries in Perl's DBI?
[ "", "sql", "perl", "dbi", "" ]
Is there a way to show the console in a Windows application? I want to do something like this: ``` static class Program { [STAThread] static void Main(string[] args) { bool consoleMode = Boolean.Parse(args[0]); if (consoleMode) { Console.WriteLine("consolemode started"); // ... } else { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } } ```
What you want to do is not possible in a sane way. There was a similar question [so look at the answers](https://stackoverflow.com/questions/338951/output-to-command-line-if-started-from-command-line#339216). Then there's also an [insane approach](http://www.rootsilver.com/2007/08/how-to-create-a-consolewindow) (site down - [backup available here.](http://web.archive.org/web/20111227234507/http://www.rootsilver.com/2007/08/how-to-create-a-consolewindow)) written by [Jeffrey Knight](https://stackoverflow.com/users/83418/jeffrey-knight): > Question: How do I create an application that can run in either GUI > (windows) mode or command line / console mode? > > On the surface of it, this would seem easy: you create a Console > application, add a windows form to it, and you're off and running. > However, there's a problem: > > Problem: If you run in GUI mode, you end up with both a window and a > pesky console lurking in the background, and you don't have any way to > hide it. > > What people seem to want is a true amphibian application that can run > smoothly in either mode. > > If you break it down, there are actually four use cases here: > > ``` > User starts application from existing cmd window, and runs in GUI mode > User double clicks to start application, and runs in GUI mode > User starts application from existing cmd window, and runs in command mode > User double clicks to start application, and runs in command mode. > ``` > > I'm posting the code to do this, but with a caveat. > > I actually think this sort of approach will run you into a lot more > trouble down the road than it's worth. For example, you'll have to > have two different UIs' -- one for the GUI and one for the command / > shell. You're going to have to build some strange central logic > engine that abstracts from GUI vs. command line, and it's just going > to get weird. If it were me, I'd step back and think about how this > will be used in practice, and whether this sort of mode-switching is > worth the work. Thus, unless some special case called for it, I > wouldn't use this code myself, because as soon as I run into > situations where I need API calls to get something done, I tend to > stop and ask myself "am I overcomplicating things?". > > Output type=Windows Application > > ``` > using System; > using System.Collections.Generic; > using System.Windows.Forms; > using System.Runtime.InteropServices; > using System.Diagnostics; > using Microsoft.Win32; > > namespace WindowsApplication > { > static class Program > { > /* > DEMO CODE ONLY: In general, this approach calls for re-thinking > your architecture! > There are 4 possible ways this can run: > 1) User starts application from existing cmd window, and runs in GUI mode > 2) User double clicks to start application, and runs in GUI mode > 3) User starts applicaiton from existing cmd window, and runs in command mode > 4) User double clicks to start application, and runs in command mode. > > To run in console mode, start a cmd shell and enter: > c:\path\to\Debug\dir\WindowsApplication.exe console > To run in gui mode, EITHER just double click the exe, OR start it from the cmd prompt with: > c:\path\to\Debug\dir\WindowsApplication.exe (or pass the "gui" argument). > To start in command mode from a double click, change the default below to "console". > In practice, I'm not even sure how the console vs gui mode distinction would be made from a > double click... > string mode = args.Length > 0 ? args[0] : "console"; //default to console > */ > > [DllImport("kernel32.dll", SetLastError = true)] > static extern bool AllocConsole(); > > [DllImport("kernel32.dll", SetLastError = true)] > static extern bool FreeConsole(); > > [DllImport("kernel32", SetLastError = true)] > static extern bool AttachConsole(int dwProcessId); > > [DllImport("user32.dll")] > static extern IntPtr GetForegroundWindow(); > > [DllImport("user32.dll", SetLastError = true)] > static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId); > > [STAThread] > static void Main(string[] args) > { > //TODO: better handling of command args, (handle help (--help /?) etc.) > string mode = args.Length > 0 ? args[0] : "gui"; //default to gui > > if (mode == "gui") > { > MessageBox.Show("Welcome to GUI mode"); > > Application.EnableVisualStyles(); > > Application.SetCompatibleTextRenderingDefault(false); > > Application.Run(new Form1()); > } > else if (mode == "console") > { > > //Get a pointer to the forground window. The idea here is that > //IF the user is starting our application from an existing console > //shell, that shell will be the uppermost window. We'll get it > //and attach to it > IntPtr ptr = GetForegroundWindow(); > > int u; > > GetWindowThreadProcessId(ptr, out u); > > Process process = Process.GetProcessById(u); > > if (process.ProcessName == "cmd" ) //Is the uppermost window a cmd process? > { > AttachConsole(process.Id); > > //we have a console to attach to .. > Console.WriteLine("hello. It looks like you started me from an existing console."); > } > else > { > //no console AND we're in console mode ... create a new console. > > AllocConsole(); > > Console.WriteLine(@"hello. It looks like you double clicked me to start > AND you want console mode. Here's a new console."); > Console.WriteLine("press any key to continue ..."); > Console.ReadLine(); > } > > FreeConsole(); > } > } > } > } > ```
This is a tad old (OK, it's VERY old), but I'm doing the exact same thing right now. Here's a very simple solution that's working for me: ``` [DllImport("kernel32.dll", SetLastError = true)] static extern bool AllocConsole(); [DllImport("kernel32.dll")] static extern IntPtr GetConsoleWindow(); [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); const int SW_HIDE = 0; const int SW_SHOW = 5; public static void ShowConsoleWindow() { var handle = GetConsoleWindow(); if (handle == IntPtr.Zero) { AllocConsole(); } else { ShowWindow(handle, SW_SHOW); } } public static void HideConsoleWindow() { var handle = GetConsoleWindow(); ShowWindow(handle, SW_HIDE); } ```
Show Console in Windows Application?
[ "", "c#", "winforms", "console", "" ]
(I still feel like a complete newbie in MS Visual environments... so please bear with!) I'm using Microsoft Visual C# 2008 Express Edition. I have a project and in that project are two different forms. The .cs file for each form starts out: ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Common; using System.Drawing; using System.Text; using System.Windows.Forms; namespace MyNameSpace { public partial class MyFormName : Form { ... ``` (...and the second is "MyFormName2" but no differences besides that) I want to write a function that I know both forms are going to need to access. I right-clicked on my project, selected "Add", selected "New Item" then selected "Code File" and named my file "Common.cs" and it gave me a completely blank file that's in my project. How do I set this up...? I thought I should do the following... ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Common; using System.Drawing; using System.Text; using System.Windows.Forms; namespace MyNameSpace { } ``` ...but then when I try to add a function like: public void mytestfunc() { } within that namespace I get the following error: "Expected class, delegate, enum, interface, or struct" How do I set things up so I can have "mytestfunc" be available to both MyFormName and MyFormName2? Thanks! -Adeena UPDATE: Understand (now) that everything must be in a class, but then I don't understand how to really use it. Does that mean I have to create an object? This common function happens to just be some math... so now if I have this: ``` namespace MyNameSpace { public class MyCommonClass { public void testFunc() { MessageBox.Show("Hee hee!"); return; } } } ``` ...how do I call testFunc from my Form? Must I do the following: ``` MyCommonClass temp = new MyCommonClass; temp.testFunc(); ``` or is there another way to call testFunc?
If you do something like: ``` namespace MyNameSpace { public class myclass { public myMethod() { // Code } } } ``` You will be able to instantiate and access it. If you change it to: ``` namespace MyNameSpace { public class myclass { public static myMethod() { // Code } } } ``` You will be able to call myClass.myMethod without instantiating a new myClass.
The short answer is that everything needs to be inside a class; I'd suggest you sit down with [a basic tutorial](http://www.csharp-station.com/Tutorial.aspx) to help you get to grips with the basics...
How do I add common C# code to a Visual C# 2008 Express project/solution?
[ "", "c#", "visual-studio", "visual-studio-2008", "" ]
I'd like to create a derived control from System.Windows.Forms.ComboBox that is bound to a list of objects that I retrieve from the database. Idea is other developers can just drop this control on their form without having to worry about the datasource, binding, unless they want to. I have tried to extend combobox and then set the DataSource, DisplayMember, and ValueMember in the constructor. ``` public class CustomComboBox : ComboBox { public CustomComboBox() { this.DataSource = MyDAL.GetItems(); // Returns List<MyItem> this.DisplayMember = "Name"; this.ValueMember = "ItemID"; } } ``` Works when I run, but throws a lot of errors in Visual Studio's once it's added to any form. The error I get is: > "Code generation for property 'Items' failed. Error was: 'Object reference not set to an instance of an object" What's the correct way to accomplish this (C#, Winforms, .NET 2.0+)?
DesignMode property doesn't work in a constructor. From googling for a while, found this LicenseManager thing. ``` if (LicenseManager.UsageMode != LicenseUsageMode.Designtime) { // Do your database/IO/remote call } ``` However LicenseManager only works in constructors. For eventhandlers use DesignMode. Source: <http://dotnetfacts.blogspot.com/2009/01/identifying-run-time-and-design-mode.html> Another reference: <http://weblogs.asp.net/fmarguerie/archive/2005/03/23/395658.aspx>
The problem is that the designer actually does some compilation and execution in a slightly different context than normally running the program does. In the constructor, you can wrap your code in: ``` if (!DesignMode) { //Do this stuff } ``` That will tell the designer to not run any of your initialization code while it is being designed.
How to create a derived ComboBox with pre-bound datasource that is designer friendly?
[ "", "c#", "winforms", "combobox", "datasource", "designer", "" ]
Are there any nvl() equivalent functions in SQL? Or something close enough to be used in the same way in certain scenarios? --- UPDATE: no if statements no case statements no isnull no coalesce --- ``` select nvl (purge_date,"SODIUFOSDIUFSDOIFUDSF") from id_rec where id=36581; (expression) SODIUFOSDIUFSDOIFUDSF 1 row(s) retrieved. select isnull (purge_date,"SODIUFOSDIUFSDOIFUDSF") from id_rec where id=36581; 674: Routine (isnull) can not be resolved. Error in line 1 Near character position 8 select coalesce (purge_date,"SODIUFOSDIUFSDOIFUDSF") from id_rec where id=36581; 674: Routine (coalesce) can not be resolved. Error in line 1 Near character position 8 select decode(purge_date, NULL, "01/01/2009", purge_date) from id_rec where id=74115; 800: Corresponding types must be compatible in CASE expression. Error in line 1 Near character position 57 ```
You seem to be using Informix. AFAIK, there is DECODE there: `DECODE(field, NULL, 'it is null, man', field)` should give you same result as `NVL(field, 'it is null, man')` Please post exact name and version of the RDBMS you are using.
[ISNULL](http://msdn.microsoft.com/en-us/library/ms184325.aspx) (for a single replace) or [COALESCE](http://msdn.microsoft.com/en-us/library/ms190349.aspx) (Returns the first nonnull expression among its arguments.)
SQL nvl equivalent - without if/case statements & isnull & coalesce
[ "", "sql", "syntax", "informix", "null", "" ]
I have a `DataSet` populated from Excel Sheet. I wanted to use SQLBulk Copy to Insert Records in `Lead_Hdr` table where `LeadId` is PK. I am having following error while executing the code below: > The given ColumnMapping does not match up with any column in the > source or destination ``` string ConStr=ConfigurationManager.ConnectionStrings["ConStr"].ToString(); using (SqlBulkCopy s = new SqlBulkCopy(ConStr,SqlBulkCopyOptions.KeepIdentity)) { if (MySql.State==ConnectionState.Closed) { MySql.Open(); } s.DestinationTableName = "PCRM_Lead_Hdr"; s.NotifyAfter = 10000; #region Comment s.ColumnMappings.Clear(); #region ColumnMapping s.ColumnMappings.Add("ClientID", "ClientID"); s.ColumnMappings.Add("LeadID", "LeadID"); s.ColumnMappings.Add("Company_Name", "Company_Name"); s.ColumnMappings.Add("Website", "Website"); s.ColumnMappings.Add("EmployeeCount", "EmployeeCount"); s.ColumnMappings.Add("Revenue", "Revenue"); s.ColumnMappings.Add("Address", "Address"); s.ColumnMappings.Add("City", "City"); s.ColumnMappings.Add("State", "State"); s.ColumnMappings.Add("ZipCode", "ZipCode"); s.ColumnMappings.Add("CountryId", "CountryId"); s.ColumnMappings.Add("Phone", "Phone"); s.ColumnMappings.Add("Fax", "Fax"); s.ColumnMappings.Add("TimeZone", "TimeZone"); s.ColumnMappings.Add("SicNo", "SicNo"); s.ColumnMappings.Add("SicDesc", "SicDesc"); s.ColumnMappings.Add("SourceID", "SourceID"); s.ColumnMappings.Add("ResearchAnalysis", "ResearchAnalysis"); s.ColumnMappings.Add("BasketID", "BasketID"); s.ColumnMappings.Add("PipeLineStatusId", "PipeLineStatusId"); s.ColumnMappings.Add("SurveyId", "SurveyId"); s.ColumnMappings.Add("NextCallDate", "NextCallDate"); s.ColumnMappings.Add("CurrentRecStatus", "CurrentRecStatus"); s.ColumnMappings.Add("AssignedUserId", "AssignedUserId"); s.ColumnMappings.Add("AssignedDate", "AssignedDate"); s.ColumnMappings.Add("ToValueAmt", "ToValueAmt"); s.ColumnMappings.Add("Remove", "Remove"); s.ColumnMappings.Add("Release", "Release"); s.ColumnMappings.Add("Insert_Date", "Insert_Date"); s.ColumnMappings.Add("Insert_By", "Insert_By"); s.ColumnMappings.Add("Updated_Date", "Updated_Date"); s.ColumnMappings.Add("Updated_By", "Updated_By"); #endregion #endregion s.WriteToServer(sourceTable); s.Close(); MySql.Close(); } ```
Well, is it right? Do the column names exist on both sides? To be honest, I've never bothered with mappings. I like to keep things simple - I tend to have a staging table that looks like the input on the server, then I `SqlBulkCopy` into the staging table, and finally run a stored procedure to move the table from the staging table into the actual table; advantages: * no issues with live data corruption if the import fails at any point * I can put a transaction just around the SPROC * I can have the bcp work without logging, safe in the knowledge that the SPROC will be logged * it is simple ;-p (no messing with mappings) As a final thought - if you are dealing with bulk data, you can get better throughput using `IDataReader` (since this is a streaming API, where-as `DataTable` is a buffered API). For example, I tend to hook CSV imports up using [CsvReader](http://www.codeproject.com/KB/database/CsvReader.aspx) as the source for a SqlBulkCopy. Alternatively, I have written shims around `XmlReader` to present each first-level element as a row in an `IDataReader` - very fast.
I've encountered the same problem while copying data from access to SQLSERVER 2005 and i found that the column mappings are case sensitive on both data sources regardless of the databases sensitivity.
SqlBulkCopy Not Working
[ "", "c#", "asp.net", "sqlbulkcopy", "" ]
Here's the setup I have in a vs2008 solution: Data layer in a project named MyProject.Data Web application in a project named MyProject.Web MyProject.Web has a reference to MyProject.Data In MyProject.Web I have a class I use called "MySite.Utils" I want to be able to use MySite.Utils in MyProject.Data but I can't because it would cause a circular reference. One solution which is NOT possible is creating a third project and moving "MySite.Utils" in there because MySite.Utils actually uses MyProject.Data (thus it needs to reference it and another circular reference would be created) What's the best/easiest way to fix this?
You need to move MySite.Utils to MyProject.Data by the sound of it
The best fix is to simplify things... for example, is that utility code *data* utility code, or *ui* utility code. Perhaps split it into 2 dlls; that might make things simpler. After that, interfaces are a reasonable option, but you might need some IoC framework to provide the implementations. IoC is the most common way of getting around this type of problem. For example, you declare your `ICustomerRepository` in a reference assembly; everything references that. Your DAL **implements** the interface, but the utils project no longer needs to reference the DAL - just the interface assembly. Your DAL can now reference the utils - or it might just know about another interface `IDataUtils` (better to split it up more meaningfully, of course). The glue here is the IoC container, such as Castle Windsor. Finally, and **don't do this**, but even though the IDE doesn't let you, it is possible to create circular references in .NET (via the command line tools); it is legal, but it gets very messy very quickly, and it is hard to repair a broken build. Don't go there!!
vs2008 circular references (c#)
[ "", "c#", "asp.net", "visual-studio-2008", "" ]
Is it a good concept to use multiple inheritance or can I do other things instead?
Multiple inheritance (abbreviated as MI) *smells*, which means that *usually*, it was done for bad reasons, and it will blow back in the face of the maintainer. ## Summary 1. Consider composition of features, instead of inheritance 2. Be wary of the Diamond of Dread 3. Consider inheritance of multiple interfaces instead of objects 4. Sometimes, Multiple Inheritance is the right thing. If it is, then use it. 5. Be prepared to defend your multiple-inherited architecture in code reviews ## 1. Perhaps composition? This is true for inheritance, and so, it's even more true for multiple inheritance. Does your object really need to inherit from another? A `Car` does not need to inherit from an `Engine` to work, nor from a `Wheel`. A `Car` has an `Engine` and four `Wheel`. If you use multiple inheritance to resolve these problems instead of composition, then you've done something wrong. ## 2. The Diamond of Dread Usually, you have a class `A`, then `B` and `C` both inherit from `A`. And (don't ask me why) someone then decides that `D` must inherit both from `B` and `C`. I've encountered this kind of problem twice in eight years, and it is amusing to see because of: 1. How much of a mistake it was from the beginning (In both cases, `D` should not have inherited from both `B` and `C`), because this was bad architecture (in fact, `C` should not have existed at all...) 2. How much maintainers were paying for that, because in C++, the parent class `A` was present twice in its grandchild class `D`, and thus, updating one parent field `A::field` meant either updating it twice (through `B::field` and `C::field`), or having something go silently wrong and crash, later (new a pointer in `B::field`, and delete `C::field`...) Using the keyword virtual in C++ to qualify the inheritance avoids the double layout described above if this is not what you want, but anyway, in my experience, you're probably doing something wrong... In Object hierarchy, you should try to keep the hierarchy as a Tree (a node has ONE parent), not as a graph. ### More about the Diamond (edit 2017-05-03) The real problem with the Diamond of Dread in C++ (*assuming the design is sound - have your code reviewed!*), is that **you need to make a choice**: * Is it desirable for the class `A` to exist twice in your layout, and what does it mean? If yes, then by all means inherit from it twice. * if it should exist only once, then inherit from it virtually. This choice is inherent to the problem, and in C++, unlike other languages, you can actually do it without dogma forcing your design at language level. But like all powers, with that power comes responsibility: Have your design reviewed. ## 3. Interfaces Multiple inheritance of zero or one concrete classes, and zero or more interfaces is usually Okay, because you won't encounter the Diamond of Dread described above. In fact, this is how things are done in Java. Usually, what you mean when C inherits from `A` and `B` is that users can use `C` as if it was an `A`, and/or as if it was a `B`. In C++, an interface is an abstract class which has: 1. ~~all its method declared pure virtual (suffixed by = 0)~~ (removed the 2017-05-03) 2. no member variables The Multiple inheritance of zero to one real object, and zero or more interfaces is not considered "smelly" (at least, not as much). ### More about the C++ Abstract Interface (edit 2017-05-03) First, the NVI pattern can be used to produce an interface, because **the real criteria is to have no state** (i.e. no member variables, except `this`). Your abstract interface's point is to publish a contract ("you can call me this way, and this way"), nothing more, nothing less. The limitation of having only abstract virtual methods should be a design choice, not an obligation. Second, in C++, it makes sense to inherit virtually from abstract interfaces, (even with the additional cost/indirection). If you don't, and the interface inheritance appears multiple times in your hierarchy, then you'll have ambiguities. Third, object orientation is great, but it is not *The Only Truth Out ThereTM* in C++. Use the right tools, and always remember you have other paradigms in C++ offering different kinds of solutions. ## 4. Do you really need Multiple Inheritance? Sometimes, yes. Usually, your `C` class is inheriting from `A` and `B`, and `A` and `B` are two unrelated objects (i.e. not in the same hierarchy, nothing in common, different concepts, etc.). For example, you could have a system of `Nodes` with X,Y,Z coordinates, able to do a lot of geometric calculations (perhaps a point, part of geometric objects) and each Node is an Automated Agent, able to communicate with other agents. Perhaps you already have access to two libraries, each with its own namespace (another reason to use namespaces... But you use namespaces, don't you?), one being `geo` and the other being `ai` So you have your own `own::Node` derive both from `ai::Agent` and `geo::Point`. This is the moment when you should ask yourself if you should not use composition instead. If `own::Node` is really really both a `ai::Agent` and a `geo::Point`, then composition will not do. Then you'll need multiple inheritance, having your `own::Node` communicate with other agents according to their position in a 3D space. *(You'll note that `ai::Agent` and `geo::Point` are completely, totally, fully UNRELATED... This drastically reduces the danger of multiple inheritance)* ### Other cases (edit 2017-05-03) There are other cases: * using (hopefully private) inheritance as implementation detail * some C++ idioms like policies could use multiple inheritance (when each part needs to communicate with the others through `this`) * the virtual inheritance from std::exception ([Is Virtual Inheritance necessary for Exceptions?](https://stackoverflow.com/questions/5874255/)) * etc. Sometimes you can use composition, and sometimes MI is better. The point is: You have a choice. Do it responsibly (and have your code reviewed). ## 5. So, should I do Multiple Inheritance? Most of the time, in my experience, no. MI is not the right tool, even if it seems to work, because it can be used by the lazy to pile features together without realizing the consequences (like making a `Car` both an `Engine` and a `Wheel`). But sometimes, yes. And at that time, nothing will work better than MI. But because MI is smelly, be prepared to defend your architecture in code reviews (and defending it is a good thing, because if you're not able to defend it, then you should not do it).
From an [interview with Bjarne Stroustrup](http://www.artima.com/intv/modern.html): > People quite correctly say that you don't need multiple inheritance, because anything you can do with multiple inheritance you can also do with single inheritance. You just use the delegation trick I mentioned. Furthermore, you don't need any inheritance at all, because anything you do with single inheritance you can also do without inheritance by forwarding through a class. Actually, you don't need any classes either, because you can do it all with pointers and data structures. But why would you want to do that? When is it convenient to use the language facilities? When would you prefer a workaround? I've seen cases where multiple inheritance is useful, and I've even seen cases where quite complicated multiple inheritance is useful. Generally, I prefer to use the facilities offered by the language to doing workarounds
Why should I avoid multiple inheritance?
[ "", "c++", "oop", "multiple-inheritance", "" ]
E,g ``` class Test { public: void setVal(const std::string& str) { this.isVal = str; //This will error out } private: string isVal; }; ```
In C++, `this` is a pointer (as opposed to a reference). So you have to say `this->isVal` instead.
Adding to [Chris's answer](https://stackoverflow.com/questions/467851/why-cant-we-use-this-inside-the-class#467853), you can also do: ``` (*this).isVal = str; ``` However, it's better to do what Chris said, as it is more orthodox. This is just illustrating that you need to de-reference the pointer before calling methods on it.
Why can't we use "this" inside the class?
[ "", "c++", "" ]
As an example, when inserting a record into a table with a unique index, is it best to test first? *e.g.*, ``` $mysqli->query('SELECT email FROM tblUser WHERE email = 'foo@bar.org'); ``` then make sure 0 rows are returned, *then* do the insert? ``` $mysqli->query('INSERT INTO tblUser ...'); ``` Or is it better to just skip the test and handle the error in the event there's a duplicate entry? THANKS!
It's better to insert and handle any duplicate key errors. The reason is that if you test first, some other client can still insert the value in the brief moment between your test and your insert. So you'd need to handle errors anyway.
Broadly speaking, there are three ways to handle this situation with a single query (fewer queries is usually a good thing to shoot for), but none of them is a universal "best way". Which you should use depends on your needs. The first is, as you mention, running the `INSERT …` blindly and handling any errors PHP. This is the best approach when a duplicate key indicates a procedural problem (a bug in the software, a user trying to register a name that's already been used, etc.), as it allows you to perform additional operations before committing to a database update. Second, there is the `INSERT IGNORE …` syntax. I would tend to call this the least commonly-useful approach, as it **discards your `INSERT` completely** if the key already exists. Primarily useful when a row (or rows) may or may not have been added to the table previously, but the data is known not to have changed. Lastly, you can use an `INSERT … ON DUPLICATE KEY UPDATE …` statement. These can get rather verbose, but are very handy, as they allow you to insert data into your table without worrying about whether older data exists. If so, the existing row is updated. If not, a new one is inserted. Either way, your table will have the latest data available.
MySQL Insert: Test first?
[ "", "php", "mysql", "database", "" ]
I'd like to create a random string, consisting of alpha-numeric characters. I want to be able to be specify the length of the string. How do I do this in C++?
Mehrdad Afshari's [answer](https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c#440147) would do the trick, but I found it a bit too verbose for this simple task. Look-up tables can sometimes do wonders: ``` #include <ctime> #include <iostream> #include <unistd.h> std::string gen_random(const int len) { static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; std::string tmp_s; tmp_s.reserve(len); for (int i = 0; i < len; ++i) { tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)]; } return tmp_s; } int main(int argc, char *argv[]) { srand((unsigned)time(NULL) * getpid()); std::cout << gen_random(12) << "\n"; return 0; } ``` Note that `rand` [generates poor-quality random numbers](https://stackoverflow.com/a/19666713/6243352).
Here's my adaptation of Ates Goral's answer using C++11. I've added the lambda in here, but the principle is that you could pass it in and thereby control what characters your string contains: ``` std::string random_string( size_t length ) { auto randchar = []() -> char { const char charset[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; const size_t max_index = (sizeof(charset) - 1); return charset[ rand() % max_index ]; }; std::string str(length,0); std::generate_n( str.begin(), length, randchar ); return str; } ``` Here is an example of passing in a lambda to the random string function: <http://ideone.com/Ya8EKf> Why would you use **C++11**? 1. Because you can produce strings that follow a certain **probability distribution** (or distribution combination) for the character set you're interested in. 2. Because it has built-in support for **non-deterministic random numbers** 3. Because it supports unicode, so you could change this to an internationalized version. For example: ``` #include <iostream> #include <vector> #include <random> #include <functional> //for std::function #include <algorithm> //for std::generate_n typedef std::vector<char> char_array; char_array charset() { //Change this to suit return char_array( {'0','1','2','3','4', '5','6','7','8','9', 'A','B','C','D','E','F', 'G','H','I','J','K', 'L','M','N','O','P', 'Q','R','S','T','U', 'V','W','X','Y','Z', 'a','b','c','d','e','f', 'g','h','i','j','k', 'l','m','n','o','p', 'q','r','s','t','u', 'v','w','x','y','z' }); }; // given a function that generates a random character, // return a string of the requested length std::string random_string( size_t length, std::function<char(void)> rand_char ) { std::string str(length,0); std::generate_n( str.begin(), length, rand_char ); return str; } int main() { //0) create the character set. // yes, you can use an array here, // but a function is cleaner and more flexible const auto ch_set = charset(); //1) create a non-deterministic random number generator std::default_random_engine rng(std::random_device{}()); //2) create a random number "shaper" that will give // us uniformly distributed indices into the character set std::uniform_int_distribution<> dist(0, ch_set.size()-1); //3) create a function that ties them together, to get: // a non-deterministic uniform distribution from the // character set of your choice. auto randchar = [ ch_set,&dist,&rng ](){return ch_set[ dist(rng) ];}; //4) set the length of the string you want and profit! auto length = 5; std::cout<<random_string(length,randchar)<<std::endl; return 0; } ``` [Sample output.](http://ideone.com/LxhX15)
How do I create a random alpha-numeric string in C++?
[ "", "c++", "string", "random", "" ]
I can't seem to get Python to import a module in a subfolder. I get the error when I try to create an instance of the class from the imported module, but the import itself succeeds. Here is my directory structure: ``` Server -server.py -Models --user.py ``` Here's the contents of server.py: ``` from sys import path from os import getcwd path.append(getcwd() + "\\models") #Yes, i'm on windows print path import user u=user.User() #error on this line ``` And user.py: ``` class User(Entity): using_options(tablename='users') username = Field(String(15)) password = Field(String(64)) email = Field(String(50)) status = Field(Integer) created = Field(DateTime) ``` The error is: AttributeError: 'module' object has no attribute 'User'
I believe you need to create a file called `__init__.py` in the Models directory so that python treats it as a module. Then you can do: ``` from Models.user import User ``` You can include code in the `__init__.py` (for instance initialization code that a few different classes need) or leave it blank. But it must be there.
You have to create `__init__.py` on the `Models` subfolder. The file may be empty. It defines a package. Then you can do: ``` from Models.user import User ``` Read all about it in python tutorial, [here](http://docs.python.org/tutorial/modules.html#packages). There is also a good article about file organization of python projects [here](http://jcalderone.livejournal.com/39794.html).
Can't get Python to import from a different folder
[ "", "python", "python-2.x", "" ]
I'm writing an application where a user provides a connection string manually and I'm wondering if there is any way that I could validate the connection string - I mean check if it's correct and if the database exists.
You could try to connect? For quick (offline) validation, perhaps use `DbConnectionStringBuilder` to parse it... ``` DbConnectionStringBuilder csb = new DbConnectionStringBuilder(); csb.ConnectionString = "rubb ish"; // throws ``` But to check whether the db exists, you'll need to try to connect. Simplest if you know the provider, of course: ``` using(SqlConnection conn = new SqlConnection(cs)) { conn.Open(); // throws if invalid } ``` If you only know the provider as a string (at runtime), then use `DbProviderFactories`: ``` string provider = "System.Data.SqlClient"; // for example DbProviderFactory factory = DbProviderFactories.GetFactory(provider); using(DbConnection conn = factory.CreateConnection()) { conn.ConnectionString = cs; conn.Open(); } ```
Try this. ``` try { using(var connection = new OleDbConnection(connectionString)) { connection.Open(); return true; } } catch { return false; } ```
How to check if connection string is valid?
[ "", "c#", "connection-string", "" ]
Is there some way to make c++ dlls built with diffrent compilers compatible with each other? The classes can have factory methods for creation and destruction, so each compiler can use its own new/delete (since diffrent runtimes have there own heaps). I tried the following code but it crashed on the first member method: interface.h ``` #pragma once class IRefCounted { public: virtual ~IRefCounted(){} virtual void AddRef()=0; virtual void Release()=0; }; class IClass : public IRefCounted { public: virtual ~IClass(){} virtual void PrintSomething()=0; }; ``` test.cpp compiled with VC9, test.exe ``` #include "interface.h" #include <iostream> #include <windows.h> int main() { HMODULE dll; IClass* (*method)(void); IClass *dllclass; std::cout << "Loading a.dll\n"; dll = LoadLibraryW(L"a.dll"); method = (IClass* (*)(void))GetProcAddress(dll, "CreateClass"); dllclass = method();//works dllclass->PrintSomething();//crash: Access violation writing location 0x00000004 dllclass->Release(); FreeLibrary(dll); std::cout << "Done, press enter to exit." << std::endl; std::cin.get(); return 0; } ``` a.cpp compiled with g++ g++.exe -shared c.cpp -o c.dll ``` #include "interface.h" #include <iostream> class A : public IClass { unsigned refCnt; public: A():refCnt(1){} virtual ~A() { if(refCnt)throw "Object deleted while refCnt non-zero!"; std::cout << "Bye from A.\n"; } virtual void AddRef() { ++refCnt; } virtual void Release() { if(!--refCnt) delete this; } virtual void PrintSomething() { std::cout << "Hello World from A!" << std::endl; } }; extern "C" __declspec(dllexport) IClass* CreateClass() { return new A(); } ``` EDIT: I added the following line to the GCC CreateClass method, the text was correctly printed to the console, so its defenatly the function call thats killing it. ``` std::cout << "C.DLL Create Class" << std::endl; ``` I was wondering, how does COM manage to maintain binary compatibility even across languages, since its basicly all classes with inheritence (although only single) and therefore virtual functions. I'm not massivly bothered if I cant have overloaded operators/functions as long as I can maintain the basic OOP stuff (ie classes and single inheritence).
You should be able to mix modules built with different compilers if you lower your expectations and stick to simple functions. The way classes and virtual functions behave is defined by the C++ standard, but the way that's implemented is up to the compiler. In this case, I know that VC++ builds objects which have virtual functions with a "vtable" pointer in the first 4 bytes of the object (I'm assuming 32-bit), and that points to a table of pointers to the method entry points. So the line: `dllclass->PrintSomething();` is actually equivalent to something like: ``` struct IClassVTable { void (*pfIClassDTOR) (Class IClass * this) void (*pfIRefCountedAddRef) (Class IRefCounted * this); void (*pfIRefCountedRelease) (Class IRefCounted * this); void (*pfIClassPrintSomething) (Class IClass * this); ... }; struct IClass { IClassVTable * pVTab; }; (((struct IClass *) dllclass)->pVTab->pfIClassPrintSomething) (dllclass); ``` If the g++ compiler is implementing the virtual function tables in any way differently from MSFT VC++ -- as it is free to do and still be conformant to the C++ standard -- this will just crash as you've demonstrated. The VC++ code expects the function pointers to be in particular places in memory (relative to the object pointer). It gets more complicated by inheritance, and really, really, complicated with multiple inheritance and virtual inheritance. Microsoft has been very public about the way VC++ implements classes, so you can write code that depends on it. For example, a lot of COM object headers distributed by MSFT have both C and C++ bindings in the header. The C bindings expose their vtable structure like my code above does. On the other hand, GNU -- IIRC -- has left open the option of using different implementations in different releases, and just guaranteeing the programs built with it's compiler (only!) will conform to the standard behaviour, The short answer is to stick to simple C-style functions, POD structures (Plain Old Data; i.e., no virtual functions), and pointers to opaque objects.
You're almost certainly asking for trouble if you do this - while other commenters are correct that the C++ ABI may be the same in some instances, the two libraries are using different CRTs, different versions of the STL, different exception throwing semantics, different optimizations... you're heading down a path towards madness.
Dll compatibility between compilers
[ "", "c++", "dll", "compiler-construction", "binary-compatibility", "" ]
Following code, when compiled and run with g++, prints '1' twice, whereas I expect '1' to be printed only once, since I am dumping a single structure to the file, but while reading back it seems to be reading two structures. Why? ``` #include <iostream.h> #include <fstream.h> int main(){ struct student { int rollNo; }; struct student stud1; stud1.rollNo = 1; ofstream fout; fout.open("stu1.dat"); fout.write((char*)&stud1,sizeof(stud1)); fout.close(); ifstream filin("stu1.dat"); struct student tmpStu; while(!filin.eof()) { filin.read((char*)&tmpStu,sizeof(tmpStu)); cout << tmpStu.rollNo << endl; } filin.close(); } ```
`eof` only gets set after a read fails, so the read runs twice, and the second time, it doesn't modify the buffer. Try this: ``` while(filin.read((char*)&tmpStu,sizeof(tmpStu))) { cout << tmpStu.rollNo << endl; } ``` Or ``` while(!filin.read((char*)&tmpStu,sizeof(tmpStu)).eof()) { cout << tmpStu.rollNo << endl; } ``` Read returns a reference to filin when called, which will evaluate to true if the stream is still good. When read fails to read any more data, the reference will evaluate to false, which will prevent it from entering the loop.
Your while loop is executing twice because the EOF condition is not true until the first attempt to read beyond the end of the file. So the cout is executed twice.
C++ file handling (structures)
[ "", "c++", "file", "file-io", "fstream", "" ]
I have a `List<List<int>>`. I would like to convert it into a `List<int>` where each int is unique. I was wondering if anyone had an elegant solution to this using LINQ. I would like to be able to use the Union method but it creates a new List<> everytime. So I'd like to avoid doing something like this: ``` List<int> allInts = new List<int>(); foreach(List<int> list in listOfLists) allInts = new List<int>(allInts.Union(list)); ``` Any suggestions? Thanks!
``` List<List<int>> l = new List<List<int>>(); l.Add(new List<int> { 1, 2, 3, 4, 5, 6}); l.Add(new List<int> { 4, 5, 6, 7, 8, 9 }); l.Add(new List<int> { 8, 9, 10, 11, 12, 13 }); var result = (from e in l from e2 in e select e2).Distinct(); ``` ### Update 09.2013 But these days I would actually write it as ``` var result2 = l.SelectMany(i => i).Distinct(); ```
``` List<int> result = listOfLists .SelectMany(list => list) .Distinct() .ToList(); ```
Convert List<List<T>> into List<T> in C#
[ "", "c#", "linq", "generics", "list", "union", "" ]
Would like to create a strong password in C++. Any suggestions? * I assume it should use alpha (upper and lower), numeric, special characters. * It would be good to be able to specify a minimum length. * It would be great to avoid characters that are hard to visually distinguish like "O" and "O" * It would be great to void all characters same, dictionary words, reversed words, names. Any other tips? Where could I find code like this?
[APG](http://www.adel.nursat.kz/apg/download.shtml) (Automated Password Generator) implements all but your last requirement (no dictionary words / usernames / repeated characters). It includes both pronounceable and fully random password generation algorithms. Pronounceable passwords look something like this: ``` yevGaijra clishahopp jewnAms8 RacMevOm Duheamch& raicsant~ ``` It's written in C and is available under a BSD-like license. Cryptographically speaking, I'm not sure that your last requirement is valid...? If the password generation is truly random, then a password of `aaaaaaaa` is just as likely as a password of `6-n&1jIK`, and if your attacker knows your algorithm, then by disallowing passwords like `aaaaaaaa`, you're reducing the attacker's search space.
There's a few ways. The easy isn't necessarily the best Create a string representing all the characters you want to define (meaning, no O's or 0s's, whatever), then fill a random-length string with random characters from that set. The next step is to keep generating until you pass all assertions. That is, check for dictionary words, reverse names, etc. There will be times where generation takes longer than expected, but should still be faster than you can notice.
How do I create a strong password string in C++?
[ "", "c++", "string", "passwords", "" ]
I'm writing a Java Swing application using the Metal look-and-feel. Every time there is a JButton in my application the user uses the Tab key to move the focus to the button and then hits the Enter key. Nothing happens! If he hits the Space key the button events are fired. How do I assign the Enter key to trigger the same events as the Space key? Thank you for your help.
I found the following: <http://tips4java.wordpress.com/2008/10/25/enter-key-and-button/> Where Rob Camick writes that when using JDK5 and later you simply add... ``` UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE); ``` ...to the application to solve the problem. This did the trick for me! And I can't imagine anything simpler. However, when using older versions of Java you will have to do something like Richard and Peter describe in their answers to this question.
Here is complete example. Richard was close, but you also need to map pressed ENTER to action, not just released. To make it work for ALL buttons, I have put this mapping to default input map for buttons. Add imports, and it should be runnable. --- ``` public class Main implements Runnable { public static void main(String[] args) { SwingUtilities.invokeLater(new Main()); } @Override public void run() { setupEnterActionForAllButtons(); JFrame frame = new JFrame("Button test"); frame.getContentPane().add(createButton(), BorderLayout.NORTH); frame.getContentPane().add(createButton(), BorderLayout.SOUTH); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } private void setupEnterActionForAllButtons() { InputMap im = (InputMap) UIManager.getDefaults().get("Button.focusInputMap"); Object pressedAction = im.get(KeyStroke.getKeyStroke("pressed SPACE")); Object releasedAction = im.get(KeyStroke.getKeyStroke("released SPACE")); im.put(KeyStroke.getKeyStroke("pressed ENTER"), pressedAction); im.put(KeyStroke.getKeyStroke("released ENTER"), releasedAction); } private JButton createButton() { JButton b = new JButton("press enter"); b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("Pressed"); } }); return b; } } ```
How do I assign Enter as the trigger key of all JButtons in my Java application?
[ "", "java", "swing", "events", "jbutton", "" ]
How come, in Java, I can write ``` List<?> list = new LinkedList<Double>(); ``` but not ``` List<Container<?>> list = new LinkedList<Container<Double>>(); ``` where Container is just something like ``` public class Container<T> { ... } ``` This came up because I have a method that accepts a `List<Container<?>>`, and I would like to use Arrays.asList to pass arguments to it: ``` process(Arrays.asList(new Container<Double>(), new Container<Double>())); ``` But the language doesn't allow this, because it infers the type of `Arrays.asList` to be `List<Container<Double>>`, and that is not assignable to `List<Container<?>>`. If I add a String-parameterized Container to the call, ``` process(Arrays.asList(new Container<Double>(), new Container<String>())); ``` it still doesn't work, because it infers the type `List<Container<? extends Serializable & Comparable<?>>>` for Arrays.asList. Only if I pass in something that is neither Comparable nor Serializable does it work properly. Of course, I can put in a cast and get the compiler to shut up, but I'm wondering if I'm doing something wrong here.
Each parameterization must be wildcarded: ``` List<? extends Container<?>> list = new LinkedList<Container<Double>>(); ``` Edit: I was searching through [Angelika Langer's FAQ](http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html) for an explanation, but didn't find one (it's probably there, but hiding somewhere in the 500 pages). The way to think about this is that each parameterization is independent, and the compiler will not infer information about the parameterization unless you explicitly say to do so.
> Edit: I was searching through Angelika Langer's FAQ for an explanation, but didn't find one (it's probably there, but hiding somewhere in the 500 pages). Thank you very much for the answer. I found an explanation in the FAQ, and after some squinting at it I think I get it. <http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeArguments.html#What%20do%20multilevel%20wildcards%20mean>?
Java generics: List<Container<?>> = new LinkedList<Container<Double>>() is prohibited?
[ "", "java", "generics", "" ]
Refering to a previously asked [question](https://stackoverflow.com/questions/373020/finding-the-current-active-window-in-mac-os-x-using-python "question"), I would like to know how to get the title of the current active document. I tried the script mention in the answers to the question above. This works, but only gives me the name of the application. For example, I am writing this question: When I fire up the script it gives me the name of the application, i.e. "Firefox". This is pretty neat, but does not really help. I would rather like to capture the title of my current active document. See the image. [Firefox title http://img.skitch.com/20090126-nq2egknhjr928d1s74i9xixckf.jpg](http://img.skitch.com/20090126-nq2egknhjr928d1s74i9xixckf.jpg) I am using Leopard, so no backward compatibility needed. Also I am using Python's Appkit to gain access to the NSWorkspace class, but if you tell me the Objective-C code, I could figure out the translation to Python. --- Ok, I've got a solution which is not very satisfing, thats why I don't mark Koen Bok's answer. At least not yet. ``` tell application "System Events" set frontApp to name of first application process whose frontmost is true end tell tell application frontApp if the (count of windows) is not 0 then set window_name to name of front window end if end tell ``` Save as script and invoke it with osascript from the shell.
As far as I know your best bet is wrapping an AppleScript. But AppleScript is magic to me so I leave it as an exercise for the questioner :-) This might help a little: [A script to resize frontmost two windows to fill screen - Mac OS X Hints](http://hints.macworld.com/article.php?story=20060105082728937)
In Objective-C, the short answer, using a little Cocoa and mostly the [Carbon Accessibility API](https://developer.apple.com/library/mac/documentation/Accessibility/Reference/AccessibilityCarbonRef/Reference/reference.html) is: ``` // Get the process ID of the frontmost application. NSRunningApplication* app = [[NSWorkspace sharedWorkspace] frontmostApplication]; pid_t pid = [app processIdentifier]; // See if we have accessibility permissions, and if not, prompt the user to // visit System Preferences. NSDictionary *options = @{(id)kAXTrustedCheckOptionPrompt: @YES}; Boolean appHasPermission = AXIsProcessTrustedWithOptions( (__bridge CFDictionaryRef)options); if (!appHasPermission) { return; // we don't have accessibility permissions // Get the accessibility element corresponding to the frontmost application. AXUIElementRef appElem = AXUIElementCreateApplication(pid); if (!appElem) { return; } // Get the accessibility element corresponding to the frontmost window // of the frontmost application. AXUIElementRef window = NULL; if (AXUIElementCopyAttributeValue(appElem, kAXFocusedWindowAttribute, (CFTypeRef*)&window) != kAXErrorSuccess) { CFRelease(appElem); return; } // Finally, get the title of the frontmost window. CFStringRef title = NULL; AXError result = AXUIElementCopyAttributeValue(window, kAXTitleAttribute, (CFTypeRef*)&title); // At this point, we don't need window and appElem anymore. CFRelease(window); CFRelease(appElem); if (result != kAXErrorSuccess) { // Failed to get the window title. return; } // Success! Now, do something with the title, e.g. copy it somewhere. // Once we're done with the title, release it. CFRelease(title); ``` Alternatively, it may be simpler to use the CGWindow API, as alluded to in [this StackOverflow answer](https://stackoverflow.com/a/3042284/308464).
Get the title of the current active Window/Document in Mac OS X
[ "", "python", "objective-c", "macos", "" ]
Here's the thing: I have two applications, written in C++ and running on two machines with different OS (one Linux and one Windows). One of this process is in charge of updating an XML file on a NAS (Network Attached Storage) while the other one reads this file. Is it possible to synchronize these two processes in order to avoid reading of the file at the same time it's being modified?
You could create a lock file on the server that is created before you do a write, wait then write and delete on completion., Have the read process check for the token before reading the file. **Edit**: To address the comments, you can implement a double-checked locking type pattern. Have both reader and writer have a locking file and double check before you do work, something like: Reader: Check for write lock file, create read lock file, check for write lock file, if exists delete read file and abort. Writer: Check for read lock file, create write lock file, check for read lock file, if exists delete write lock file and abort. This will stop your processes trampling on each other but a potential race condition may occur in that the you could potentially have both processes check, create then recheck simultaneously though this will not cause the data to be read in an inconsistent state but will cause both read and write processes to abort for your specified delay
Thank you all for your answers. At last we managed to resolve our problem, not by using locking commands of the OS (because we were not sure they would propagate correctly to the OS of the NAS head), but by creating lock directories instead of lock files. Directory creation is an atomic operation, and returns an error value if the folder already exists. Therefore, we don't have to check the lock existence before acquiring it, both operations are made in a single step.
How can I synchronize two processes accessing a file on a NAS?
[ "", "c++", "concurrency", "synchronization", "mutex", "nas", "" ]
We have a table that looks roughly like this: ``` CREATE TABLE Lockers { UserID int NOT NULL PRIMARY KEY (foreign key), LockerStyleID int (foreign key), NameplateID int (foreign key) } ``` All of the keys relate to other tables, but because of the way the application is distributed, it's easier for us to pass along IDs as parameters. So we'd like to do this: ``` Locker l = new Locker { UserID = userID, LockerStyleID = lockerStyleID, NameplateID = nameplateID }; entities.AddLocker(l); ``` We could do it in LINQ-to-SQL, but not EF?
This missing feature seems to annoy a lot of people. * Good news: MS will address the issue with .NET 4.0. * Bad news: for now, or if you're stuck on 3.5 you have to do a little bit of work, but it IS possible. You have to do it like this: ``` Locker locker = new Locker(); locker.UserReference.EntityKey = new System.Data.EntityKey("entities.User", "ID", userID); locker.LockerStyleReference.EntityKey = new EntityKey("entities.LockerStyle", "ID", lockerStyleID); locker.NameplateReference.EntityKey = new EntityKey("entities.Nameplate", "ID", nameplateID); entities.AddLocker(locker); entities.SaveChanges(); ```
What I've been doing to make things easy is adding the foreign key property myself in the partial class: ``` public int UserID { get { if (this.User != null) return this.User.UserID; } set { this.UserReference.EntityKey = new System.Data.EntityKey("entities.User", "ID", value); } } ```
Entity Framework: Setting a Foreign Key Property
[ "", "c#", "ado.net-entity-data-model", "" ]
I am having a similar issue to [this person](https://stackoverflow.com/questions/28387/sql-server-2k5-memory-consumption). The primary difference being the application is NOT meant for a developer environment, and therefore I need to know how to optimize the space used by Sql Server (possibly per machine based on specs). I was intrigued by [Ricardo C's](https://stackoverflow.com/users/10795/ricardo-c) answer, particularly the following: > Extracted fromt he SQL Server > documentation: > > Maximum server memory (in MB) > > Specifies the maximum amount of memory SQL Server can allocate when it > starts and while it runs. This > configuration option can be set to a > specific value if you know there are > multiple applications running at the > same time as SQL Server and you want > to guarantee that these applications > have sufficient memory to run. If > these other applications, such as Web > or e-mail servers, request memory only > as needed, then do not set the option, > because SQL Server will release memory > to them as needed. **However, > applications often use whatever memory > is available when they start and do > not request more if needed**. If an > application that behaves in this > manner runs on the same computer at > the same time as SQL Server, set the > option to a value that guarantees that > the memory required by the application > is not allocated by SQL Server. My question is: how does an application request memory from the OS when it needs it? Is this something built into compilation or something managed by the developer? The two primary apps running on this machine are Sql Server and the (fairly heavyweight) C# application I'm developing, and I'm almost certain we didn't specifically do anything in the realm of asking the OS for memory. Is there a correct/necessary way to do this?
Some applications allocate a lot of memory at startup, and then run their own memory management system on it. This can be good for applications that have particular allocation patterns, and that feel they can do a better job than the more generic memory manager provided by the runtime system. Many games do this, since they often have a very good idea of how their memory usage pattern is going to look, and often are heavily optimized. The default/system allocator is general-purpose and not always fast enough. [Doom did this](http://doom.wikia.com/wiki/Zone_memory), and is fairly well-known for it and of course its code is available and widely discussed. In "managed" languages like C# I think this is very rare, and nothing you need to worry about.
It will depend on a few things - in particular the Operating System, and the language used. For instance, under MacOS Classic, it was impossible to have more memory allocated after startup - we used to have to go and modify how much memory was allocated using the Finder, and then restart the application. Those were the bad old days. Modern operating systems will allow for running processes to request more memory - for instance in C, you can use alloc(), malloc(), realloc() or similar to request chunks of memory. In dynamic languages, you just create objects or variables, and more memory is allocated. In java, there is a limit as to how much memory the JVM has access to - and this can be changed by only restarting the JVM, and passing some arguments to it (sounds like the bad old days, doesn't it?). In Objective-C, in addition to the malloc() family of functions, you can also create objects on the heap, using ``` [object alloc]; ``` which is more often seen as ``` [[object alloc] init]; ``` Note that this is slightly different to creating objects on the stack - if you are serious about programming learning the difference between these two might be useful, too :) In summary - the programmer needs to ask the OS for more memory. This can be implicit (in dynamic languages, by creating objects, or by creating objects on the heap) or explicitly, such as in C by using alloc()/malloc()/etc.
Requesting memory for your application
[ "", "c#", "sql-server-2005", "memory-management", "" ]
In C#, what makes a field different from a property, and when should a field be used instead of a property?
Properties expose fields. Fields should (almost always) be kept private to a class and accessed via get and set properties. Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class. ``` public class MyClass { // this is a field. It is private to your class and stores the actual data. private string _myField; // this is a property. When accessed it uses the underlying field, // but only exposes the contract, which will not be affected by the underlying field public string MyProperty { get { return _myField; } set { _myField = value; } } // This is an AutoProperty (C# 3.0 and higher) - which is a shorthand syntax // used to generate a private field for you public int AnotherProperty { get; set; } } ``` @Kent points out that Properties are not required to encapsulate fields, they could do a calculation on other fields, or serve other purposes. @GSS points out that you can also do other logic, such as validation, when a property is accessed, another useful feature.
Object orientated programming principles say that, the internal workings of a class should be hidden from the outside world. If you expose a field you're in essence exposing the internal implementation of the class. Therefore we wrap fields with Properties (or methods in Java's case) to give us the ability to change the implementation without breaking code depending on us. Seeing as we can put logic in the Property also allows us to perform validation logic etc if we need it. C# 3 has the possibly confusing notion of autoproperties. This allows us to simply define the Property and the C#3 compiler will generate the private field for us. ``` public class Person { private string _name; public string Name { get { return _name; } set { _name = value; } } public int Age{get;set;} //AutoProperty generates private field for us } ```
What is the difference between a field and a property?
[ "", "c#", "oop", "properties", "field", "" ]
I'm trying to convert an Enum array to an int array: ``` public enum TestEnum { Item1, Item2 } int[] result = Array.ConvertAll<TestEnum, int>(enumArray, new Converter<TestEnum, int>(Convert.ToInt32)); ``` For some reason Convert.ToInt32 doesn't work when used in Array.ConvertAll, so I had to make some changes: ``` int[] result = Array.ConvertAll<TestEnum, int>(enumArray, new Converter<TestEnum, int>(ConvertTestEnumToInt)); public static int ConvertTestEnumToInt(TestEnum te) { return (int)te; } ``` Just out of curiosity, is there any way to have this working without using an extra method? Regards
Just cast using an anonymous method: ``` int[] result = Array.ConvertAll<TestEnum, int>( enumArray, delegate(TestEnum value) {return (int) value;}); ``` or with C# 3.0, a lambda: ``` int[] result = Array.ConvertAll(enumArray, value => (int) value); ```
Luckily for us, C# 3.0 includes a `Cast` operation: ``` int[] result = enumArray.Cast<int>().ToArray(); ``` If you stop using arrays and start using `IEnumerable<>`, you can even get rid of the `ToArray()` call.
Convert an array of 'enum' to an array of 'int'
[ "", "c#", ".net", "" ]
I often find myself writing a property that is evaluated lazily. Something like: ``` if (backingField == null) backingField = SomeOperation(); return backingField; ``` It is not much code, but it does get repeated a lot if you have a lot of properties. I am thinking about defining a class called LazyProperty: ``` public class LazyProperty<T> { private readonly Func<T> getter; public LazyProperty(Func<T> getter) { this.getter = getter; } private bool loaded = false; private T propertyValue; public T Value { get { if (!loaded) { propertyValue = getter(); loaded = true; } return propertyValue; } } public static implicit operator T(LazyProperty<T> rhs) { return rhs.Value; } } ``` This would enable me to initialize a field like this: ``` first = new LazyProperty<HeavyObject>(() => new HeavyObject { MyProperty = Value }); ``` And then the body of the property could be reduced to: ``` public HeavyObject First { get { return first; } } ``` This would be used by most of the company, since it would go into a common class library shared by most of our products. I cannot decide whether this is a good idea or not. I think the solutions has some pros, like: * Less code * Prettier code On the downside, it would be harder to look at the code and determine exactly what happens - especially if a developer is not familiar with the LazyProperty class. What do you think ? Is this a good idea or should I abandon it ? Also, is the implicit operator a good idea, or would you prefer to use the Value property explicitly if you should be using this class ? Opinions and suggestions are welcomed :-)
Just to be overly pedantic: Your proposed solution to avoid repeating code: ``` private LazyProperty<HeavyObject> first = new LazyProperty<HeavyObject>(() => new HeavyObject { MyProperty = Value }); public HeavyObject First { get { return first; } } ``` Is actually more characters than the code that you did not want to repeat: ``` private HeavyObject first; public HeavyObject First { get { if (first == null) first = new HeavyObject { MyProperty = Value }; return first; } } ``` Apart from that, I think that the implicit cast made the code very hard to understand. I would not have guessed that a method that simply returns first, actually end up creating a HeavyObject. I would at least have dropped the implicit conversion and returned first.Value from the property.
**Don't do it at all.** Generally using this kind of lazy initialized properties is a valid design choice in one case: when `SomeOperation();` is an expensive operation (in terms of I/O, like when it requires a DB hit, or computationally) AND when you are certain you will often NOT need to access it. That said, by default you should go for eager initialization, and when profiler says it's your bottleneck, then change it to lazy initialization. If you feel urge to create that kind of abstraction, it's a smell.
Implementing a "LazyProperty" class - is this a good idea?
[ "", "c#", ".net", "lazy-evaluation", "" ]
I intend to develop a small (Java) application for managing my finances. I believe I need to use an embedded database, but I have no experience regarding this issue. I tried to look at [some of the available products](http://java-source.net/open-source/database-engines), but I can't decide which one would be more suitable for me. [H2](http://www.h2database.com/), [HSQLDB](http://hsqldb.org/), [Derby](http://db.apache.org/derby/) and [Berkeley DB](http://www.oracle.com/technology/products/berkeley-db/je/index.html) seem to be good candidates, but I still don't see how they compare to each other. I appreciate your help comparing them and helping me decide which one to use. I intend to use Hibernate for my application (unless you would recommend using DBMS-provided API), but I also want to have the ability to edit the database easily using a SQL browsing tool (modifying schema and changing data). Thank you.
Either * [HSQLDB](http://hsqldb.org/) - Used by OpenOffice, tested and stable. It's easy to use. If you want to edit your db-data, you can just open the file and edit the insert statements. or * [H2](http://www.h2database.com/html/main.html) - Said to be faster (by the developer, who originally designed hsqldb, too) Which one you use is up to you, depending how much performance and how much stability you need. The developer of H2 has put up a nice performance evaluation: <http://www.h2database.com/html/performance.html>
I use [Apache Derby](http://db.apache.org/derby/) for pretty much all of my embedded database needs. You can also use Sun's Java DB that is based on Derby but the latest version of Derby is much newer. It supports a lot of options that commercial, native databases support but is much smaller and easier to embed. I've had some database tables with more than a million records with no issues. I used to use HSQLDB and Hypersonic about 3 years ago. It has some major performance issues at the time and I switch to Derby from it because of those issues. Derby has been solid even when it was in incubator at Apache.
Java Embedded Databases Comparison
[ "", "java", "database", "comparison", "embedded-database", "" ]
I'm reading a [post](http://savoysoftware.com/blog/?p=114) about iPhone programming and I've noticed that the talk about Objective C++, the code shown in the post looks mainly like Objective-C but there also are several snippets in C++. Is it really possible to program Cocoa from C++?
In addition to the other comments, I would add that Objective-C++ is not exactly the same as "program Cocoa from C++" because there is no C++ to Cocoa bridge involved. In Objective-C++, you program the Cocoa API entirely with Objective-C objects/syntax. The Cocoa API remains unchanged, so you need to communicate with it in the same way (using Objective-C strings, Objective-C arrays and Objective-C objects). The difference with Objective-C++, compared to plain Objective-C, is that you can *also* use C++ objects (containing Objective-C objects, contained by Objective-C objects or just along-side Objective-C objects).
Yes. Basically, Objective-C is a set of Smalltalk like object extensions to C. Objective C++ is the result of applying those same extensions to C++. This leaves you with a language with two different object models. Apple's xcode development environment provides both an Objective-C and Objective-C++ compiler.
There is really something like Objective C++?
[ "", "c++", "objective-c", "cocoa", "macos", "objective-c++", "" ]
Some time ago I wrote a little piece of code to ask about on interviews and see how people understand concepts of cache and memory: ``` #include "stdafx.h" #include <stdlib.h> #include <windows.h> #include <iostream> #define TOTAL 0x20000000 using namespace std; __int64 count(int INNER, int OUTER) { int a = 0; int* arr = (int*) HeapAlloc(GetProcessHeap(), 0, INNER * sizeof(int)); if (!arr) { cerr << "HeapAlloc failed\n"; return 1; } LARGE_INTEGER freq; LARGE_INTEGER startTime, endTime; __int64 elapsedTime, elapsedMilliseconds; QueryPerformanceFrequency(&freq); QueryPerformanceCounter(&startTime); /* Начало работы */ for (int i = 0; i < OUTER; i++) { for (int j = 0; j < INNER; j++) { a |= i; arr[j] = a; } } /* Конец работы */ QueryPerformanceCounter(&endTime); elapsedTime = endTime.QuadPart - startTime.QuadPart; elapsedMilliseconds = (1000 * elapsedTime) / freq.QuadPart; HeapFree(GetProcessHeap(), 0, arr); return elapsedMilliseconds; } int _tmain(int argc, _TCHAR* argv[]) { __int64 time; for (int INNER = 0x10; INNER <= 0x2000000; INNER <<= 1) { int OUTER = TOTAL / INNER; time = count(INNER, OUTER); cout << INNER << "\t" << OUTER << "\t" << time << "\n"; } } ``` That's what it compiles to (the loop itself): ``` 00401062 xor ecx,ecx 00401064 test ebp,ebp 00401066 jle count+83h (401083h) 00401068 xor eax,eax 0040106A test ebx,ebx 0040106C jle count+7Ch (40107Ch) 0040106E mov edi,edi 00401070 or esi,ecx 00401072 mov dword ptr [edi+eax*4],esi 00401075 add eax,1 00401078 cmp eax,ebx 0040107A jl count+70h (401070h) 0040107C add ecx,1 0040107F cmp ecx,ebp 00401081 jl count+68h (401068h) ``` That's what the program outputs on my machine: --- ``` LOG2(INNER) LOG2(OUTER) Time, ms 4 25 523 5 24 569 6 23 441 7 22 400 8 21 367 9 20 358 10 19 349 11 18 364 12 17 378 13 16 384 14 15 357 15 14 377 16 13 379 17 12 390 18 11 386 19 10 419 20 9 995 21 8 1,015 22 7 1,038 23 6 1,071 24 5 1,082 25 4 1,119 ``` --- I ask people to explain what's going on. As inner array grows, the number of cycles decreases, as the time does. As inner array outgrows the cache, cache misses begin to happen and time raises. It's all right so far. **BUT**: when the INNER array size is 16 (that gives us 64 bytes of data), there is little performance **boost**, despite the greater number of `jmps` in code. It's little (523 vs. 569), but reproducible. **The question is**: why this boost?
Probably because 64 is the cache line size on your machine, and you basically run each iteration fully out of a single cache line.
I'm not sure what you're asking. Are you just checking what we know? Why bother? Or are you asking us because you can't explain the boost at 64bytes yourself? Or is it to find out if this is a good interview question, or...? Anyway, If the intention is simply to provide a background for your interview question, you should remove all unnecessary code. Is HeapAlloc important? Why couldn't the array be declared on the stack? Or with new/malloc? Why do you need to do error handling in this little test program? Again, it just distracts and adds more noise. The same goes for the QPC calls. And I won't even ask why you need a precompiled header in this. In order to ask the interviewee about a 6-line loop, he has to sift through 16 lines of irrelevant noise. Why? And as mentioned in a comment, the output table is basically unreadable. I'm all for seeing if an interviewee can read code, but I don't see the point making a question about performance and cache characteristics so hard to read. In any case, at 64-byte, one INNER array fits exactly into most CPU's cache lines. Which means that exactly one cache line has to be read for each iteration of OUTER.
Cache, loops and performance
[ "", "c++", "performance", "memory", "caching", "" ]
I'm looking to use: ``` #define ``` and ``` #if ``` to allow me to simulate potentially absent hardware during unit tests. What are the rules for using the `#define` statements? i.e. what is its default scope? can I change the scope of the directive?
As Chris said, the scope of #define is just the file. (It's worth noting that this isn't the same as "the class" - if you have a partial type, it may consist of two files, one of which has symbol defined and one of which doesn't! You can also define a symbol project-wide, but that's done with [project properties](http://msdn.microsoft.com/en-us/library/c7f8bfy4.aspx) or a [compiler switch](http://msdn.microsoft.com/en-us/library/0feaad6z.aspx) rather than being specified in source code.
From [MSDN](http://msdn.microsoft.com/en-us/library/yt3yck0x(VS.71).aspx), its scope is the file
c# Pre-processor directive scope
[ "", "c#", "scope", "c-preprocessor", "preprocessor-directive", "" ]
How would I get the last item (or any specific item for that matter) in a simplexml object? Assume you don't know how many nodes there will be. ex. ``` <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="/xsl.xml"?> <obj href="http://xml.foo.com/" display="com.foo.bar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://obix.org/ns/schema/1.0" > <list name="data" of="HistoryRecord"> <obj> <abstime name="timestamp" val="1876-11-10T00:00:00-08:00"></abstime> <int name="energy_in_kwh" val="1234"></int> <int name="energy_out_kwh" val="123456"></int> </obj> <obj> <abstime name="timestamp" val="1876-11-10T00:15:00-08:00"></abstime> <int name="energy_in_kwh" val="1335"></int> <int name="energy_out_kwh" val="443321"></int> </obj> </list> <int name="count" val="2"></int> </obj> ``` And I want to grab the last `<obj></obj>` chunk (or even just part of it).
Use XPath's `last()` function, which solves this very problem: ``` <?php $xml = simplexml_load_file('HistoryRecord.xml'); $xml->registerXPathNamespace('o', 'http://obix.org/ns/schema/1.0'); $xpath = "/o:obj/o:list/o:obj[last()]/o:int[@name = 'energy_in_kwh']"; $last_kwh = $xml->xpath($xpath); ?> ``` Here it looks for the last inner `<obj>`, and therein for the `<int>` with the name of `"energy_in_kwh"`. Watch out for the namespace registration. (All your elements are part of the `"http://obix.org/ns/schema/1.0"` namespace, the XPath query must reflect that. --- EDIT: Note that `[last()]` is equivalent to `[position() = last()]`.
There is a XPath expression that'll do exactly what you want: ``` $xml='<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="/xsl.xml"?> <obj href="http://xml.foo.com/" display="com.foo.bar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://obix.org/ns/schema/1.0" > <list name="data" of="HistoryRecord"> <obj> <abstime name="timestamp" val="1876-11-10T00:00:00-08:00"></abstime> <int name="energy_in_kwh" val="1234"></int> <int name="energy_out_kwh" val="123456"></int> </obj> <obj> <abstime name="timestamp" val="1876-11-10T00:15:00-08:00"></abstime> <int name="energy_in_kwh" val="1335"></int> <int name="energy_out_kwh" val="443321"></int> </obj> </list> <int name="count" val="2"></int> </obj>'; $x=simplexml_load_string($xml); $x->registerXPathNamespace('obix', 'http://obix.org/ns/schema/1.0'); $objects=$x->xpath('/obix:obj/obix:list/obix:obj[last()]'); print_r($objects); ``` For example `/bookstore/book[last()]` will select the last book element that is the child of the bookstore element.
PHP SimpleXML. How to get the last item?
[ "", "php", "xml", "simplexml", "" ]
I need to set the properties of a class using reflection. I have a `Dictionary<string,string>` with property names and string values. Inside a reflection loop, I need to convert the string value to the appropriate property type while setting the value for each property. Some of these property types are nullable types. 1. How can I know from PropertyInfo if the property is a nullable type? 2. How can I set a nullable type using reflection? **edit:** The first method defined in the comments on this blog seems to do the trick as well: <http://weblogs.asp.net/pjohnson/archive/2006/02/07/437631.aspx>
1. One way to do this is: ``` type.GetGenericTypeDefinition() == typeof(Nullable<>) ``` 2. Just set is as per any other reflection code: ``` propertyInfo.SetValue(yourObject, yourValue); ```
Why do you need to know if it is nullable? And do you mean "reference-type", or "`Nullable<T>`"? Either way, with string values, the easiest option would be via the `TypeConverter`, which is more-easily (and more accurately) available on `PropertyDescriptor`: ``` PropertyDescriptorCollection props = TypeDescriptor.GetProperties(obj); // then per property... PropertyDescriptor prop = props[propName]; prop.SetValue(obj, prop.Converter.ConvertFromInvariantString(value)); ``` This should use the correct converter, even if set per-property (rather than per-type). Finally, if you are doing lots of this, this allows for acceleration via [`HyperDescriptor`](http://www.codeproject.com/KB/cs/HyperPropertyDescriptor.aspx), without changing the code (other than to enable it for the type, done once only).
how to set nullable type via reflection code ( c#)?
[ "", "c#", "reflection", "" ]
I have a method in a C++ interface that I want to deprecate, with portable code. When I Googled for this all I got was a Microsoft specific solution; [`#pragma deprecated`](https://learn.microsoft.com/en-us/cpp/preprocessor/deprecated-c-cpp?view=vs-2017) and [`__declspec(deprecated)`](https://learn.microsoft.com/en-us/cpp/cpp/deprecated-cpp?view=vs-2017). If a general or fully-portable deprecation solution is not available, I will accept as a "second prize solution" one that can be used multiple specific compilers, like MSVC and a GCC.
In C++14, you can mark a function as deprecated using the `[[deprecated]]` attribute (see section 7.6.5 [dcl.attr.deprecated]). > The *attribute-token* `deprecated` can be used to mark names and entities whose use is still allowed, but is discouraged for some reason. For example, the following function `foo` is deprecated: ``` [[deprecated]] void foo(int); ``` It is possible to provide a message that describes why the name or entity was deprecated: ``` [[deprecated("Replaced by bar, which has an improved interface")]] void foo(int); ``` The message must be a string literal. For further details, see [“Marking as deprecated in C++14”](http://josephmansfield.uk/articles/marking-deprecated-c++14.html).
This should do the trick: ``` #ifdef __GNUC__ #define DEPRECATED(func) func __attribute__ ((deprecated)) #elif defined(_MSC_VER) #define DEPRECATED(func) __declspec(deprecated) func #else #pragma message("WARNING: You need to implement DEPRECATED for this compiler") #define DEPRECATED(func) func #endif ... //don't use me any more DEPRECATED(void OldFunc(int a, float b)); //use me instead void NewFunc(int a, double b); ``` However, you will encounter problems if a function return type has a commas in its name e.g. `std::pair<int, int>` as this will be interpreted by the preprocesor as passing 2 arguments to the DEPRECATED macro. In that case you would have to typedef the return type. Edit: simpler (but possibly less widely compatible) version [here](https://stackoverflow.com/a/21265197/2651243).
How can I mark a C++ class method as deprecated?
[ "", "c++", "deprecated", "portability", "" ]
We're using RSpec and Cucumber in our Rails apps with good results. Webrat is great for non-AJAX interactions, but we're getting ready to get back into writing tests for our Javascript. Webrat has Selenium support built in, and we've used Selenium before, but I'm curious if anyone has had good results using Watir with Cucumber and what the pros and cons are of Watir versus Selenium.
As the founder of OpenQA and Selenium RC, I'm obviously biased towards Selenium as a good option. We recently just put out a 1.0 beta 2 release and are very close to a 1.0 final. However, you couldn't go wrong with Watir/FireWatir either. Adam's comment that WebDriver will merge to form Selenium 2.0 is correct, but he's incorrect in implying that Watir doesn't use native hooks. If Watir were simply a Selenium clone and also used JavaScript injection, I'd say it wasn't worth looking at. But because it has native hooks, it can do some things that Selenium currently can't. While it has fewer browsers supported, it goes a bit deeper in the main browser it does support (IE) and lets you control things outside of the page/canvas. In summary: either is fine, Selenium is great, and if you hang on a little longer with Selenium you'll soon get the best of both worlds with WebDriver/Selenium 2.0.
I am having good results using Cucumber with Celerity through JRuby. Celerity is a headless browser which wraps around HtmlUnit with a Watir-compatible API and supports JavaScript and AJAX testing. Being headless makes Celerity faster and easy to integrate within a Continuous Integration build cycle. Since Celerity is API-compatible with Watir, you can switch between Watir and Celerity fairly easily. There are some caveats, but it's been worth the effort.
Selenium or Watir for Javascript Testing in Rails
[ "", "javascript", "ruby-on-rails", "ajax", "testing", "selenium", "" ]
I have this method Verify\_X which is called during databind for a listbox selected value. The problem is the strongly typed datasource. I want to use the abstract class BaseDataSource or an interface to call the methods supported: Parameters[] and Select(), Instead of using the most specific implementation as seen below. This is so one method can be used for all the different types of datasources I have instead of having a method for each. They all inherit the same way. Here is the chain of inheritance / implementation ``` public class DseDataSource : ProviderDataSource<SCCS.BLL.Dse, DseKey> public abstract class ProviderDataSource<Entity, EntityKey> : BaseDataSource<Entity, EntityKey>, ILinkedDataSource, IListDataSource where Entity : SCCS.BLL.IEntityId<EntityKey>, new() where EntityKey : SCCS.BLL.IEntityKey, new() public abstract class BaseDataSource<Entity, EntityKey> : DataSourceControl, IListDataSource, IDataSourceEvents where Entity : new() where EntityKey : new() ``` The BaseDataSource has the methods and properties I need. DseDataSource is implemented the following way: ``` public class DseDataSource : ProviderDataSource<SCCS.BLL.Dse, DseKey> ``` I know it is possible to edit the class DseDataSource, add an interface to access Parameters[] and Select(), then program against that, which allows what I want, but this requires editing the NetTiers libraries and I am curious to see if this can be done since it seemed so difficult. ``` public static string Verify_DSE(string valueToBind, DseDataSource dataSource) { if (ListContainsValue(dataSource.GetEntityList(), valueToBind)) return valueToBind; CustomParameter p = dataSource.Parameters["WhereClause"] as CustomParameter; if (p != null) { p.Value = "IsActive=true OR Id=" + valueToBind; dataSource.Select(); return valueToBind; } return string.Empty; } private static bool ListContainsValue(IEnumerable list, string value) { if (value.Length == 0) return true; foreach (object o in list) { IEntity entity = o as IEntity; if (entity != null) { if (entity.Id.ToString() == value) return true; } } return false; } ``` The end result would be code such as: ``` public static string Verify(string valueToBind, object dataSource) { //what is the correct way to convert from object BaseDataSource baseInstance = dataSource as BaseDataSource; if baseInstance != null) { if (ListContainsValue(baseInstance.GetEntityList(), valueToBind)) return valueToBind; CustomParameter p = baseInstance.Parameters["WhereClause"] as CustomParameter; if (p != null) { p.Value = "IsActive=true OR Id=" + valueToBind; baseInstance.Select(); return valueToBind; } } return string.Empty; } ```
If you are unable to alter the class definition or to use some sort of extension methods, you can use Reflection. Here is a sample that I worked up using assumptions about your code: ``` public static string Verify(string valueToBind, object dataSource) { ////what is the correct way to convert from object //BaseDataSource baseInstance = dataSource as BaseDataSource; Type type = dataSource.GetType(); MethodInfo select = type.GetMethod("Select"); PropertyInfo parameters = type.GetProperty("Parameters"); PropertyInfo parameterGetter = null; object parametersInstance = null; if (parameters != null) { parametersInstance = parameters.GetValue(dataSource, null); type = parametersInstance.GetType(); parameterGetter = type.GetProperty("Item"); } //if baseInstance != null) if (select != null && parameters != null && parameterGetter != null) { if (ListContainsValue(baseInstance.GetEntityList(), valueToBind)) return valueToBind; CustomParameter p = parameterGetter.GetValue(parametersInstance, new object[] {"WhereClause" }) as CustomParameter; if (p != null) { p.Value = "IsActive=true OR Id=" + valueToBind; select.Invoke(dataSource, null); return valueToBind; } } return string.Empty; } ```
Thanks John you really put me on the right path there. I ended up with the following code: ``` public string Verify(string valueToBind, object dataSource) { IListDataSource listDataSource = dataSource as IListDataSource; if (listDataSource != null) { if (ListContainsValue(listDataSource.GetEntityList(), valueToBind)) return valueToBind; } Type type = dataSource.GetType(); MethodInfo select = type.GetMethod("Select", new Type[0]); PropertyInfo parameterCollectionInfo = type.GetProperty("Parameters"); ParameterCollection pc = parameterCollectionInfo.GetValue(dataSource, null) as ParameterCollection; if (pc != null) { CustomParameter p = pc["WhereClause"] as CustomParameter; if (p != null) { p.Value = "IsActive=true OR Id=" + valueToBind; select.Invoke(dataSource, null); return valueToBind; } } return string.Empty; } ```
Casting to abstract class or interface when generics are used
[ "", "c#", "reflection", "casting", "abstract-class", "generics", "" ]
My comfort level with java is good , I wanted to teach my friend C# (where I would not consider myself expert in anyway). From the perspective of interviews what should I be studying/implementing myself in C# before i can teach her from an interview perspective. I am not a big fan of a language specific interviews but then my friend has little programming experience. EDIT:What are the most important aspects of the C# language that you would recommend studying for an interview.
I tend to take the view that the things you should know for an interview are the things you need to know for core development - at least if the interviewer is any good. So, for C# I would make sure you're comfortable with: * Properties * Reference types vs value types * Parameter passing (what ref means etc) * Generics (quite different to Java) * Delegates and events * "using" statements * Exception handling Slightly more involved: * Nullable value types * Partial types * Iterator blocks (these are fun to play with) If you feel like tackling C# 3: * Lambda expressions * Extension methods * Basic grasp of how query expressions are processed (i.e. syntactic sugar; details not as important) * Object and collection initializers
Well, firstly I'd try to avoid mistakes due confusion with java concepts (since you're from a java background). For example: * int/Int32 (etc): in C# they are the same * generics: how they differ from java * delegates/events: don't exist in java * closures: java captures the *value*; C# captures the *variable* (allowing updates) * structs, how they work, and why you very rarely need them ;-p But C# is not a tiny language, and the .NET framework is huge. So there is a lot to cover...
How should I teach my friend C#?
[ "", "c#", "" ]
I need to get the version information of a DLL file I created in Visual Studio 2008 C++. How do I get it?
Thanks for the answers. This worked for me: ``` WCHAR fileName[_MAX_PATH]; DWORD size = GetModuleFileName(g_dllHandle, fileName, _MAX_PATH); fileName[size] = NULL; DWORD handle = 0; size = GetFileVersionInfoSize(fileName, &handle); BYTE* versionInfo = new BYTE[size]; if (!GetFileVersionInfo(fileName, handle, size, versionInfo)) { delete[] versionInfo; return; } // we have version information UINT len = 0; VS_FIXEDFILEINFO* vsfi = NULL; VerQueryValue(versionInfo, L"\\", (void**)&vsfi, &len); aVersion[0] = HIWORD(vsfi->dwFileVersionMS); aVersion[1] = LOWORD(vsfi->dwFileVersionMS); aVersion[2] = HIWORD(vsfi->dwFileVersionLS); aVersion[3] = LOWORD(vsfi->dwFileVersionLS); delete[] versionInfo; ```
If you want programmatic access, see [Version Information](http://msdn.microsoft.com/en-us/library/ms646981(VS.85).aspx) in MSDN for the APIs and data structures you need.
How to get the version information of a DLL file in C++
[ "", "c++", "windows", "dll", "version", "" ]
String's in C# are immutable and threadsafe. But what when you have a public getter property? Like this: ``` public String SampleProperty{ get; private set; } ``` If we have two threads and the first is calling 'get' and the second is calling 'set' at the "same" time, what will happen? IMHO the set must made a lock to be thread-safe like this: ``` private string sampleField; private object threadSafer = new object(); public String SampleProperty{ get{ return this.sampleField; } private set{ lock(threadSafer){ sampleField = value; } } } ```
Most of the answers are using the word "atomic" as if atomic changes are all that are needed. They're not, usually. This has been mentioned in the comments, but not usually in the answers - that's the only reason for me providing this answer. (The point about locking at a coarser granularity, to allow things like appending, is entirely valid as well.) Usually you want a reading thread to see the *latest* value of the variable/property. That [isn't guaranteed by atomicity](http://pobox.com/~skeet/csharp/threads/volatility.shtml). As a quick example, here's a *bad* way to stop a thread: ``` class BackgroundTaskDemo { private bool stopping = false; static void Main() { BackgroundTaskDemo demo = new BackgroundTaskDemo(); new Thread(demo.DoWork).Start(); Thread.Sleep(5000); demo.stopping = true; } static void DoWork() { while (!stopping) { // Do something here } } } ``` `DoWork` may well loop forever, despite the write to the boolean variable being atomic - there's nothing to stop the JIT from caching the value of `stopping` in `DoWork`. To fix this, you either need to lock, make the variable `volatile` or use an explicit memory barrier. This all applies to string properties as well.
A reference-type field's get/set (ldfld/stfld) is (IIRC) guaranteed to be atomic, so there shouldn't be any risk of corruption here. So it should be thread-safe from **that** angle, but personally I'd lock the data at a higher level - i.e. ``` lock(someExternalLock) { record.Foo = "Bar"; } ``` or maybe: ``` lock(record.SyncLock) { record.Foo = "Bar"; } ``` This allows you to make multiple reads/updates to the same **object** as an atomic operation, so that other threads can't get an invalid object-state
Is a string property itself threadsafe?
[ "", "c#", "multithreading", "" ]
The if keyword in the following statement is underlined in green by ReSharper: ``` if (readOnlyFields.Contains(propertyName)) return false; return base.CanWriteProperty(propertyName); ``` ReSharper suggests the following change: ``` return !readOnlyFields.Contains(propertyName) && base.CanWriteProperty(propertyName); ``` Why is this "better"? I find the current code more readable and the result should be the same as far as I know. Any thoughts?
Neither one is better in the sense that either one will perform better than the other. (Any difference is going to be entirely negligible.) Certain coding conventions suggest that you use one return statement per function so that it's easy to understand it's flow. It's not a hard and fast rule though and in this case it's pretty obvious what's going on. If you don't like it's suggestion but you would like to ensure that your code is easily read by others I'd suggest the following: ``` if (readOnlyFields.Contains(propertyName)) return false; else return base.CanWriteProperty(propertyName); ``` But your way is fine too.
On the quick fix menu (Alt+Enter), there's a "Correction options" (or something like that). You can turn this specific suggestion into a hint, or turn it off entirely. On a personal note, I prefer your original over ReSharper's suggestion.
ReSharper syntax suggestion
[ "", "c#", "visual-studio-2008", "syntax", "resharper", "" ]
Why does the following code NOT give an error, nor any type of a warning about an implicit conversion? ``` std::wstring str = L"hi"; if(str[0] == 'h') cout<<"strange"<<endl; ``` The proper normal code is: ``` std::wstring str = L"hi"; if(str[0] == L'h') cout<<"strange"<<endl; ``` Compiler: visual studio 2005 Warning level: level 4 (highest)
It doesn't give a warning because the comparison is valid. In general, you can always compare integral types, they just get promoted to wider types as needed. And I'm pretty sure some compilers would issue a warning about this. Which one are you using? (In any case, warnings are compiler-specific, and they're not required to warn about this or anything else)
> Why does the following code NOT give an error ... Isn't it because C++ allows implicit conversions? For example, isn't the following also legal: ``` if (str[0] == 104) //C++ allows various implicit type conversions ``` > ... nor any type of a warning about an implicit conversion? That question is compiler-specific: which compiler are you using? There's probably a compiler option that affects what types of warnings you get from the compiler.
unicode char comparing to non unicode char, but no warning nor error
[ "", "c++", "string", "unicode", "" ]
**Closed as exact duplicate of [this question](https://stackoverflow.com/questions/228164/on-design-patterns-when-to-use-the-singleton). But reopened, as the other Singleton questions are for general use and not use for DB access** I was thinking of making an internal data access class a Singleton but couldn't convince myself on the choice mainly because the class has no state except for local variables in its methods. What is the purpose of designing such classes to be Singletons after all? Is it warranting sequential access to the database which is not convincing since most modern databases could handle concurrency well? Is it the ability to use a single connection repeatedly which could be taken care of through connection pooling? Or Is it saving memory by running a single instance? Please enlighten me on this one.
I've found that the singleton pattern is appropriate for a class that: * Has no state * Is full of basic "Service Members" * Has to tightly control its resources. An example of this would be a data access class. You would have methods that take in parameters, and return say, a DataReader, but you don't manipulate the state of the reader in the singleton, You just get it, and return it. At the same time, you can take logic that could be spread among your project (for data access) and integrate it into a single class that manages its resources (database connections) properly, regardless of who is calling it. All that said, Singleton was invented prior to the .NET concept of fully static classes, so I am on the fence on if you should go one way or or the other. In fact, that is an excellent question to ask.
As one example, **object factories** are very often good candidates to be singletons.
In what circumstances should I use a Singleton class?
[ "", "c#", ".net", "design-patterns", "oop", "" ]
Just curious: * 4 instanceof Number => false * new Number(4) instanceof Number => true? Why is this? Same with strings: * `'some string' instanceof String` returns false * `new String('some string') instanceof String` => true * `String('some string') instanceof String` also returns false * `('some string').toString instanceof String` also returns false For object, array or function types the instanceof operator works as expected. I just don't know how to understand this. [**new insights**] ``` Object.prototype.is = function() { var test = arguments.length ? [].slice.call(arguments) : null ,self = this.constructor; return test ? !!(test.filter(function(a){return a === self}).length) : (this.constructor.name || (String(self).match ( /^function\s*([^\s(]+)/im ) || [0,'ANONYMOUS_CONSTRUCTOR']) [1] ); } // usage var Newclass = function(){}; // anonymous Constructor function var Some = function Some(){}; // named Constructor function (5).is(); //=> Number 'hello world'.is(); //=> String (new Newclass()).is(); //=> ANONYMOUS_CONSTRUCTOR (new Some()).is(); //=> Some /[a-z]/.is(); //=> RegExp '5'.is(Number); //=> false '5'.is(String); //=> true ```
`value instanceof Constructor` is the same as `Constructor.prototype.isPrototypeOf(value)` and both check the [[Prototype]]-chain of `value` for occurences of a specific object. Strings and numbers are **primitive values**, not objects and therefore don't have a [[Prototype]], so it'll only work if you wrap them in regular objects (called 'boxing' in Java). Also, as you noticed, `String(value)` and `new String(value)` do different things: If you call the constructor functions of the built-in types without using the `new` operator, they try to convert ('cast') the argument to the specific type. If you use the `new` operator, they create a wrapper object. `new String(value)` is roughly equivalent to `Object(String(value))`, which behaves the same way as `new Object(String(value))`. --- Some more on types in JavaScript: ECMA-262 defines the following primitive types: *Undefined*, *Null*, *Boolean*, *Number*, and *String*. Additionally, there is the type *Object* for things which have properties. For example, functions are of type *Object* (they just have a special property called [[Call]]), and `null` is a primitive value of type *Null*. This means that the result of the `typeof` operator doesn't really return the type of a value... Aditionally, JavaScript objects have another property called [[Class]]. You can get it via `Object.prototype.toString.call(value)` (this will return `'[object`*`Classname`*`]'`). Arrays and functions are of the type *Object*, but their classes are *Array* and *Function*. The test for an object's class given above works when `instanceof` fails (e.g. when objects are passed between window/frame boundaries and don't share the same prototypes). --- Also, you might want to check out this improved version of `typeof`: ``` function typeOf(value) { var type = typeof value; switch(type) { case 'object': return value === null ? 'null' : Object.prototype.toString.call(value). match(/^\[object (.*)\]$/)[1] case 'function': return 'Function'; default: return type; } } ``` For primitives, it will return their **type** in *lower case*, for objects, it will return their **class** in *title case*. **Examples:** * For primitives of **type** *Number* (eg `5`), it will return `'number'`, for wrapper objects of **class** *Number* (eg `new Number(5)`), it will return `'Number'`; * For functions, it will return `'Function'`. If you don't want to discern between primitive values and wrapper objects (for whatever, probably bad reason), use `typeOf(...).toLowerCase()`. Known bugs are some built-in functions in IE, which are considered `'Object'` and a return value of `'unknown'` when used with some COM+ objects.
You may try to evaluate: ``` >>> typeof("a") "string" >>> typeof(new String("a")) "object" >>> typeof(4) "number" >>> typeof(new Number(4)) "object" ```
Why is 4 not an instance of Number?
[ "", "javascript", "" ]
the two bits of SQL below get the same result ``` SELECT c.name, o.product FROM customer c, order o WHERE c.id = o.cust_id AND o.value = 150 SELECT c.name, o.product FROM customer c INNER JOIN order o on c.id = o.cust_id WHERE o.value = 150 ``` I've seen both styles used as standard at different companies. From what I've seen, the 2nd one is what most people recommend online. Is there any real reason for this other than style? Does using an Inner Join sometimes have better performance? I've noticed Ingres and Oracle developers tend to use the first style, whereas Microsoft SQL Server users have tended to use the second, but that might just be a coincidence. Thanks for any insight, I've wondered about this for a while. Edit: I've changed the title from 'SQL Inner Join versus Cartesian Product' as I was using the incorrect terminlogy. Thanks for all the responses so far.
Both queries are an inner joins and equivalent. The first is the older method of doing things, whereas the use of the JOIN syntax only became common after the introduction of the SQL-92 standard (I believe it's in the older definitions, just wasn't particularly widely used before then). The use of the JOIN syntax is strongly preferred as it separates the join logic from the filtering logic in the WHERE clause. Whilst the JOIN syntax is really syntactic sugar for inner joins it's strength lies with outer joins where the old \* syntax can produce situations where it is impossible to unambiguously describe the join and the interpretation is implementation-dependent. The [LEFT | RIGHT] JOIN syntax avoids these pitfalls, and hence for consistency the use of the JOIN clause is preferable in all circumstances. Note that neither of these two examples are Cartesian products. For that you'd use either ``` SELECT c.name, o.product FROM customer c, order o WHERE o.value = 150 ``` or ``` SELECT c.name, o.product FROM customer c CROSS JOIN order o WHERE o.value = 150 ```
To answer part of your question, I think early bugs in the JOIN ... ON syntax in Oracle discouraged Oracle users away from that syntax. I don't think there are any particular problems now. They are equivalent and should be parsed into the same internal representation for optimization.
SQL INNER JOIN syntax
[ "", "sql", "syntax", "inner-join", "cross-join", "" ]
Our java applet needs to open a new htm page to web browser but popup blocker seem to block this code: ``` try { AppletContext a = getAppletContext(); URL url = new URL(link); a.showDocument(url,"_blank"); } ``` can you use somehow live javascript to open a window instead?
`AppletContext` show document is implemented by doing the JavaScript call. However, the context the popup blocker is using will probably be absent. If the click happens outside of an applet you can use only JavaScript to open the popup, but using a URL supplied by the applet (so the applet never has to call out to JavaScript).
I'm probably not being helpful, but a popup blocker's task is to block popups. If there was a way to fool it, it would not be a good blocker after all. You will have to advise your users to disable the popup blocker to use your application.
Can Applet open a new HTML window *and* bypass popup blocker?
[ "", "java", "applet", "" ]
We have a static method in a utility class that will download a file from a URL. An authenticator has been set up so that if a username and password is required, the credentials can be retrieved. The problem is that the credentials from the first successful connection are used for every connection afterwords, as long as the credentials are valid. This is a problem because our code is multi user, and since the credentials are not checked for every connection, it's possible that a user without proper credentials could download a file. Here's the code we're using ``` private static URLAuthenticator auth; public static File download(String url, String username, String password, File newFile) { auth.set(username, password); Authenticator.setDefault(auth); URL fURL = new URL(url); OutputStream out = new BufferedOutputStream(new FileOutputStream(newFile)); URLConnection conn = fURL.openConnection(); InputStream in = conn.getInputStream(); try { copyStream(in, out); } finally { if (in != null) in.close(); if (out != null) out.close(); } return newFile; } public class URLAuthenticator extends Authenticator { private String username; private String password; public URLAuthenticator(String username, String password) { set(username, password); } public void set(String username, String password) { this.username = username; this.password = password; } protected PasswordAuthentication getPasswordAuthentication() { log.debug("Retrieving credentials '" + username + "', '" + password + "'."); return new PasswordAuthentication(username, password.toCharArray()); } } ``` I only see the log statement from getPasswordAuthentication once, the first time that a file is downloaded. After that first successful attempt, getPasswordAuthentication is not called again, even though the credentials have been reset. The result is that after the first successful connection, invalid credentials can be entered, and a successful connection can still be made. Is this possibly a result of the download method being static, and in a static class? **Edit** I forgot to mention that this is in a JSF webapp running under tomcat - maybe one of those technologies is setting some default credentials somewhere? I've pulled the URLAuthenticator out into its own class, and made it as non-static as possible, but the problem still exists. I've read that if the default authenticator is set to null with Authenticator.setDefault(null), then on windows the NTLM authentication will be used. That shouldn't be the problem here since I'm setting the Authenticator everytime, but I thought I'd throw it out there. The NTLM authentication is definately getting used, because if the server is run as a user that has access to the downloaded file, the credentials aren't even asked for, the file just downloads. So something obviously is grabbing my credentials and passing them in before the authenticator is called.
I've figured something out at least. It appears that this behavior is a [bug](https://bugs.java.com/bugdatabase/view_bug?bug_id=6626700). A workaround is to use a Sun specific class to explicitly reset the cache, like so: ``` import sun.net.www.protocol.http.AuthCacheValue; import sun.net.www.protocol.http.AuthCacheImpl; .... AuthCacheValue.setAuthCache(new AuthCacheImpl()); Authenticator.setDefault(new URLAuthenticator(username, password)); ``` I'm resetting the AuthCache at the top of the download function described in the question. During compile, you'll get warnings about using these classes. This doesn't completely fix the problem: if NTLM authentication works, the authenticator still won't get called, but as long as the server is running under a user that has does not have permission for the requested file, this should clear the cache out.
Facing the same problem, none of these answers worked for me. It took me some time and looking through the java runtime source to figure this out. Sun.net.www.protocol.http.ntlm.NTLMAuthentication attempts to use transparent authentication, what is basically use of current user credentials to login to remote server. In my server to server scenario (Java EE server to Sharepoint) this wasn't acceptable. In order to disable transparent authentication we need to let authentication provider know that connection is not trusted and it needs to authenticate with every call: ``` static { NTLMAuthenticationCallback.setNTLMAuthenticationCallback(new NTLMAuthenticationCallback() { @Override public boolean isTrustedSite(URL url) { return false; } }); } ```
Reset the Authenticator credentials
[ "", "java", "" ]
I am trying to pass a number to my JavaScript function, but actually a wrong value is getting passed. I am giving the entire code here: ``` <html> <head> <script type="text/javascript"> function test(num) { /*It should alert as 01004 or 1004 but to my surprise it's alerting as 516!*/ alert(num); } </script> </head> <body> <a href="javascript:test(01004);">Test it!</a> </body> </html> ``` In the above code, instead of 01004, if I pass it as 10040 I am getting the correct value in the alert box. Any idea about this strange case? Thanks in advance.
A numeric literal that starts with a zero is interpreted as octal, so writing 01004 is *exactly* the same as writing 516. Some other answers suggesting using parseInt inside the function to convert the octal value to decimal. This wont help, as the numeric value 516 is passed to the function. If you ask parseInt to give you a base 10 interpretation back, you'll get 516! The way to fix this is either to lose the leading zero, or if the zero is required, make it a string literal rather than a numeric, and use parseInt(num, 10) inside the function.
The leading zero is probably making it think the number is octal. UPDATE: Thanks to @Paul Dixon for jogging my mind awake somewhat this morning. `01004` is a literal, so no amount of after-the-fact parsing, i.e., `parseInt`, is going to update the base of the number. You need to either strip the leading `0` in your code to make it `1004` (the easiest solution), or put quotes around the literal to make it a string before sending it to `parseInt` (which is more work for no reason I can see).
JavaScript function parameter
[ "", "javascript", "function", "types", "parameters", "" ]
I have this P/Invoke RegSetValueExW that sets the value to the registry key. in C# ``` [DllImport("coredll.dll", EntryPoint = "RegSetValueExW")] public static extern int RegSetValueExW(uint hKey, string lpValueName, uint lpReserved, uint lpType, byte[] lpData, uint lpcbData); ``` I'm having a problem with the 4th param byte[] lpdata. I need to pass a DWORD with a value of 5 (int) in it. Everything is OK if I pass a string (REG\_SZ), just need to convert using the GetBytes function. If I call GetBytes("5") it converts it to ascii value of 53 so it writes 53 on the registry value instead of 5
I've got to start by asking why you are using PInvoke here when there is already a method for setting registry values in the Microsoft.Win32.RegistryKey class? Or are you stuck using an old version of the Compact Framework? Assuming you have a good reason for the PInvoke, the easiest answer is just to overload the PInvoke declaration for integer values. i.e.: ``` [DllImport("coredll.dll", EntryPoint = "RegSetValueExW")] public static extern int RegSetValueExW(uint hKey, string lpValueName, uint lpReserved, uint lpType, ref int lpData, uint lpcbData); ```
Use REG\_DWORD instead of REG\_SZ and then use BitConverter.GetBytes(Int32) to convert the int to a byte[].
How to pass a (byte[] lpData) with integer value to RegSetValueExW P/Invoke
[ "", "c#", "interop", "registry", "" ]
I have an image with two points, aligned something like this: ``` |----------------| | | | . | | | | . | | | |----------------| ``` I have both X, Y coordinates for both points and I need to rotate the image X degrees so it looks like this instead: ``` |----------------| | | | | | . . | | | | | |----------------| ``` Basically so they align next to eachother, what's the math for this? (A code example in C# would be even better but not required)
It depends on which point you want to use as a "center" for your rotation. Let's call the point to the up and left pointA and the one to the right and below pointB. If you want to rotate around the point A so that point B aligns with it, calculating the rotation angle in radians would go like this: ``` double angle = Math.Atan2(pointB.Y - pointA.Y, pointB.X - pointA.X); ``` I don't how you're handling your image, so the following applies only if you're using System.Drawing.Graphics: ``` myImage.TranslateTransform(-pointA.X, -pointA.Y); myImage.RotateTransform((float) angle, MatrixOrder.Append); myImage.TranslateTransform(pointA.X, pointA.Y, MatrixOrder.Append); ``` Hope it helps.
No code, sorry, but a stratagy. You need to be able to create the result image by sampling the the source image. You know the angle of rotation, so you now need to create a mapper function which maps from the result back to the original. The code would simply scan each row of the result image, and map the pixel back to the original image. You can do a simple; ``` for (int plotY = 0; plotY < resultHeight; plotY++) { for (int plotX = 0; plotX < resultWidth; plotX++) { resultImage.PlotPixel(getOriginalPixel(plotX, plotY, angleOfRotation)); } } ``` So now we just need the magical "getOriginalPixel" method, and this is where the maths comes in. If we rotate the image 0 degrees, then plotX, plotY is just the X/Y of the original image. But that's no fun. ``` pickX = x * cos(angle) - y * sin(angle) pickY = y * cos(angle) + x * sin(angle) ``` I think will map to the source pixel. You'll need to check if it's out of bounds and just return black or something :)
Rotate image math (C#)
[ "", "c#", "math", "image", "rotation", "" ]
I'm working on a multi-threaded Silverlight application. The application has two threads: Main/UI and a background working thread. The UI thread should be able to kill the background thread, like so: ``` private Thread executionThread; .... executionThread = new Thread(ExecuteStart); executionThread.Start(); .... executionThread.Abort(); // when the user clicks "Stop" ``` The last line raises an Exception: > MethodAccessException: Attempt to access the method failed: System.Threading.Thread.Abort() Any idea? why i cannot abort a thread in Silverlight? Thanks, Naimi
Rather than creating a Thread manually for this purpose you might want to consider using the [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker(VS.95).aspx) class. This class has built in functionality for cancelling the asynchronous operation when WorkerSupportsCancellation = true. Have a look at this article on MSDN for a [full example](http://msdn.microsoft.com/en-us/library/cc221403(VS.95).aspx) of how to use the BackgroundWorker in Silverlight.
It's documented, see [Thread.Abort()](http://msdn.microsoft.com/en-us/library/ty8d3wta(VS.95).aspx) > This member has a > SecurityCriticalAttribute attribute, > which restricts it to internal use by > the .NET Framework for Silverlight > class library. Application code that > uses this member throws a > MethodAccessException. You could use a [ManualResetEvent](http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent(VS.95).aspx) (a thread safe communication method) to signal the background thread to stop. Example code in the background thread: ``` if (!shouldStop.WaitOne(0)) // you could also sleep 5 seconds by using 5000, but still be stopped // after just 2 seconds by the other thread. { // do thread stuff } else { // do cleanup stuff and exit thread. } ```
Unable to kill a worker thread in Silverlight
[ "", "c#", ".net", "silverlight", "multithreading", "" ]
The median of five is sometimes used as an exercise in algorithm design and is known to be computable **using only 6 comparisons**. What is the best way to implement this **"median of five using 6 comparisons"** in C# ? All of my attempts seem to result in awkward code :( I need nice and readable code while still using only 6 comparisons. ``` public double medianOfFive(double a, double b, double c, double d, double e){ // // return median // return c; } ``` **Note:** I think I should provide the "algorithm" here too: I found myself not able to explain the algorithm clearly as *Azereal* did in his forum post. So I will reference his post here. From <http://www.ocf.berkeley.edu/~wwu/cgi-bin/yabb/YaBB.cgi?board=riddles_cs;action=display;num=1061827085> > Well I was posed this problem in one > of my assignments and I turned to this > forum for help but no help was here. > I eventually found out how to do it. > > 1. Start a mergesort with the first 4 elements and order each pair (2 > comparisons) > 2. Compare the two lower ones of each pair and eliminate the lowest one from > the possibilities (3 comparisons) > 3. Add in the 5th number set aside to the number without a pair and compare > the two (4 comparisons) > 4. Compare the two lowest of the two new pairs and eliminate the lower one > (5 comparisons) > 5. Compare the one by itself and the lower of the last pair and the lower > number is the median > > The possible median is within the > parentesis > > (54321) > > 5:4 3:2 2 comparisons > > (4<5 2<3 1) > > 4:2 3 comparisons > > 2(4<5 3 1) > > 1:3 4 comparisons > > 2(4<5 1<3) > > 4:1 5 comparisons > > 1,2(4<5 3) > > 4:3 6 comparisons > > 1,2(3)4,5 > > Three is the median Here is the C++ code I wrote to find median of five. Don't mind its awkwardness: ``` double StageGenerator::MedianOfFive(double n1, double n2, double n3, double n4, double n5){ double *a = &n1, *b = &n2, *c = &n3, *d = &n4, *e = &n5; double *tmp; // makes a < b and b < d if(*b < *a){ tmp = a; a = b; b = tmp; } if(*d < *c){ tmp = c; c = d; d = tmp; } // eleminate the lowest if(*c < *a){ tmp = b; b = d; d = tmp; c = a; } // gets e in a = e; // makes a < b and b < d if(*b < *a){ tmp = a; a = b; b = tmp; } // eliminate another lowest // remaing: a,b,d if(*a < *c){ tmp = b; b = d; d = tmp; a = c; } if(*d < *a) return *d; else return *a; } ``` It should be more compact, isn't it ? --- As @pablito pointed out in his answer, the built-in `List.Sort()` cannot fulfill this requirement since it uses up to 13 comparisons :]
This is basically just factoring out the swapping and sorting code from your C++ example: ``` private static void Swap(ref double a, ref double b) { double t = a; a = b; b = t; } private static void Sort(ref double a, ref double b) { if (a > b) { double t = a; a = b; b = t; } } private static double MedianOfFive(double a, double b, double c, double d, double e){ // makes a < b and c < d Sort(ref a, ref b); Sort(ref c, ref d); // eleminate the lowest if (c < a) { Swap(ref b, ref d); c = a; } // gets e in a = e; // makes a < b Sort(ref a, ref b); // eliminate another lowest // remaing: a,b,d if (a < c) { Swap(ref b, ref d); a = c; } return Math.Min(d, a); } ```
I found this post interesting and as an exercise I created this which ONLY does 6 comparisons and NOTHING else: ``` static double MedianOfFive(double a, double b, double c, double d, double e) { return b < a ? d < c ? b < d ? a < e ? a < d ? e < d ? e : d : c < a ? c : a : e < d ? a < d ? a : d : c < e ? c : e : c < e ? b < c ? a < c ? a : c : e < b ? e : b : b < e ? a < e ? a : e : c < b ? c : b : b < c ? a < e ? a < c ? e < c ? e : c : d < a ? d : a : e < c ? a < c ? a : c : d < e ? d : e : d < e ? b < d ? a < d ? a : d : e < b ? e : b : b < e ? a < e ? a : e : d < b ? d : b : d < c ? a < d ? b < e ? b < d ? e < d ? e : d : c < b ? c : b : e < d ? b < d ? b : d : c < e ? c : e : c < e ? a < c ? b < c ? b : c : e < a ? e : a : a < e ? b < e ? b : e : c < a ? c : a : a < c ? b < e ? b < c ? e < c ? e : c : d < b ? d : b : e < c ? b < c ? b : c : d < e ? d : e : d < e ? a < d ? b < d ? b : d : e < a ? e : a : a < e ? b < e ? b : e : d < a ? d : a; } ```
How do I calculate the "median of five" in C#?
[ "", "c#", "algorithm", "readability", "median", "" ]
I have a SqlCommand object, and I execute its ExecuteNonQuery method. The query fails, but I can't see how to obtain the query to debug it. Could you help me? **Update** I am currently using Wireshark (tcpdump) to read the command, but I think that its not the best solution **Update** The CommandText property only provides the Stored Procedure name. I want the whole command, with the parameters.
You can use SQL Profiler to see what is the query/call to stored procedure being sent along with parameterrs.
You can get the value of the CommandText property of your SqlCommand ? If an exception is thrown, you can catch it, and access the CommandText property which will give you the SQL command like you've set it. Offcourse, if it contains parameters, the parameters won't be replaced by the appropriate values.
How to obtain the IDbCommand output to the DB? (.NET)
[ "", "c#", ".net", "sqlcommand", "idbcommand", "" ]
This is a followup question to this question: [select all contents of textbox when it receives focus (Javascript or jQuery)](https://stackoverflow.com/questions/480735/select-all-contents-of-textbox-when-it-receives-focus-javascript-or-jquery) Basically I am using a textbox in conjunction with the [jQuery masked input plugin](http://plugins.jquery.com/maskedinput/)(Edit: Link may no longer point at relevant version) When the masked input textbox receives focus I want to select all of the contents of that textbox, but it seems as though having this plugin binded to the textbox prevents that. I was just wondering if there was a way around this. Below is a sample .html page that demonstrates the issue: ``` <html> <head> <title></title> </head> <body> <input id="masktest" type="text" value="01/01/2009" /> <br /> <input id="focustest" type="text" value="on focus will select all contents..." /> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript" src="http://jquery-joshbush.googlecode.com/files/jquery.maskedinput-1.2.1.pack.js"></script> <script type="text/javascript"> $(function() { $("#masktest").mask("99/99/9999"); // Contents of textboxes will be selected when receiving focus. $("input[type=text]") .focus(function() { $(this).select(); }); }); </script> </body> </html> ```
I'm the author of the [Masked Input Plugin](http://digitalbush.com/projects/masked-input-plugin/) for jQuery. I decided that this should be the default behavior for completed masks and I got it into the latest release. You can read the details [here](http://digitalbush.com/2009/03/10/masked-input-plugin-122/)
Hey Jon, not too sure about the performance of this, but this should work: ``` $(function() { // Contents of textboxes will be selected when receiving focus. $("input[type=text]") .focus(function() { var mask = "99/99/9999"; $(this).unmask(mask).select().mask(mask); }); }); ```
jQuery masked input plugin. select all content when textbox receives focus
[ "", "javascript", "jquery", "jquery-plugins", "" ]
I need to write a temporary Web-based graphical front-end for a custom server system. In this case performance and scalability aren't issues, since at most 10 people may check the system simultaneously. Also it should be PHP or Python (server) & JavaScript (client) (can't use Flex or Silverlight for very specific non-programming related issues). So I know I could use YUI or jQuery, but was wondering if there is something even more high-level that would say allow me to write such a little project within a few hours of work, and get done with it. Basically I want to be as lazy as possible (this is throw-away code anyways) and get the job done in as little time as possible. Any suggestions?
As it hasn't been mentioned yet: [jQuery.UI](http://ui.jquery.com/)
You could look at [ext.js](http://extjs.com) - it provides lots of widgets to GetThingsDone quickly.
What is a good Very-High level UI framework for JavaScript?
[ "", "javascript", "user-interface", "" ]
I've been playing around with ASP.NET MVC with a site containing a Master Page. I created an MVC user control called `ProductThumbnailControl`. The user control displays a product and a small thumbnail image. The View is a `ViewProduct` view which displays full product information - the usercontrol just being a UI element off to the site. ``` public partial class ProductThumbnailControl : System.Web.Mvc.ViewProductControl<ViewProductsModel> { } ``` [I read a blog entry](http://blog.matthidinger.com/2008/02/21/ASPNETMVCUserControlsStartToFinish.aspx) that shows how user controls consume `ViewData`. I learned that the user control can *automagically* get its model from the parent View. Since it's consuming the same data the View doesn't need to explicitly pass anything to the user control, making for cleaner markup and code. So now I've learned that the Master Page is using the same `ViewData` as the page. This means means the Master Page itself doesn't really have a model to help render itself. ### Question Whats the correct way for a Master Page to get its data in the first place? I thought about trying the following? You could have a `SiteModel` : ``` //Arbitrary properties for example class SiteModel { public string PartnerId {get; set;} public ShoppingCart ShoppingCartContents {get; set;} public string CurrentUserId {get; set;} } ``` The View inherits from it: ``` class ViewProductModel : SiteModel { public Product Product {get; set;} } ``` `SiteModel` would be consumed by the Master Page. Views could use data from it if needed - if they needed to display the current user's email somewhere. Is this a horrible idea? Should the master page just get its data from wherever it needs it? What if I want to include a user control in the `masthead`? Where would it get its `ViewData` from since there is only one `ViewData` object for the whle page? Would I have to use this horrible syntax that I hate and pass the master page's user control an explicit model? ``` Html.RenderUserControl("~/Views/Account/UserControls/Header.ascx", null, new { SelectedItem = "Profile" }) ``` What's the best way to tackle this scenario?
Our master page takes data from the view. We use [strongly typed view names](http://oddiandeveloper.blogspot.com/2008/11/strongly-typed-view-names.html) for our views and in the methods for that implementation we also add standard view data that every page needs from our persistent objects (like the application menu structure info, the user info to display on screen and so forth). This does have the disadvantage of making our view data for the master page not strongly typed like it is for the Model object, but it works very well for us. Your idea is also good. As the idea of the Master page is similar to the idea of inheritance, why not use inheritance to setup your model objects. You could take it a step further and create a model factory that produces your model objects and sets the base class data while it does so.
Looks like my solution is very similar to Microsoft's recommendation with one key exception. I was creatng a ViewData baseclass, and they create a Controller baseclass - which makes a lot more sense. However it seems that both ideas could (and should) work in tandem. The MS tutorial below uses a dictionary to store view data, so if you had a strongly typed model you'd also need a baseclass for that. [Microsoft MVC tutorial](http://www.asp.net/learn/mvc/tutorial-13-cs.aspx)
Should an ASP.NET masterpage get its data from the view?
[ "", "c#", ".net", "asp.net-mvc", "" ]
I am writing a JSON response from a perl/cgi program. The header's content type needs to be "application/json". But it doesn't seems to be recognized as response is thrown as a text file. I would be capturing response using JSON library of jQuery. Where am I missing in sending the JSON response.
I am doing this in a perl/cgi program. I use these in the top of my code: ``` use CGI qw(:standard); use JSON; ``` Then I print the json header: ``` print header('application/json'); ``` which is a content type of: ``` Content-Type: application/json ``` And then I print out the JSON like this: ``` my $json->{"entries"} = \@entries; my $json_text = to_json($json); print $json_text; ``` My javascript call/handles it like this: ``` $.ajax({ type: 'GET', url: 'myscript.pl', dataType: 'json', data: { action: "request", last_ts: lastTimestamp }, success: function(data){ lastTs = data.last_mod; for (var entryNumber in data.entries) { //Do stuff here } }, error: function(){ alert("Handle Errors here"); }, complete: function() { } }); ``` You don't necessarily have to use the JSON library if you don't want to install it, you could print straight JSON formatted text, but it makes converting perl objects to JSON prety easy.
Even if you specify the type "application/json" you still need to parse the text. jQuery do this for you, using the $.getJSON function,ie: ``` $.getJSON("http://someurl.com/blabla.json",{some: "info"},function(json){ alert(json["aKey"]["anotherOne"]); }); ``` (here the [specs](http://docs.jquery.com/Ajax/jQuery.getJSON#urldatacallback)). But maybe you are already aware of this, so the problem resides somewhere else: can you please tell us a sample of your json response, because maybe the problem is that is not valid. It's not really clear to me why you say that "doesnt seems to be recognised": when I write json services the first test I do is to call them on the browser and maybe fire up firebug and try to parse it (so yes the response it's a text response, but javascript it's still quite happy to parse it and return a json object).
How can I send a JSON response from a Perl CGI program?
[ "", "javascript", "perl", "json", "" ]
I was browsing through "Text Processing in Python" and tried its [example](http://gnosis.cx/TPiP/038.code) about Schwartzian sort. I used following structure for sample data which also contains empty lines. I sorted this data by fifth column: 383230 -49 -78 1 **100034** '06 text' 9562 'text' 720 'text' 867 335067 -152 -18 3 **100030** 'text' 2400 'text' 2342 'text' 696 136592 21 230 3 **100035** '03. text' 10368 'text' 1838 'text' 977 Code used for Schwartzian sorting: ``` for n in range(len(lines)): # Create the transform lst = string.split(lines[n]) if len(lst) >= 4: # Tuple w/ sort info first lines[n] = (lst[4], lines[n]) else: # Short lines to end lines[n] = (['\377'], lines[n]) lines.sort() # Native sort for n in range(len(lines)): # Restore original lines lines[n] = lines[n][1] open('tmp.schwartzian','w').writelines(lines) ``` I don't get how the author intended that short or empty lines should go to end of file by using this code. Lines are sorted after the if-else structure, thus raising empty lines to top of file. Short lines of course work as supposed with the custom sort (fourth\_word function) as implemented in the example. This is now bugging me, so any ideas? If I'm correct about this then how would you ensure that short lines actually stay at end of file? **EDIT:** I noticed the square brackets around '\377'. This messed up sort() so I removed those brackets and output started working. ``` else: # Short lines to end lines[n] = (['\377'], lines[n]) print type(lines[n][0]) >>> (type 'list') ``` I accepted nosklo's answer for good clarification about the meaning of '\377' and for his improved algorithm. Many thanks for the other answers also! If curious, I used 2 MB sample file which took 0.95 secs with the custom sort and 0.09 with the Schwartzian sort while creating identical output files. It works!
I don't know what is the question, so I'll try to clarify things in a general way. This algorithm sorts lines by getting the 4th field and placing it in front of the lines. Then built-in `sort()` will use this field to sort. Later the original line is restored. The lines empty or shorter than 5 fields fall into the `else` part of this structure: ``` if len(lst) >= 4: # Tuple w/ sort info first lines[n] = (lst[4], lines[n]) else: # Short lines to end lines[n] = (['\377'], lines[n]) ``` It adds a `['\377']` into the first field of the list to sort. The algorithm does that in hope that '\377' (the last char in ascii table) will be *bigger* than any string found in the 5th field. So the original line should go to bottom when doing the sort. I hope that clarifies the question. If not, perhaps you should indicate exaclty what is it that you want to know. A better, generic version of the same algorithm: ``` sort_by_field(list_of_str, field_number, separator=' ', defaultvalue='\xFF') # decorates each value: for i, line in enumerate(list_of_str)): fields = line.split(separator) try: # places original line as second item: list_of_str[i] = (fields[field_number], line) except IndexError: list_of_str[i] = (defaultvalue, line) list_of_str.sort() # sorts list, in place # undecorates values: for i, group in enumerate(list_of_str)) list_of_str[i] = group[1] # the second item is original line ``` The algorithm you provided is equivalent to this one.
Not directly related to the question, but note that in recent versions of python (since 2.3 or 2.4 I think), the transform and untransform can be performed automatically using the `key` argument to `sort()` or `sorted()`. eg: ``` def key_func(line): lst = string.split(line) if len(lst) >= 4: return lst[4] else: return '\377' lines.sort(key=key_func) ```
Schwartzian sort example in "Text Processing in Python"
[ "", "python", "" ]
1) How important is it for the site to be accessible without javascript? I'm using a lot of ajax. I converted most of the site to be accessible without js, but the effort involved left me wondering if it was worth it. 2) What are the sort of scenarios (that occur fairly often) in which javascript might be turned off? (apart from people being paranoid and turning off js) I'm developing the website that caters exclusively to the students in my university.I know that most (99%) of the users of the site will access it through a normal web-browser (no screen readers, or mobiles etc.) I see that even large sites like digg, reddit simply stop working when I turn off js, without any attempt to provide html only access. Even in SO, it isn't possible to vote or view comments without javascript (though there are some nice error messages shown) Edit: SEO is not a major concern, since it a very niche website, and marketing is done by other means. And right now, it has been indexed and is the first result when searching for the site name.
The most common non-accessible non-paranoid reason why JS would be disabled is when search engine bots come to index the content. You need to be able to handle that if you want to be listed properly on search engines. EDIT for your edit: Fair enough. It really depends on your site's features. If it's a primarily informational site, then requiring JS is absurd. If it's more of a web application, then not requiring makes it much harder to use. Make the informational parts (if any) as accessible as possible, and do what you want with the rest.
**The Importance of Being Accessible** It may be very important for your website to be highly accessible, especially if the site is being built for an organization which is subsidized by federal dollars. The Rehabilitation Act was ammended in 1998, and now *requires* Federal agencies to make their electronic and information technology accessible to people with disabilities. There are similar laws applying to e-commerce sites, applying to the online storefronts of traditional retailers. You can look into [**Secion 508**](http://www.section508.gov/) for more info, but the main idea is that partial page refreshes won't be read by modern screen readers, and if your site needs to be accessible, the extra effort is required, and certainly worth your effort. Many web frameworks are still in use which did not anticipate ajax, and it can require a lot of work-arounds to make things accessible. Still, it's really the best thing to do, even if you are developing a private website. Here are a couple of other articles which deal with the topic: * [**Secion 508**](http://www.section508.gov/) * [**http://www.alistapart.com/articles/saveaccessibility/**](http://www.alistapart.com/articles/saveaccessibility/) * [**http://www.alistapart.com/articles/politics/**](http://www.alistapart.com/articles/politics/) **Users without javascript** As far as "turning off" javascript, users don't do this anywhere nearly as often as they did 5 years ago, though some still may. This will not likely be the case with your audience, and it's generally not considered the major concern it once was. These days, the real concern is just client support. All modern browsers support enough javascript to allow you to do your work. It's the alternative clients, like the accessibility devices you mentioned, which may add requirements to your design. If some of your audience works in a security-sensitive environment (government agencies, etc.), it may still be mandated that javascript is turned off on their work machines. This is also becoming less and less of a problem as time goes on, though it's a more common case than the paranoia issue you mentioned. Of course, if you offer some support for those users, you won't have to worry about it.
ajax and accessibility
[ "", "javascript", "accessibility", "" ]
I thought it should be a config file, but cannot find it. thanks
If you're talking about .Net settings, then they will normally be in a .config (xml) file in the same directory as the application. When you save them, however, a local copy gets saved in to a user writable folder (typically C:\Users\username\AppData\Local under Vista). Under XP, look in the Documents and Settings folder. The .Net application uses this file in preference to the 'default' one in the application directory. Hope this helps.
The whole config file location can be a bit slippery. Depending on whether or not its a "user" setting or an "application" setting, it will go into a different file. Some settings can even come from your "machine" config (Like in the case of ASP.NET). Instead of guessing where everything is, I find it much more useful to **ask .NET where it is looking for these files**. Roughly: ``` //Machine Configuration Path string path1 = ConfigurationManager.OpenMachineConfiguration().FilePath; //Application Configuration Path string path2 = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None).FilePath; //User Configuration Path string path3 = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath; ``` ## App.Config This is what gets added to your project. The build process will name it **[myproject].exe.config**. This holds the (mostly) read only application settings and the application-level defaults for user-specific settings. Application level settings are difficult to programmatically change their values. Application level setting properties will only have "get" defined. **The intention is:** *if your setting is for all users of the application, then a manual edit (or the installer) should set them. If it changes per user, then make it a per-user setting.* ## Binary Default Settings Your application will run without its [myproject].exe.config file. To do this, the binary has its own version of the file "stored". This is useful in some ways, but can be confusing. If you have a .config file in the wrong place or with the wrong name, .NET reverts to the "binary defaults". It can cause the appearance of not being able to affect the settings by changing the config file. Use the method above to know where the .config REALLY goes, or face the wrath of the binary default settings. ## User.Config This is generated the first time you "save" your Default.Settings object with a "per-user" setting. This file is saved in the user's profile path in a location based on your project's name, version, operating system, and *some other dark .NET magics*. The properties for these settings are readable/writeable. They are designed to be easily set and then saved with a single call. ## Pulling it Together So where do my settings go? The answer is that potentially many files are joined together to get the "Active set" of settings. App.config and user.config settings are the basic blocks, but there are machine.config settings, and then there are dependency assembly settings that can further complicate things...but thats another topic entirely. The real truth of config files is *spread across a lot of ugly cases and details*. However, with a little knowledge about how they are joined together, it is a fairly useful system. Especially if you realize you can databind to these settings ;)
where property.setting value stored in c# windows application
[ "", "c#", "windows", "" ]
I need some help ... I'm a bit (read total) n00b when it comes to regular expressions, and need some help writing one to find a specific piece of text contained within a specific HTML tag from PHP. The source string looks like this: ``` <span lang="en">English Content</span><span lang="fr">French content</span> ... etc ... ``` I'd like to extract just the text of the element for a specific language. Can anyone help?
There are plenty of HTML parsers available for PHP. I suggest you check out one of those, (for example: [PHP Simple HTML DOM Parser](http://sourceforge.net/projects/simplehtmldom/)). Shooting yourself in the foot with trying to read HTML with regex is a lot easier than you think, and a lot harder to avoid than you wish (especially when you don't know regex thoroughly, and your input is not guaranteed to be 100% clean HTML).
There's this most awesome class that lets you do SQL-like queries on HTML pages. It might be worth a look: [HTML SQL](http://www.phpclasses.org/browse/package/3086.html) I've used it a bunch and I love it. Hope that helps...
PHP regex to get contents of a specific span element
[ "", "php", "regex", "" ]
All I need is to be able to detect when text is dropped into a Textarea. I then take that text and do stuff with it and clear the textarea. There may be many of these textareas and very high UI expectations, so polling is a last resort. For IE, "onfocus" does the trick, since this event is fired after the user drops stuff into the textarea. For Firefox, I can't find an event that works. I've tried onmouseup and onchange.. don't know what else to try from there. I'd hate to have to poll the textarea for content. Help much appreciated. Thanks. Edit: For clarification, "dropped" means the user selects text (usually) from the page, but it doesn't matter where, drags it, and drops it into the textarea. This is not the same as Ctrl+V, or right click pasting (which take two different methods of detection, BTW), or (obviously) typing into the textarea. Specifically, it is the "drop" aspect of drag and drop. I really don't know how else to phrase it. I feel this question was stated rather accurately. To humor me, assume that I meant any of the other operations on a textarea that you all have chosen to share. If I meant "pasting", don't you think I would have mentioned *something* about pasting in the title or content of my question? Same goes for *typing* in a textarea. But, perhaps, you all just don't know me well enough to know that I type what I mean, rather than mistakingly typing things only somewhat related to what I mean.
Polling seems to be the only way to go. When a Drag+Drop operation is started within the browser, it seems to cancel out everything else that's going on. You can witness this by putting "onmouseover" events on something on the page, then starting a DnD operation and dragging over it. The events will not fire. It seems only a coincidence of how the browser internally handles "drag and drop" that it causes onfocus() to be fired for the textarea in IE and Safari. I doubt there is much defined in the W3 specification... not that it matters, W3 is crap, and besides nobody adheres to it completely. In my question I stated the luxury of emptying out the textarea after each use, so I feel that polling for: textarea.value.length>0 is hardly any cost and shouldn't be much of a performance concern. But, alas, it specifically has to do with dropping content into a textarea. Down-mod away to sooth your pain.
For Firefox, this works for me: ``` window.addEventHandler("dragdrop", function(event) {alert("Drop it like it's hot!")}, true) ``` Does not work in Safari, however. Haven't tried IE.
Detecting drop into textarea with Javascript
[ "", "javascript", "drag-and-drop", "textarea", "detect", "" ]
For simplicity, i have the following file named test.jsp: ``` <script language="javascript"> alert("a$b".replace(/\$/g,"k")); </script> ``` I put this file in my local server, then display it using firefox: <http://localhost:8080/myproj/test.jsp>. It works okay, the result alert string is: ``` akb ``` But when i put this file in a remote server and use the same firefox to display, it output is: a$bk which is incorrect for me. Then i change the test.jsp content to: ``` <script language="javascript"> alert("a$b".replace(/\\$/g,"k")); </script> ``` Note here i add two slashes instead of one. In this case it works in the remote server but not in local one. Then i rename the file from test.jsp to test.html, but the content is the same as my first case, i.e.: ``` <script language="javascript"> alert("a$b".replace(/\$/g,"k")); </script> ``` By using the same firefox, it works okay in both servers. But my file needs to embed the javascript in jsp file. it is not allowed to use .html suffix for my file. What should I do to write a portable javascript in this scenario? My local server uses tomcat-5.5.26; remote server uses tomcat-5.0.28. Firefox version is 3.0.4.
JSP 2.0 Spec says: "When EL evaluation is disabled, \$ will not be recognized as a quote, whereas when EL evaluation is enabled, \$ will be recognized as a quote for $." (JSP.3.3.2) Whether EL Evaluation is enabled or disabled depends on many things: * if application server supports JSP 2.0 (Tomcat 5.0 and higher does) * web.xml descriptor file... if declares (e.g. by not using web-app\_2\_4.xsd schema) that it uses Servet 2.3 spec or earlier, EL is disabled by default. * JSP Configuration <el-ignored> * Page directive isELIgnored (`<%@ page isELIgnored=”true|false” %>`) (See [JSP Spec 2.0](http://jcp.org/aboutJava/communityprocess/final/jsr152/), part JSP.3.3.2 for more details) Simple way to check if EL is enabled/disabled is to use ${request} on your page. If you see '${request}' in output, EL is disabled. If you see something different, it is enabled. You may want to change `\$` (one backslash) to `\\$` (two backslashes) to get `\$` in output if you also use EL on your page. If you see differences between local/remote server, their settings related to EL probably differ. Best what you can do is to 1) use JSP 2.0, Servlet 2.4 or later (enables EL), 2) run same web server on machines. (Btw, I suggest you upgrade Tomcat 5.0 to 5.5 at least).
Maybe you can move the javascript code to a separate .js file? This will prevent the code from being interpreted as jsp.
Javascript String.replace(/\$/,str) works weirdly in jsp file
[ "", "javascript", "regex", "jsp", "tomcat", "el", "" ]
Do you know of an "easy" way to store and retrieve objects in Java **without using a relational DB / ORM like Hibernate**? [*Note that I am not considering serialization as-is for this purpose, as it won't allow to retrieve arbitrary objects in the middle of an object graph. Neither am I considering DB4O because of its restrictive license. Thanks.*] "Easy" meaning: not having to handle low-level details such as key/value pairs to rebuild an object graph (as with BerkeleyDB or traditional caches). The same applies for rebuilding objects from a document- or column-oriented DB (CouchDB, HBase, ..., even Lucene). Perhaps there are interesting projects out there that provide a layer of integration between the mentioned storage systems and the object model (like ORM would be for RDBMSs) that I am not aware of. Anyone successfully using those in production, or experimenting with persistence strategies other than relational DBs? How about RDF stores? **Update**: I came across a very interesting article: [A list of distributed key-value stores](http://www.metabrew.com/article/anti-rdbms-a-list-of-distributed-key-value-stores/)
I guess I have found a sort of answer to my question. Getting the document-oriented paradigm mindset is no easy task when you have always thought your data in terms of relationships, normalization and joins. [CouchDB](http://couchdb.apache.org) seems to fit the bill. It still could act as a key-value store but its great querying capabilities (map/reduce, view collations), concurrency readiness and language-agnostic HTTP access makes it my choice. Only glitch is having to correclty define and map JSON structures to objects, but I'm confident I will come up with a simple solution for usage with relational models from Java and Scala (and worry about caching later on, as contention is moved away from the database). Terracotta could still be useful but certainly not as with an RDBMS scenario. Thank you all for your input.
* [Object Serialization](http://www.mactech.com/articles/mactech/Vol.14/14.04/JavaSerialization/index.html) (aka storing things to a file) * [Hibernate](http://www.hibernate.org/) (uses a relational database but it is fairly transparent to the developer) I would suggest Hibernate because it will deal with most of the ugly details that bog developers down when using a database while still allowing for the optimizations that have been made to database software over the years.
Easy way to store and retrieve objects in Java without using a relational DB?
[ "", "java", "persistence", "relational", "" ]
Ok, here's a problem script. ``` var links = [ 'one', 'two', 'three' ]; for( var i = 0; i < links.length; i++ ) { var a = document.createElement( 'div' ); a.innerHTML = links[i]; a.onclick = function() { alert( i ) } document.body.appendChild( a ); } ``` This script generates three divs: one, two and three, using an array. I've set a (Dom0 for simplicity) click handler on each div which alerts the index of its position in the array. - except it doesn't! It always alerts 3, the last index of the array. This is because the 'i' in 'alert( i )' is a live reference to the outer scope (in this case global) and its value is 3 at the end of the loop. What it needs is a way of de-referencing i within the loop. This is one solution and I tend to use it. ``` var links = [ 'one', 'two', 'three' ]; for( var i = 0; i < links.length; i++ ) { var a = document.createElement( 'div' ); a.innerHTML = links[i]; a.i = i; //set a property of the current element with the current value of i a.onclick = function() { alert( this.i ) } document.body.appendChild( a ); } ``` Does anyone else do anything different? Is there a really smart way of doing it? Does anyone know how the libraries do this?
You need to use this little closure trick - create and execute a function that returns your event handler function. ``` var links = [ 'one', 'two', 'three' ]; for( var i = 0; i < links.length; i++ ) { var a = document.createElement( 'div' ); a.innerHTML = links[i]; a.onclick = (function(i) { return function() { alert( i ) } })(i); document.body.appendChild( a ); } ```
I'd stay with your own solution, but modify it in the following way: ``` var links = [ 'one', 'two', 'three' ]; function handler() { alert( this.i ); } for( var i = 0; i < links.length; i++ ) { var a = document.createElement( 'div' ); a.innerHTML = links[i]; a.i = i; //set a property of the current element with the current value of i a.onclick = handler; document.body.appendChild( a ); } ``` This way, only one function object gets created - otherwise, the function literal will be evaluated on every iteration step! A solution via closure is even worse performance-wise than your original code.
How can one de-reference JavaScript variables when enclosing an outer scope
[ "", "javascript", "scope", "" ]
We have some auto-generated resource files in our project in Visual Studio 2008, with some localized versions, and in one of these localized versions, there is a string which in this case is empty. More explicit. We have a core resource file, with lots of string resources. We then have 4 other localized versions of thisfile, and in one of these other localized files, one of the strings is given an empty value. The problem now is that the form designer is quite happy about having found a resource for a string, and will apparently stop at nothing for reusing this resource for any empty strings it will assign a property in the generated designer code for a form. For instance, if for some reason a property on a control is not specified with a default value (so it will be serialized to code even if it is empty), then it will reference our resource instead of writing out the empty string literal in the C# code. Problem is that it references the localized versions, and these aren't compiled to code. Here's an abbreviated code example: ``` this.rpAllFields.KeyTip = global::namespaces.SystemMessagesResources_sv_SE. dash_red_shift_info_description; ``` In this case, the `dash_red_shift_info_description` does not have a value for the sv-SE locale, so the designer, when it sees an empty string in the code, will try to link to that resource. But the SystemMessagesResources\_sv\_SE isn't an existing class, but seemingly a generated class name for the swedish localized version of the SystemMessagesResources resource file, which *is* compiled to a class. Is this possible to avoid? We're getting rather tired of the search/replace each time we change something in the form files, and we're pretty sure there's a slap-my-forehead-boneheaded thing we've done that make this happens, but we're aparently not capable of finding the cause of this ourselves. The above code would, if we removed the resource, read like this: ``` this.rpAllFields.KeyTip = ""; ```
You might try creating a string resource empty\_string, defined as "" for every locale. If you make it the first resource, the form designer will (hopefully) always pick that one as the value to sprinkle through your forms. This way at least you'll be using a string designated for that purpose.
If the problem is being caused by an empty string in the resource file, what would the effect be of making it a space. So instead of "" the resource file contains " ". I don't know if that's the best solution but I would be interested to know if it stops the designer from using that resource as a default empty string. However, not knowing how it is used, I'm not sure what the impact of having a value that should be undefined be defined as a space...
Resources in project file in VS2008 gets "reused" creatively by the form designer, possible to avoid?
[ "", "c#", "visual-studio-2008", "resources", "form-designer", "" ]
I decided to use LINQ to SQL in my personal project after hearing lots of goods. Is there any thing I need to taken care before start using it (during initial design)?
**EDIT** Completely rewritten as earlier post was misleading - apologies. There has been much rumour that Microsoft will not be taking Linq2Sql any further. Fuelled by an [ADO.Net team blog post](http://blogs.msdn.com/adonet/archive/2008/10/29/update-on-linq-to-sql-and-linq-to-entities-roadmap.aspx). Following that there was much speculation on [the blogs](http://codebetter.com/blogs/david.hayden/archive/2008/10/31/linq-to-sql-is-dead-read-between-the-lines.aspx) and on [Stack Overflow](https://stackoverflow.com/questions/253263/has-microsoft-really-killed-linq-to-sql) about whether or not Microsoft were really discontinuing work on Linq2Sql. If the technology works for you now and does all you need, then great. It may be that Entity Framework, or some other Data Access Model (nHibernate) will work better for you.
See [What’s wrong with Linq to SQL?](https://stackoverflow.com/questions/165102/whats-wrong-with-linq-to-sql)
LINQ to SQL: What gives pain?
[ "", ".net", "sql", "linq", "linq-to-sql", "" ]
HI, I am trying to convert the following vba code to c# and i am facing some errors.Hope someone can help me vba code ``` Open "C:\testfile.txt" For Input As #1 varii = "" Do While Not EOF(1) Line Input #1, strField varii = varii & "," & strField Loop Close #1 astrFields = Split(varii, ",") For intIx = 1 To UBound(astrFields) counter = 0 i = i + 1 Dim cn As New ADODB.Connection, cn2 As New ADODB.Connection Dim rs As ADODB.Recordset Dim connString As String Dim SelectFieldName Set cn = CurrentProject.Connection SelectFieldName = astrFields(intIx) Set rs = cn.OpenSchema(adSchemaColumns, _ Array(Empty, Empty, Empty, SelectFieldName)) If Left(rs!Table_Name, 4) <> "MSys" And Left(rs!Table_Name, 4) <> "Abfr " Then strSql = "SELECT t.[" & astrFields(intIx) & "], t.fall from [" & rs!Tab le_Name & "] t Inner Join 01UMWELT on t.fall = [01UMWELT].fall " End If Set rs3 = CurrentDb.OpenRecordset(strSql) Do While Not rs3.EOF With rs3 feedbackmsg = "Processing " & rs!Table_Name & " Record no : " & .Fields(1) SysCmd acSysCmdSetStatus, feedbackmsg varii = Nz(.Fields(astrFields(intIx)), "NullValue") If varii = "NullValue" Then Call .Edit .Fields(astrFields(intIx)) = 888 Call .Update ``` THis is the c# code so far i have coded ``` FileInfo theSourceFile = new FileInfo("C:\\csharp\\testfile.txt"); StreamReader reader = theSourceFile.OpenText(); varii = ""; do { text = reader.ReadLine(); varii = varii + "," + reader.ReadLine(); //Console.WriteLine(text); } while (text != null); string[] split = varii.Split(new Char[] {' '}); foreach (string s in split) { if (s.Trim() != "") Console.WriteLine(s); } int temp = split.GetUpperBound(1); for (intix = 1; intix <= temp; intix++) { counter = 0; i++; ADODB.Connection cn = new ADODB.Connection(); ADODB.Connection cn2 = new ADODB.Connection(); ADODB.Recordset rs; object selectfieldname; //ConnectionClass conDatabase = new ADODB.Connection(); cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source='C:\\csharp\\accident_database.mdb';"; rs = cn.OpenSchema(ADODB.SchemaEnum.adSchemaTables, Missing.Value, Missing.Value); if (Microsoft.Vbe.Left(rs.Fields("Table_Name").Value, 4) != "MSys" && + Microsoft.Vbe.Left(rs.Fields("Table_Name").Value, 4) != "Abfr") { strsql = "SELECT t.[" + split(intix) + "],t.fall from [" + rs.Fields("Table_Name").Value + "]" + "t Inner join 01umwelt on t.fall = [01umwelt].fall"; } rs3 = CurrentDB.OpenRecordset(strsql); while (!rs3.EOF) { feedbackmsg = "Processing" + rs.Fields("Table_Name").Value + "Record no:" + rs3.Fields(1).Value; SysCmd acSysCmdSetStatus, feecbackmsg; varii = Nz(rs3.Fields(astrfields(intix)).Value, "NullValue"); if (varii == "NullValue") { rs3.Edit(); rs3.Fields[astrfields(intix)].Value = 888; rs3.Update(); ``` I am recieving errors in the if statement ``` if (Microsoft.Vbe.Left(rs.Fields("Table_Name").Value, 4) != "MSys" && + Microsoft.Vbe.Left(rs.Fields("Table_Name").Value, 4) != "Abfr") ``` here Vbe.left is not getting accepted and secondly in the sql statement following this i get an error split is an variablebut used like method. Thanks
In converting bear in mind that VBA uses the same operator () for indexes and method calls, whereas C# uses [] for indexes and () for calls to methods. ``` split(intix) ``` should be ``` split[intix] ``` Try ``` rs.Fields("Table_Name").Value.ToString().Substring(0,4), but check the length first. ie rs.Fields("Table_Name").Value.ToString().Length >= 4 ```
If you add `using VB = Microsoft.VisualBasic;` namespace on top you can use `VB.Left()` instead of `Microsoft.Vbe.Left()`
C#. How to excecute a query on recordset?
[ "", "c#", "" ]
I never actually thought I'd run into speed-issues with python, but I have. I'm trying to compare really big lists of dictionaries to each other based on the dictionary values. I compare two lists, with the first like so ``` biglist1=[{'transaction':'somevalue', 'id':'somevalue', 'date':'somevalue' ...}, {'transactio':'somevalue', 'id':'somevalue', 'date':'somevalue' ...}, ...] ``` With 'somevalue' standing for a user-generated string, int or decimal. Now, the second list is pretty similar, except the id-values are always empty, as they have not been assigned yet. ``` biglist2=[{'transaction':'somevalue', 'id':'', 'date':'somevalue' ...}, {'transactio':'somevalue', 'id':'', 'date':'somevalue' ...}, ...] ``` So I want to get a list of the dictionaries in biglist2 that match the dictionaries in biglist1 for all other keys *except* id. I've been doing ``` for item in biglist2: for transaction in biglist1: if item['transaction'] == transaction['transaction']: list_transactionnamematches.append(transaction) for item in biglist2: for transaction in list_transactionnamematches: if item['date'] == transaction['date']: list_transactionnamematches.append(transaction) ``` ... and so on, not comparing id values, until I get a final list of matches. Since the lists can be really big (around 3000+ items each), this takes quite some time for python to loop through. I'm guessing this isn't really how this kind of comparison should be done. Any ideas?
Index on the fields you want to use for lookup. O(n+m) ``` matches = [] biglist1_indexed = {} for item in biglist1: biglist1_indexed[(item["transaction"], item["date"])] = item for item in biglist2: if (item["transaction"], item["date"]) in biglist1_indexed: matches.append(item) ``` This is probably thousands of times faster than what you're doing now.
What you want to do is to use correct data structures: 1. Create a dictionary of mappings of tuples of other values in the first dictionary to their id. 2. Create two sets of tuples of values in both dictionaries. Then use set operations to get the tuple set you want. 3. Use the dictionary from the point 1 to assign ids to those tuples.
Comparing massive lists of dictionaries in python
[ "", "python", "" ]
Is there a simple way to flatten a list of iterables with a list comprehension, or failing that, what would you all consider to be the best way to flatten a shallow list like this, balancing performance and readability? I tried to flatten such a list with a nested list comprehension, like this: ``` [image for image in menuitem for menuitem in list_of_menuitems] ``` But I get in trouble of the `NameError` variety there, because the `name 'menuitem' is not defined`. After googling and looking around on Stack Overflow, I got the desired results with a `reduce` statement: ``` reduce(list.__add__, map(lambda x: list(x), list_of_menuitems)) ``` But this method is fairly unreadable because I need that `list(x)` call there because x is a Django `QuerySet` object. **Conclusion**: Thanks to everyone who contributed to this question. Here is a summary of what I learned. I'm also making this a community wiki in case others want to add to or correct these observations. My original reduce statement is redundant and is better written this way: ``` >>> reduce(list.__add__, (list(mi) for mi in list_of_menuitems)) ``` This is the correct syntax for a nested list comprehension (Brilliant summary [dF](https://stackoverflow.com/users/3002/df)!): ``` >>> [image for mi in list_of_menuitems for image in mi] ``` But neither of these methods are as efficient as using `itertools.chain`: ``` >>> from itertools import chain >>> list(chain(*list_of_menuitems)) ``` And as @cdleary notes, it's probably better style to avoid \* operator magic by using `chain.from_iterable` like so: ``` >>> chain = itertools.chain.from_iterable([[1,2],[3],[5,89],[],[6]]) >>> print(list(chain)) >>> [1, 2, 3, 5, 89, 6] ```
If you're just looking to iterate over a flattened version of the data structure and don't need an indexable sequence, consider [itertools.chain and company](http://docs.python.org/library/itertools.html#itertools.chain). ``` >>> list_of_menuitems = [['image00', 'image01'], ['image10'], []] >>> import itertools >>> chain = itertools.chain(*list_of_menuitems) >>> print(list(chain)) ['image00', 'image01', 'image10'] ``` It will work on anything that's iterable, which should include Django's iterable `QuerySet`s, which it appears that you're using in the question. **Edit:** This is probably as good as a reduce anyway, because reduce will have the same overhead copying the items into the list that's being extended. `chain` will only incur this (same) overhead if you run `list(chain)` at the end. **Meta-Edit:** Actually, it's less overhead than the question's proposed solution, because you throw away the temporary lists you create when you extend the original with the temporary. **Edit:** As [J.F. Sebastian says](https://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python#411548) `itertools.chain.from_iterable` avoids the unpacking and you should use that to avoid `*` magic, but [the timeit app](https://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python#408281) shows negligible performance difference.
You almost have it! The [way to do nested list comprehensions](http://docs.python.org/tutorial/datastructures.html#nested-list-comprehensions) is to put the `for` statements in the same order as they would go in regular nested `for` statements. Thus, this ``` for inner_list in outer_list: for item in inner_list: ... ``` corresponds to ``` [... for inner_list in outer_list for item in inner_list] ``` So you want ``` [image for menuitem in list_of_menuitems for image in menuitem] ```
Flattening a shallow list in Python
[ "", "python", "list-comprehension", "" ]
I have an application that allows users to write their own code in a language of our own making that's somewhat like C++. We're getting problems, however, where sometimes our users will accidentally write an infinite loop into their script. Once the script gets into the infinite loop, the only way they can get out is to shut the application down and restart, potentially losing their work. I'd like to add some means where the user, when he realizes that his code is in an infinite loop, can hit a special key, like F10 or something, and the code will break out of the loop. But I'd like to do it without implementing a ton of checks within the script runtime. Optimally, I'd like to have a separate "debugger" thread that's mostly idle, but as one of its tasks it listens for that F10 key, and when it gets the F10 key, it will cause the script runtime thread to throw an exception, so that it will stop executing the script. So my question is, is there a way to have one thread cause another thread to throw an exception? My application is written in C++.
It's possible. Detect the keystroke in a separate thread, a hidden window and WM\_HOTKEY for example. Call SuspendThread() to freeze the interpreter thread. Now use GetThreadContext() to get the CPU registers of the interpreter thread. Modify CONTEXT.Eip to the address of a function and call SetThreadContext(). Have that function call RaiseException() or throw a C++ exception. ResumeThread() and boom.
If the script is actually interpreted by your application then you can just tell the interpreter to stop executing whenever some user event occurs.
Cross-thread exception throwing
[ "", "c++", "winapi", "" ]
Can anyone recommend a free grid/graphing component for C#/.NET? I'm having a look at NPlot right now, but so far I'm finding it quite troublesome. EDIT: I particularly need something that plugs into Windows Forms - I'm not doing ASP.NET, and don't really fancy reproducing my graph using Google's API every time I get a new data point (several times a second). Thanks :-)
MS just [released](https://weblogs.asp.net/scottgu/new-asp-net-charting-control-lt-asp-chart-runat-quot-server-quot-gt) one if you are using 3.5 or you could use [ZedGraph](https://sourceforge.net/projects/zedgraph/) EDIT: The Link is Just a ASP.NET demo they have a [Windows Forms Release](https://www.microsoft.com/en-us/download/details.aspx?id=14422) as well with [DEMOS](https://web.archive.org/web/20190502114248/https://code.msdn.microsoft.com/mschart) **Microsofts Chart Control** [![Microsofts Chart Control](https://i.stack.imgur.com/kYd2x.jpg)](https://i.stack.imgur.com/kYd2x.jpg)
[MS Chart Controls](http://www.microsoft.com/downloads/details.aspx?familyId=130f7986-bf49-4fe5-9ca8-910ae6ea442c&displayLang=en) ([VS tools](http://www.microsoft.com/downloads/details.aspx?familyid=1d69ce13-e1e5-4315-825c-f14d33a303e9&displaylang=en)) work with winforms too: > Microsoft Chart Controls for Microsoft > .NET Framework 3.5 will install new > assemblies that contain the ASP.NET > and Windows Forms Chart Controls. I haven't had time to use it yet, so I don't know whether it supports charting/plotting (rather than data-graphing).
Free C# Grid/Graph component
[ "", "c#", ".net", "graphing", "" ]
I wish to set up a ActiveMQ instance (primarily as a STOMP server) which will service requests from two types of clients: 1. authenticated users which can read and write to topics 2. non-authenticated users which can only read from topics I have been using the SimpleAuthenticationBroker so far and I cannot see anyway to configure the above situation, nor do I see any bit in the code which recognises a wildcard for a user to pass authentication. If I configure the server to use the authentication broker, it will expect ALL connections to authenticate, which is what I don't want. The only solution I think I can see is to provide my own implementation to support the functionality I require, but I would love to find some way built into the server.
This is not currently supported by ActiveMQ security implementation, but you can always define a user that can connect without a password with read-only privileges. You can raise Jira enhancement request (<https://issues.apache.org/activemq/browse/AMQ>) for this non-authenticated users feature and better yet provide a patch for current plugins.
This feature is now available as of ActiveMQ 5.4, as I've just found when searching for the same functionality: <http://activemq.apache.org/security.html>
How to configure ActiveMQ to assign an 'anonymous' user and role to non-authenticated users
[ "", "java", "security", "activemq-classic", "stomp", "" ]
I think this must be a stupid question, but why do the results of urlsafe\_b64encode() always end with a '=' for me? '=' isn't url safe? ``` from random import getrandbits from base64 import urlsafe_b64encode from hashlib import sha256 from time import sleep def genKey(): keyLenBits = 64 a = str(getrandbits(keyLenBits)) b = urlsafe_b64encode(sha256(a).digest()) print b while 1: genKey() sleep(1) ``` output : ``` DxFOVxWvvzGdOSh2ARkK-2XPXNavnpiCkD6RuKLffvA= xvA99ZLBrLvtf9-k0-YUFcLsiKl8Q8KmkD7ahIqPZ5Y= jYbNK7j62KCBA5gnoiSpM2AGOPxmyQTIJIl_wWdOwoY= CPIKkXPfIX4bd8lQtUj1dYG3ZOBxmZTMkVpmR7Uvu4s= HlTs0tBW805gaxfMrq3OPOa6Crg7MsLSLnqe-eX0JEA= FKRu0ePZEppHsvACWYssL1b2uZhjy9UU5LI8sWIqHe8= aY_kVaT8kjB4RRfp3S6xG2vJaL0vAwQPifsBcN1LYvo= 6Us3XsewqnEcovMb5EEPtf4Fp4ucWfjPVso-UkRuaRc= _vAI943yOWs3t2F6suUGy47LJjQsgi_XLiMKhYZnm9M= CcUSXVqPNT_eb8VXasFXhvNosPOWQQWjGlipQp_68aY= ```
[Base64](http://en.wikipedia.org/wiki/Base64) uses '=' for padding. Your string bit length isn't divisible by 24, so it's padded with '='. By the way, '=' should be URL safe as it's often used for parameters in URLs. See [this discussion](http://mail.python.org/pipermail/python-bugs-list/2007-February/037195.html), too.
The '=' is for padding. If you want to pass the output as the value of a URL parameter, you'll want to escape it first, so that the padding doesn't get lost when later reading in the value. ``` import urllib param_value = urllib.quote_plus(b64_data) ``` Python is just following RFC3548 by allowing the '=' for padding, even though it seems like a more suitable character should replace it.
urlsafe_b64encode always ends in '=' ?:
[ "", "python", "hash", "base64", "" ]
Drupal is very much a "Do Everything" CMS. There are modules that allow you to add almost any functionality, which is great. However, it feels like a lot of the features (v5 and v6) seem scattered around and unintuitive for the user. As a developer, I'm left with the feeling of having patched a site together using bubble gum and string. For example, to add text to the default search box (that disappears when clicked), you have to either add some jQuery code OR override the theme. I've also found the menu system more complicated than it should be. Am I the only one with this opinion? What things (if any) would you change about Drupal's core?
The lack of true object oriented design means that you frequently have to rely on other developers' foresight to leave "hook" functions to let you alter a certain behavior. Using Drupal 5 I've also run in to situations where the only way to complete a relatively simple design change is to patch Drupal itself (and then be sure to reapply patches with each new official Drupal release). But, to be fair, you should have seen how bad it was in Drupal 4. I'm also annoyed that when I take the time to identify a bug or quirk in the current production version of Drupal, I submit a patch, and the patch is never committed because, basically only security bugs get fixed in the current stable release.
To me, the biggest shortcoming of Drupal is that large portions of a live Drupal site are stored in the database. Since there's no automated way to migrate content or configuration between systems, rolling out changes to a live site must either be done manually or dealt with by excessively complicated code.
What are some of Drupal's shortcomings?
[ "", "php", "drupal", "content-management-system", "complexity-theory", "" ]
Is there a version of JDE for emacs that supports the JDK 6.10? I haven't been able to find any information on this. While it runs, every time I attempt to compile files the JDE says that it doesn't recognize my JDK version and reverts to assuming it is a Java5 version.
I've made following customizations for JDE: ``` '(jde-bug-debugger-host-address "127.0.0.1") '(jde-bug-jre-home "/usr/lib/jvm/java-6-sun") '(jde-compile-option-debug (quote ("all" (t nil nil)))) '(jde-debugger (quote ("jdb"))) '(jde-global-classpath (quote ("." "/usr/share/java/" "/usr/lib/jvm/java-6-sun/"))) '(jde-jdk-doc-url "/usr/share/doc/sun-java6-jdk/html/api/index.html") '(jde-jdk-registry (quote (("1.5" . "/usr/lib/jvm/java-6-sun")))) '(jde-regexp-jar-file "/usr/share/java/regexp.jar") '(jde-sourcepath (quote ("."))) ``` So it compiles without complaints, although I have jdk 1.6.0.07.
You can set your paths up in the configuration settings by "registering" a JDK version using `M-x customize-variable` and choosing `jde-jdk-registry`. Save that state, then do `M-x customize-variable` again, customize `jde-jdk` and pick the one you want. That *should* do it; if not, give us a little more detailed information.
JDE for Emacs for JDK 6.10
[ "", "java", "emacs", "" ]
In Java I can write a really basic JSP `index.jsp` like so: `<% request.getRequestDispatcher("/home.action").forward(request, response); %>` The effect of this is that a user requesting `index.jsp` (or just the containing directory assuming `index.jsp` is a default document for the directory) will see `home.action` without a browser redirect, i.e. the [forward](<http://java.sun.com/javaee/5/docs/api/javax/servlet/RequestDispatcher.html#forward(javax.servlet.ServletRequest,%20javax.servlet.ServletResponse))> happens on the server side. Can I do something similar with PHP? I suspect it's possible to configure Apache to handle this case, but since I might not have access to the relevant Apache configuration I'd be interested in a solution that relies on PHP alone.
If you are concerned about CURL availability then you could use `file_get_contents()` and streams. Setting up a function like: ``` function forward($location, $vars = array()) { $file ='http://'.$_SERVER['HTTP_HOST'] .substr($_SERVER['REQUEST_URI'],0,strrpos($_SERVER['REQUEST_URI'], '/')+1) .$location; if(!empty($vars)) { $file .="?".http_build_query($vars); } $response = file_get_contents($file); echo $response; } ``` This just sets up a GET, but you can do a post with `file_get_contents()` as well.
The trick about Request.Forward is that it gives you a clean, new request to the action you want. Therefore you have no residu from the current request, and for example, no problems with scripts that rely on the java eq of $\_SERVER['REQUEST\_URI'] being something. You could just drop in a CURL class and write a simple function to do this: ``` <?php /** * CURLHandler handles simple HTTP GETs and POSTs via Curl * * @author SchizoDuckie * @version 1.0 * @access public */ class CURLHandler { /** * CURLHandler::Get() * * Executes a standard GET request via Curl. * Static function, so that you can use: CurlHandler::Get('http://www.google.com'); * * @param string $url url to get * @return string HTML output */ public static function Get($url) { return self::doRequest('GET', $url); } /** * CURLHandler::Post() * * Executes a standard POST request via Curl. * Static function, so you can use CurlHandler::Post('http://www.google.com', array('q'=>'belfabriek')); * If you want to send a File via post (to e.g. PHP's $_FILES), prefix the value of an item with an @ ! * @param string $url url to post data to * @param Array $vars Array with key=>value pairs to post. * @return string HTML output */ public static function Post($url, $vars, $auth = false) { return self::doRequest('POST', $url, $vars, $auth); } /** * CURLHandler::doRequest() * This is what actually does the request * <pre> * - Create Curl handle with curl_init * - Set options like CURLOPT_URL, CURLOPT_RETURNTRANSFER and CURLOPT_HEADER * - Set eventual optional options (like CURLOPT_POST and CURLOPT_POSTFIELDS) * - Call curl_exec on the interface * - Close the connection * - Return the result or throw an exception. * </pre> * @param mixed $method Request Method (Get/ Post) * @param mixed $url URI to get or post to * @param mixed $vars Array of variables (only mandatory in POST requests) * @return string HTML output */ public static function doRequest($method, $url, $vars=array(), $auth = false) { $curlInterface = curl_init(); curl_setopt_array ($curlInterface, array( CURLOPT_URL => $url, CURLOPT_CONNECTTIMEOUT => 2, CURLOPT_RETURNTRANSFER => 1, CURLOPT_FOLLOWLOCATION =>1, CURLOPT_HEADER => 0)); if (strtoupper($method) == 'POST') { curl_setopt_array($curlInterface, array( CURLOPT_POST => 1, CURLOPT_POSTFIELDS => http_build_query($vars)) ); } if($auth !== false) { curl_setopt($curlInterface, CURLOPT_USERPWD, $auth['username'] . ":" . $auth['password']); } $result = curl_exec ($curlInterface); curl_close ($curlInterface); if($result === NULL) { throw new Exception('Curl Request Error: '.curl_errno($curlInterface) . " - " . curl_error($curlInterface)); } else { return($result); } } } ``` Just dump this in class.CURLHandler.php and you can do this: ofcourse, using $\_REQUEST is not really safe (you should check $\_SERVER['REQUEST\_METHOD']) but you get the point. ``` <?php include('class.CURLHandler.php'); die CURLHandler::doRequest($_SERVER['REQUEST_METHOD'], 'http://server/myaction', $_REQUEST); ?> ``` Ofcourse, CURL's not installed *everywhere* but we've got [native PHP curl emulators for that.](http://code.blitzaffe.com/pages/phpclasses/category/52/fileid/7) Also, this gives you even more flexibility than Request.Forward as you could also catch and post-process the output.
Does PHP Have an Equivalent of Java's RequestDispatcher.forward?
[ "", "php", "jsp", "http", "forwarding", "" ]
I am a beginner SQL user (not formally trained; OJT only) and need some assistance with a simple update statement. I would like to write an update statement that allows me to list ID's. The statement shown below is how I am currently writing it. Ideally, the statement would allow me to write it like "where plantunitid in (49-57). Is there a way to do this? Thanks for any assistance provided. update plantfunctiontable set decommissioned=1 where plantunitid in (49,50,51,52,53,54,55,56,57)
Can this work? ``` update plantfunctiontable set decommissioned=1 where plantunitid between 49 and 57 ```
You can use ``` Where plantunitid >= 49 AND plantunitid <= 57 ``` OR ``` Where plantunitid BETWEEN 49 and 57 ```
Update Statements
[ "", "sql", "sql-server-2000", "query-help", "" ]
Do you know any freely available WPF component for using masks (regex) in textbox?
I think you will find what you need in this control library: <http://www.codeplex.com/WPFDeveloperTools> Look for 'FilteredTextBox' amongst all the other useful controls. I don't think it does regex, but it should be able to filter just about everything you need, and since you will have the source, you should find it easy to enhance. As a bonus, it is free and open source on CodePlex. You can also find a nice blog post about how to go about implementing this yourself here: <http://marlongrech.wordpress.com/2007/10/28/masked-textbox/>
[Extended WPF Toolkit](https://github.com/xceedsoftware/wpftoolkit) has a [MaskedTextBox](https://github.com/xceedsoftware/wpftoolkit/wiki/MaskedTextBox) similar to the one that was in WinForms. As with the old one, this doesn't actually support RegExes, but has a subset of useful masks. Oh, and it's on [NuGet](https://www.nuget.org/packages/Extended.Wpf.Toolkit), which is nice.
Where can I find a free masked TextBox in WPF?
[ "", "c#", ".net", "wpf", "wpf-controls", "" ]