Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have an application. First I display a splash screen, a form, and this splash would call another form. Problem: When the splash form is displayed, if I then open another application on the top of the splash, and then minimize this newly opened application window, the splash screen becomes white. How do I avoid this? I want my splash to be displayed clearly and not affected by any application.
You need to display the splash screen in a different thread - currently your new form loading code is blocking the splash screen's UI thread. Start a new thread, and on that thread create your splash screen and call `Application.Run(splash)`. That will start a new message pump on that thread. You'll then need to make your main UI thread call back to the splash screen's UI thread (e.g. with Control.Invoke/BeginInvoke) when it's ready, so the splash screen can close itself. The important thing is to make sure that you don't try to modify a UI control from the wrong thread - only use the one the control was created on.
The .NET framework has excellent built-in support for splash screens. Start a new WF project, Project + Add Reference, select Microsoft.VisualBasic. Add a new form, call it frmSplash. Open Project.cs and make it look like this: ``` using System; using System.Windows.Forms; using Microsoft.VisualBasic.ApplicationServices; namespace WindowsFormsApplication1 { static class Program { [STAThread] static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); new MyApp().Run(args); } } class MyApp : WindowsFormsApplicationBase { protected override void OnCreateSplashScreen() { this.SplashScreen = new frmSplash(); } protected override void OnCreateMainForm() { // Do your time consuming stuff here... //... System.Threading.Thread.Sleep(3000); // Then create the main form, the splash screen will close automatically this.MainForm = new Form1(); } } } ```
problem with splash screen - C# - VS2005
[ "", "c#", "winforms", "splash-screen", "" ]
I have the option of writing two different formats for a database structure: ``` Article ------- ArticleID int FK Article_Tags ------------ ArticleTagID int FK ArticleID int FK TagText varchar(50) ``` or ``` Article ------- ArticleID int PK Article_Tags ------------ ArticleTagID int PK ArticleID int FK TagText varchar(50) FK Tag --- TagText varchar(50) PK ``` If I want a list of all tags in the database, I could use: ``` select distinct tagtext from article_tags ``` or: ``` select tagtext from tag ``` The first situation is pretty easy. Maybe it would speed up if i indexed it properly. The second is a little harder because I have to constantly delete tags with no joins. Imagine a pretty large system, which would be better.
I would go with ``` Article ------- ArticleID int PK Article_Tags ------------ ArticleTagID int PK ArticleID int FK TagId int FK Tag --- TagId int identity(1,1) PK TagText varchar(50) ``` There really is no reason to denormalize this from get go. (your first and second versions are not normalized) Having tags in a separate table is fine, and getting the unique tags is cleaner without that distinct statement. Performance wise if any of the 3 options are going to perform pretty much the same provided the correct indexing is applied.
I would go with whichever solution will result in the best/cleanest design for your application. If you need to attach data directly to a tag then a separate table (i.e. a more normalised solution) would be the correct one. I would warn against worrying too much about the performance difference in the 2 proposed solutions, if indexed, the difference is likely to be insignificant (both are fairly common use cases and can be easily optimised using standard db techniques). Making a decision between the 2 presented options on the basis of performance sounds like a premature optimisation.
How slow is DISTINCT?
[ "", "sql", "t-sql", "" ]
I understand (I think) that XmlHttpRequest objects adhere to the "same-domain" policy. However, I want to create a simple (POC) local html file that downloads XML from a web server and does something with it (let's start with a simple "alert()"). Is it possible at all? Do I need a special Firefox config option? The server from which I'm trying to download is **not** under my control (it's actually a Google API). My simple attempt is the code from [Mozilla's "Using XMLHttpRequest" page](https://developer.mozilla.org/En/Using_XMLHttpRequest#Example.3a.c2.a0Synchronous_request). It returns an error I don't really understand from the "send" method. Disclaimer: I'm mainly a C/C++ developer - never done any serious JS programming, never tried using these APIs.
XMLHttpRequest actually adheres to a much stricter implementation of the same domain policy: while you can set the document.domain property to allow JavaScript served from two sub-domains to talk with each other, you can't do that with XMLHttpRequestObject. In your case, going to a completely different domain, you couldn't do that with JavaScript either. There are a couple of options. First, you can use a reverse proxy to make it appear that the external site is a sub-domain of your site. Take a look at Apache's mod\_proxy, in particular ProxyPassReverse Another alternative is to return data as a JSON object: <script src="foo"> can retrieve whatever data it wants from wherever it wants. Downside of this is that it's not (easily) repeatable (as in multiple requests from same page). I also recommend that you Google for "google mashups". Most of these live on the "googlemashops.com" domain, which makes implementation a lot easier. A few live outside that domain, and may give you some ideas. Edit: rather than use the XMLHttpRequest object directly, I recommend going through a third-party library such as prototype.js
If the XML that you're trying to retrieve is returned by one of Google's JS APIs, then there's no need for XmlHttpRequest(since that can only be used on the same domain as your page anway). So in the case of using a Google API, such as the Maps one, usually begin by adding a reference to their common API somewhere on your page: ``` <script type="text/javascript" src="http://www.google.com/jsapi?key=your_google_api_key"></script> ``` Then add a reference to the specific API(s) you plan to use to your page: ``` <script type="text/javascript">google.load("maps", "2");</script> ``` Now you can call the various functions provided by that API: ``` <script type="text/javascript"> function initialize() { var map = new google.maps.Map2(document.getElementById("map")); map.setCenter(new google.maps.LatLng(41.86, 87.68), 13); } google.setOnLoadCallback(initialize); </script> ``` No XmlHttpRequest required :)
cross-site XmlHttpRequest in Firefox?
[ "", "javascript", "api", "firefox", "xmlhttprequest", "" ]
I'm new to TDD and xUnit so I want to test my method that looks something like: ``` List<T> DeleteElements<T>(this List<T> a, List<T> b); ``` Is there any Assert method that I can use ? I think something like this would be nice ``` List<int> values = new List<int>() { 1, 2, 3 }; List<int> expected = new List<int>() { 1 }; List<int> actual = values.DeleteElements(new List<int>() { 2, 3 }); Assert.Exact(expected, actual); ``` Is there something like this ?
### 2021-Apr-01 update I recommend using [FluentAssertions](https://fluentassertions.com/). It has a vast IntelliSense-friendly assertion library for many use cases including [collections](https://fluentassertions.com/collections/) ``` collection.Should().Equal(1, 2, 5, 8); collection.Should().NotEqual(8, 2, 3, 5); collection.Should().BeEquivalentTo(8, 2, 1, 5); ``` --- ### Original answer **xUnit.Net** recognizes collections so you just need to do ``` Assert.Equal(expected, actual); // Order is important ``` You can see other available collection assertions in [CollectionAsserts.cs](https://github.com/xunit/assert.xunit/blob/master/CollectionAsserts.cs) For **NUnit** library collection comparison methods are ``` CollectionAssert.AreEqual(IEnumerable, IEnumerable) // For sequences, order matters ``` and ``` CollectionAssert.AreEquivalent(IEnumerable, IEnumerable) // For sets, order doesn't matter ``` More details here: [CollectionAssert](https://github.com/nunit/docs/wiki/Collection-Assert) **MbUnit** also has collection assertions similar to NUnit: [Assert.Collections.cs](https://github.com/Gallio/mbunit-v3/blob/master/src/MbUnit/MbUnit/Framework/Assert.Collections.cs)
In the current version of XUnit (1.5) you can just use > Assert.Equal(expected, actual); The above method will do an element by element comparison of the two lists. I'm not sure if this works for any prior version.
xUnit : Assert two List<T> are equal?
[ "", "c#", "xunit", "" ]
I have a list view that is periodically updated (every 60 seconds). It was anoying to me that i would get a flicker every time it up dated. The method being used was to clear all the items and then recreate them. I decided to instead of clearing the items I would just write directly to the cell with the new text. Is this a better approach or does anyone have a better solution.
The ListView control has a flicker issue. The problem appears to be that the control's Update overload is improperly implemented such that it acts like a Refresh. An Update should cause the control to redraw only its invalid regions whereas a Refresh redraws the control’s entire client area. So if you were to change, say, the background color of one item in the list then only that particular item should need to be repainted. Unfortunately, the ListView control seems to be of a different opinion and wants to repaint its entire surface whenever you mess with a single item… even if the item is not currently being displayed. So, anyways, you can easily suppress the flicker by rolling your own as follows: ``` class ListViewNF : System.Windows.Forms.ListView { public ListViewNF() { //Activate double buffering this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true); //Enable the OnNotifyMessage event so we get a chance to filter out // Windows messages before they get to the form's WndProc this.SetStyle(ControlStyles.EnableNotifyMessage, true); } protected override void OnNotifyMessage(Message m) { //Filter out the WM_ERASEBKGND message if(m.Msg != 0x14) { base.OnNotifyMessage(m); } } } ``` From: [Geekswithblogs.net](https://web.archive.org/web/20210118172015/http://geekswithblogs.net/CPound/archive/2006/02/27/70834.aspx)
In addition to the other replies, many controls have a `[Begin|End]Update()` method that you can use to reduce flickering when editing the contents - for example: ``` listView.BeginUpdate(); try { // listView.Items... (lots of editing) } finally { listView.EndUpdate(); } ```
c# flickering Listview on update
[ "", "c#", "listview", "flicker", "" ]
I am resizing an iframe, and when I do that in Firefox, the content gets refreshed. I have a swf that extends, and in Firefox when the iframe extends to accommodate the swf, the swf appears in its normal position. In IE this doesn't happen. Anyone know how to prevent the refresh from happening in Firefox? Thanks --- **Edit:** Ok I think the page is not being refreshed just the swf please check this out at: <http://antoniocs.org/iframe/index_.html> You can see that when the re-dimensioning takes place there is a quick "flash", in Firefox 3 and the swf returns to its initial state (not expanded), this does not happen in IE. The code is all client side so you can view it all if you look at the source of the pages.
Antonio, I'm afraid that the problem is in Firefox it self. When Gecko detects a change to the width of an iFrame, it repaints the page and causes that "refresh." There's no way that I know of to change this behavior, short of using a different technique. I confirmed that the problem exists in other Gecko-based browsers as well (specifically Camino and Flock). I was not able to duplicate it in WebKit-based browsers (Chrome and Safari).
It seems to be that either setting `position: absolute;` or `.cssText` will refresh the frame. The solution is to add `style="position: absolute;"` to your `<iframe>` and set your css like this: ``` this.mrec_div_idObj.style.left = ((offsetLeftIframe) - (dimX - disX)) + "px"; this.mrec_div_idObj.style.top = (offsetTopDiv - disY) + "px"; this.mrec_div_idObj.style.zIndex = 99999999; this.mrec_div_idObj.style.margin = 0; this.mrec_div_idObj.style.padding = 0; ``` I've tested this and it **works in Firefox 3**.
How do I prevent a swf from refreshing when an iframe is resized?
[ "", "javascript", "firefox", "iframe", "flash", "refresh", "" ]
I have an ASP.Net CheckBoxList control inside an Ajax UpdatePanel. I will include the code (C#) along with the HTML below. I have found that it is something with the CheckBoxList not persisting through the post back. BTW, it is a little messy. It is a prototype. This is the method used to populate the original CheckBoxList ``` protected void BindCheckboxes() { chkBuildings.Items.Clear(); chkNeighborhoods.Items.Clear(); string city = ddlFindHome_Location.SelectedItem.Value.ToLower(); ResidentDataContext rdc = new ResidentDataContext(Utility.Lookup.GetResidentConnectionString()); var neighs = (from n in rdc.spNeighborhoods where n.vchCity.Equals(city) select n); foreach (var neighborhood in neighs) { ListItem li = new ListItem(); li.Value = neighborhood.intNeighborhoodID.ToString(); li.Attributes["onclick"] = string.Format("document.getElementById('{0}').click();", btnNeighHack.ClientID); li.Text = neighborhood.vchNeighborhood; chkNeighborhoods.Items.Add(li); } var builds = (from b in rdc.spBuildings join nb in rdc.spNeighborhoodBuildings on b.intBuildingID equals nb.intBuildingID join n in rdc.spNeighborhoods on nb.intNeightborhoodID equals n.intNeighborhoodID where n.vchCity.ToLower().Equals(city) select b).Distinct(); foreach (var buildings in builds) { ListItem li = new ListItem(); li.Value = buildings.intBuildingID.ToString(); li.Text = buildings.vchName; chkBuildings.Items.Add(li); } upNeighs.Update(); upBuilds.Update(); } ``` BindCheckboxes() is called from: ``` protected void ddlFindHome_Location_SelectedIndexChanged(object sender, EventArgs e) { BindCheckboxes(); } ``` This is the post back method for populating the Check Boxes of another CheckBoxList ``` protected void btnNeighHack_Click(object sender, EventArgs e) { List<int> neighs = new List<int>(); foreach (ListItem li in chkNeighborhoods.Items) { if (li.Selected) neighs.Add(Convert.ToInt32(li.Value)); } ResidentDataContext rdc = new ResidentDataContext(Utility.Lookup.GetResidentConnectionString()); var builds = (from b in rdc.spBuildings join nb in rdc.spNeighborhoodBuildings on b.intBuildingID equals nb.intBuildingID where neighs.Contains(nb.intNeightborhoodID) select b.intBuildingID).Distinct(); foreach (ListItem li in chkBuildings.Items) { li.Selected = false; } foreach (ListItem li in chkBuildings.Items) { if (builds.Contains(Convert.ToInt32(li.Value))) li.Selected = true; } upBuilds.Update(); } ``` Here is the ASP.Net HTML ``` <asp:UpdatePanel ID="upNeighs" runat="server" UpdateMode="Conditional"> <ContentTemplate> <div style="font-weight: bold;"> Neighborhood </div> <div style="padding-top: 7px; padding-left: 3px;"> <input type="checkbox" id="chkNeighborhood_CheckAll" />Select All </div> <hr /> <div> <asp:CheckBoxList ID="chkNeighborhoods" runat="server" /> <asp:Button style="display: none;" ID="btnNeighHack" runat="server" onclick="btnNeighHack_Click" /> </div> </ContentTemplate> </asp:UpdatePanel> <asp:UpdatePanel ID="upBuilds" runat="server" UpdateMode="Conditional"> <ContentTemplate> <div style="padding-left: 6px; padding-top: 5px; font-weight: bold;"> Building </div> <div> <asp:CheckBoxList ID="chkBuildings" runat="server" /> </div> </ContentTemplate> </asp:UpdatePanel> ``` --- I should have mentioned that the bindcheckboxes() function is called from ``` protected void ddlFindHome_Location_SelectedIndexChanged(object sender, EventArgs e) { BindCheckboxes(); } ``` So it is always a PostBack. But I think you might be onto something with that.
After further research, I have found that the controls aren't persisting through the post back, and are dropping out of the view state. So each time it posts back, there is a null object returned from: ``` protected Control PostBackControl { get { return Page.FindControl(Request.Params.Get("__EVENTTARGET")); } } ``` but it sees that the drop down list's value isn't the default value and starts to rebind everything. When I only bind the checkbox lists when the PostBackControl is the drop down list, the controls never get bound since everything in the update panel is dropping out of scope.
``` protected void BindCheckboxes() { if(!IsPostBack) { chkBuildings.Items.Clear(); chkNeighborhoods.Items.Clear(); string city = ddlFindHome_Location.SelectedItem.Value.ToLower(); ResidentDataContext rdc = new ResidentDataContext(Utility.Lookup.GetResidentConnectionString()); var neighs = (from n in rdc.spNeighborhoods where n.vchCity.Equals(city) select n); foreach (var neighborhood in neighs) { ListItem li = new ListItem(); li.Value = neighborhood.intNeighborhoodID.ToString(); li.Attributes["onclick"] = string.Format("document.getElementById('{0}').click();", btnNeighHack.ClientID); li.Text = neighborhood.vchNeighborhood; chkNeighborhoods.Items.Add(li); } var builds = (from b in rdc.spBuildings join nb in rdc.spNeighborhoodBuildings on b.intBuildingID equals nb.intBuildingID join n in rdc.spNeighborhoods on nb.intNeightborhoodID equals n.intNeighborhoodID where n.vchCity.ToLower().Equals(city) select b).Distinct(); foreach (var buildings in builds) { ListItem li = new ListItem(); li.Value = buildings.intBuildingID.ToString(); li.Text = buildings.vchName; chkBuildings.Items.Add(li); } upNeighs.Update(); upBuilds.Update(); } } ``` try that.
Asp.net updatepanel clears checkboxlist selections
[ "", "c#", "asp.net", "updatepanel", "checkboxlist", "" ]
I have a login page that has several textboxes on the page, one of them has the mode set to "password". This page worked previously but we've recently noticed (since an IE7 update) that the textbox that is specified as a password textbox is not as wide as the other textboxes on the page. If I remove the TextMode="Password", the textbox resizes to match the others. I've checked for oddities on the page when the page displays using the IE developer toolbar, but it all looks ok. The textbox code is fairly basic: ``` <tr> <td> Username </td> <td> <asp:TextBox ID="txtUsername" runat="server" TabIndex="2"></asp:TextBox> </td> </tr> <tr> <td> Password </td> <td> <asp:TextBox ID="txtPassword" TextMode="Password" runat="server" TabIndex="3"></asp:TextBox> </td> </tr> ``` I've found one other person asking about this on the web and they fixed it by applying a css to all the input controls on the page, but I haven't managed to get that to work either.
The best way to ensure that all of your controls will be of the same size is via style (either inline or in css).
I've found that if you use the following CSS: ``` input, select { font-family: sans-serif; } ``` this will make the text and password boxes be the same width. The font-family does not have to be sans-serif, but it must be defined. This may be a better solution as it seems to fix the issue rather than band-aid over it by using an explicit width in your CSS. You can now just use the default font settings of the browser by using the generic font families or be explcit if you have a particular font you are using for the page.
ASP.NET Textbox size differs when TextMode=Password
[ "", "c#", "asp.net", "" ]
I am new to C# and .NET programming. I want to design an application that opens up with a small login screen and when user presses the "Login" button, my program should close the login form and pass to a new form. How can I achieve this simple process? Thanks.
This could be a solution; In LoginForm; ``` public bool IsLoggedIn { get; private set;} public void LoginButton_Click(object sender, EventArgs e) { IsLoggedIn = DoLogin(); if(IsLoggedIn) { this.Close() } else { DoSomethingElse(); } } ``` In program.cs ``` static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); LoginForm loginForm = new LoginForm(); Application.Run(loginForm); if (loginForm.IsLoggedIn) { Application.Run(new OtherForm()); } } ```
Depending on the overall architecture of your application, I often like to let the main form control launching the login screen. ``` //Program.cs: [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } //MainForm.cs private void MainForm_Load(object sender, EventArgs e) { this.Hide(); Login login = new Login(); if (login.ShowDialog() == DialogResult.OK) { //make assignments from login currentUser = login.User; } else { //take needed action Application.Exit(); return; } } ```
Two different windows forms in C#
[ "", "c#", "winforms", "authentication", "screen", "" ]
Is there stable linear algebra (more specifically, vectors, matrices, multidimensional arrays and basic operations on them) library for C#? Search yielded a few open source libraries which are either not updated for couple of years or are in an early beta stage - and Centerspace NMath. Which alternatives are worth checking?
[Math.NET](http://numerics.mathdotnet.com/). We're using it in production.
See: <http://en.wikipedia.org/wiki/List_of_numerical_libraries> <http://www.alglib.net/> - Open source. Multi-language library. <http://www.mathdotnet.com/> - Open source. As mentioned by others. dnAnalytics is replaced by <http://numerics.mathdotnet.com/> in this. <http://www.lutzroeder.com/dotnet/> - Lutz Roeder has a open source port Mapack.Net of LAPACK. <http://www.extremeoptimization.com/> - Commercial.
C# linear algebra library
[ "", "c#", ".net", "linear-algebra", "nmath", "" ]
I still have a problem with the splash screen. I don't want to use the property `SC.TopMost=true`. Now my application scenario is as follows: **in progeram.cs:** ``` [STAThread] static void Main() { new SplashScreen(_tempAL);// where _tempAL is an arrayList Application.Run(new Form1(_tempAL)); } ``` **in SplashScreen class:** ``` public SplashScreen(ArrayList _Data) { DisplaySplash() } private void DisplaySplash() { this.Show(); this.TopMost = true; this.CenterToScreen(); this.SetTopLevel(true); _allServerNarrators = new string[10]; for (int i = 0; i < _allServerNarrators.Length; i++) _allServerNarrators[i] = null; GetFromServer(); this.Hide(); _serverData = new ArrayList(); _thisData.Add(_allServerNarrators); _thisData.Add(_serverNarrators); } private void GetFromServer() { _serverNarrators = new ArrayList(); string _file = "Suras.serverNar"; if (!Directory.Exists("c:\\ASGAQuraan")) Directory.CreateDirectory("c:\\ASGAQuraan"); while (counter < 4 && _serverFiles == null) { if (Download("c:\\ASGAQuraan", _ftpServerIP, _file)) { StreamReader _strReader = new StreamReader ("c:\\ASGAQuraan\\"+_file,System.Text.Encoding.Default); string _line = _strReader.ReadLine(); string _word; while (true) { while (_line != null) { _word = _line.Substring(0, _line.IndexOf("*")); int _narId = Convert.ToInt32(_word); _line = _line.Substring(2); int k = 0; _serverNarratorNode = new ArrayList(); while (true) { int ind = _line.IndexOf("*"); if (ind > 0 && ind < _line.Length) { string str = _line.Substring(0, (ind)); if (k == 0) { _allServerNarrators[_narId] = str; _serverNarratorNode.Add(str); } else { _serverNarratorNode.Add(str); } _line = _line.Substring(ind + 1); k++; } else { _line = null; break; } } _serverNarrators.Add(_serverNarratorNode); _serverFiles = "added"; } _line = _strReader.ReadLine(); if (_line == null) { break; } } } else counter++; } } ``` What I want is something in the splash screen class which waits until the thread finishes. For more details, please tell me what I need to tell you.
Following across 2 threads is a bit confusing, but I'm going to take a stab and say this... I don't fully understand your design here, but if the issue is that when you launch a second application the splash screen form turns white... It's most likely due to the fact that splash screen is busy executing all of that code in GetFromServer(). So busy that it has no time to re-paint itself. To remedy this problem I would suggest that you use the [BackGroundWorker component](http://msdn.microsoft.com/en-us/library/8xs8549b.aspx) to execute the GetFromServer method. This will run that method in a separate thread and leave the form's thread free to re-paint itself.
Same question, same answer: The .NET framework has excellent built-in support for splash screens. Start a new WF project, Project + Add Reference, select Microsoft.VisualBasic. Add a new form, call it frmSplash. Open Project.cs and make it look like this: ``` using System; using System.Windows.Forms; using Microsoft.VisualBasic.ApplicationServices; namespace WindowsFormsApplication1 { static class Program { [STAThread] static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); new MyApp().Run(args); } } class MyApp : WindowsFormsApplicationBase { protected override void OnCreateSplashScreen() { this.SplashScreen = new frmSplash(); } protected override void OnCreateMainForm() { // Do your time consuming stuff here... //... System.Threading.Thread.Sleep(3000); // Then create the main form, the splash screen will close automatically this.MainForm = new Form1(); } } } ```
Splash Screen waiting until thread finishes
[ "", "c#", "winforms", "splash-screen", "" ]
I was reading a question about c# code optimization and one solution was to use c++ with SSE. Is it possible to do SSE directly from a c# program?
The upcoming [Mono](http://www.mono-project.com/Main_Page) 2.2 release will have SIMD support. Miguel de Icaza blogged about the upcoming feature [here](http://tirania.org/blog/archive/2008/Nov-03.html), and the API is [here](http://go-mono.com/docs/index.aspx?tlink=0@N%3aMono.Simd). Although there will be a library that will support development under Microsoft's .NET Windows runtime, it will not have the performance benefits that you are looking for unless you run the code under the Mono runtime. Which might be doable depending on your circumstances. Update: Mono 2.2 is [released](http://www.mono-project.com/Release_Notes_Mono_2.2#SIMD_support_in_Mono)
**Can C# explicitly make an SSE call?** No. C# cannot produce inline IL much less inline x86/amd64 assembly. The CLR, and more specifically the JIT, will use SSE if it's available removing the need to force it in most circumstances. I say most because I'm not an SSE expert and I'm sure that there are cases where it could be beneficial and the JIT does not make the optimization.
Using SSE in c# is it possible?
[ "", "c#", "sse", "" ]
I have a Python class full of static methods. What are the advantages and disadvantages of packaging these in a class rather than raw functions?
There are none. This is what modules are for: grouping related functions. Using a class full of static methods makes me cringe from Javaitis. The only time I would use a static function is if the function is an integral part of the class. (In fact, I'd probably want to use a class method anyway.)
No. It would be better to make them functions and if they are related, place them into their own module. For instance, if you have a class like this: ``` class Something(object): @staticmethod def foo(x): return x + 5 @staticmethod def bar(x, y): return y + 5 * x ``` Then it would be better to have a module like, ``` # something.py def foo(x): return x + 5 def bar(x, y): return y + 5 * x ``` That way, you use them in the following way: ``` import something print something.foo(10) print something.bar(12, 14) ``` Don't be afraid of namespaces. `;-)`
Is there any advantage in using a Python class?
[ "", "python", "class", "static-methods", "" ]
How to do it? Is it possible to call a function from one F# code into C# without using a separated dll file or project?
You can't include two different languages in the same project, but you can merge them using [ilmerge](http://research.microsoft.com/en-us/people/mbarnett/ILMerge.aspx). To do this, put both projects in the same solution and reference the F# module as you would any dll. As part of your deployment script, run ilmerge to combine the exe file and dll file into a single exe file. See this [Code Project](http://www.codeproject.com/KB/dotnet/mergingassemblies.aspx) article that details how to use ilmerge to create an exe.
Not being able to mix C# and F# in the same project creates a problem; It leads to circular dependencies between the two projects. Conceptually there is only one project containing two languages, but because of the way visual studio manages projects languages cannot be mixed, leading to circular dependencies. For now the only solution I see it to create a lot of interfaces in a third project and have one of the project refer to the interfaces project, instead of the real project. Is there a better way? Kind Regards, Nick
Is it possible to mix .cs (C#) and .fs (F#) files in a single Visual Studio Windows Console Project? (.NET)
[ "", "c#", ".net", "visual-studio", "f#", "console", "" ]
I have a sparsely populated matrix that's the result of a series of left joins. I'd like to collapse it down to a single row (see below). The only solution I've seen to this is a GROUP BY on the PK and a MAX() on ColA, ColB etc. Performance is a huge issue here, so I'd like to know if anyone has a better solution. The columns ColA, ColB etc are rows that have been pivoted to columns. My understanding is that I can't use a PIVOT because the columns are coming from rows (1 to n) and could change at any given time. Join that produces the SPM (no, my tables/cols aren't really named that): ``` SELECT mainTable.custNbr , mainTable.custPartNbr , [lkup colA].usr_def_attr as [colA] , [lkup colB].usr_def_attr as [colB] , [lkup colC].usr_def_attr as [colC] , [lkup colD].usr_def_attr as [colD] , [lkup colE].usr_def_attr as [colE] FROM db2.dbo.table2 as mainTable LEFT JOIN db1.dbo.lookup as [colA] ON mainTable.lookupValue = [colA].lkup_id and mainTable.cmply_typ_lkup_id = 166697 LEFT JOIN db1.dbo.lookup as [lkup colB] ON mainTable.lookupValue = [lkup colB].lkup_id and mainTable.cmply_typ_lkup_id = 166700 LEFT JOIN db1.dbo.lookup as [lkup colC] ON mainTable.lookupValue = [lkup colC].lkup_id and mainTable.cmply_typ_lkup_id = 166699 LEFT JOIN db1.dbo.lookup as [lkup colD] ON mainTable.lookupValue = [lkup colD].lkup_id and mainTable.cmply_typ_lkup_id = 166696 LEFT JOIN db1.dbo.lookup as [lkup colE] ON mainTable.lookupValue = [lkup colE].lkup_id and mainTable.cmply_typ_lkup_id = 166698 ``` Result: ``` PKCol ColA ColB ColC ColD ColE 204045 NULL NULL NULL NULL 23 204045 NULL NULL NULL 35 NULL 204045 NULL NULL 35 NULL NULL 204045 NULL 23 NULL NULL NULL 204045 23 NULL NULL NULL NULL ``` Desired result: ``` PKCol ColA ColB ColC ColD ColE 20405 23 23 35 35 23 ```
I rewrote this as a PIVOT and saw a performance increase of about 30%. It wasn't easy to do, had to read [**this post**](http://www.simple-talk.com/community/blogs/andras/archive/2007/09/14/37265.aspx) very carefully. PIVOTs are weird.
The GROUPY BY + MAX solution isn't a bad one. Since it's going to be scanning over the same number of records whether or not you're doing aggregates. I'd be curious to know what the time difference with and without grouping is.
best way to collapse a sparsely populated matrix
[ "", "sql", "sql-server", "" ]
What is the best way to append to a text field using t-sql in Sql Server 2005? With a varchar I would do this. ``` update tablename set fieldname = fieldname + 'appended string' ``` But this doesn't work with a text field.
Try this: ``` update tablename set fieldname = convert(nvarchar(max),fieldname) + 'appended string' ```
[This should work (link)](http://developer.fusium.com/FUblog/index.cfm/2006/7/13/appending-an-ntext-field "This should work.") Copied from link: ``` DECLARE @ptrval binary(16) SELECT @ptrval = TEXTPTR(ntextThing) FROM item WHERE id =1 UPDATETEXT table.ntextthing @ptrval NULL 0 '!' GO ```
How to append to a text field in t-sql SQL Server 2005
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "append", "" ]
I have a JAR file named *helloworld.jar*. In order to run it, I'm executing the following command in a command-line window: ``` java -jar helloworld.jar ``` This works fine, but how do I execute it with double-click instead? Do I need to install any software?
Easiest route is probably upgrading or re-installing the Java Runtime Environment (JRE). Or this: * Open the Windows Explorer, from the Tools select 'Folder Options...' * Click the File Types tab, scroll down and select JAR File type. * Press the Advanced button. * In the Edit File Type dialog box, select open in Actions box and click Edit... * Press the Browse button and navigate to the location the Java interpreter javaw.exe. * In the Application used to perform action field, needs to display something similar to `C:\Program Files\Java\j2re1.4.2_04\bin\javaw.exe" -jar "%1" %` (Note: the part starting with 'javaw' must be exactly like that; the other part of the path name can vary depending on which version of Java you're using) then press the OK buttons until all the dialogs are closed. Which was stolen from here: <http://windowstipoftheday.blogspot.com/2005/10/setting-jar-file-association.html>
In Windows Vista or Windows 7, the [manual file association editor](https://stackoverflow.com/questions/394616/running-jar-file-in-windows/394628#394628) has been removed. The easiest way is to run [Jarfix](http://johann.loefflmann.net/en/software/jarfix/index.html), a tiny but powerful freeware tool. Just run it and your Java apps is back... double-clickable again.
Running JAR file on Windows
[ "", "java", "jar", "executable-jar", "" ]
Right now I am using this to export a repeater (with multiple nested repeaters) to excel: ``` protected void ExportToExcel(object sender, EventArgs e) { Response.Clear(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment;filename=finance.xls"); Response.Charset = ""; Response.ContentType = "application/vnd.ms-excel"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); rptMinistry.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); } ``` But this is not doing what I want. Instead it is giving me html in the excel file (though the data is there) this is what I get (each line is a cell in the excel sheet): ``` <tr class="alt"> <td class='hidden'>LOR In Development</td> <td>MOD</td> <td>Air Force</td> <td class="size1"></td> <td>Hellfire (AGM-114) Follow On</td> <td>10-Mar-08</td> <td class="align_right ">$50,000,000.00</td> <td class="align_right hidden">$0.00</td> </tr> <tr class="alt"> <td class='hidden'>LOR In Development</td> <td>MOD</td> <td>Air Force</td> <td class="size1"></td> <td>Precision Strike Mi-17 (block 20)</td> <td>17-May-08</td> <td class="align_right ">$20,100,000.00</td> <td class="align_right hidden">$0.00</td> </tr> ``` and so on... now the data is correct, but how can I get it to show up correctly in the spreadsheet?
You need to enclose all of that in table tags. Excel can understand HTML table structures. Try: ``` Response.Write("<table>"); Response.Write(stringWrite.ToString()); Response.Write("</table>"); ```
not to answer your question directly, but given you my opinion for that kinda of data, is in my opinion that you should use a GridView control, taking your example you will need to write something like: ``` <asp:Repeater ID="rpt" runat="server" DataSourceID="ods"> <HeaderTemplate> <table> <tr> <td>Header</td> <td>Type</td> <td>Name</td> <td>Date</td> <td>Amount</td> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td> <%#Eval("Header")%> </td> <td> <%#Eval("Type")%> </td> <td> <%#Eval("Name")%> </td> <td> <%#Eval("Date", "{0:d}")%> </td> <td> <%#Eval("Value", "{0:c}")%> </td> </tr> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> ``` using a GridView all ou nee dto write in the HTML part is only: ``` <asp:GridView ID="gv" runat="server" DataSourceID="ods" AutoGenerateColumns="false"> <Columns> <asp:BoundField DataField="Header" HeaderText="Header" /> <asp:BoundField DataField="Type" HeaderText="Type" /> <asp:BoundField DataField="Name" HeaderText="Name" /> <asp:BoundField DataField="Date" DataFormatString="{0:d}" HeaderText="Date" /> <asp:BoundField DataField="Value" DataFormatString="{0:c}" HeaderText="Value" /> </Columns> </asp:GridView> ``` something simpler and easier to read you will have much more control using a GridView object rather than a Repeater, and, you will never have that kinda of problems, because rendering the gridView will always came with the table tags. Hope it helps And BTW, I tested your case and i did not got any problems even if I was not writting the tags like Spencer mention. to see my code: [File with HTML and Method](http://rafb.net/p/CzBIX887.html) - [File with myObject](http://pastebin.com/m3da6bebd)
Export to Excel from a Repeater?
[ "", "c#", "asp.net", "excel", "repeater", "" ]
I have a few procedures, for simplicity sake, look like the following: ``` public string FetchValueAsString(string key) public int FetchValueAsInteger(string key) public bool FetchValueAsBoolean(string key) public DateTime FetchValueAsDateTime(string key) ``` I know I could just have one method that returns and object type and just do a conversion, but I'm wondering if there is a way I can just have one method called, and somehow use generics to determine the return value ... possible?
``` public static T FetchValue<T>(string key) { string value; // logic to set value here // ... return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture); } ```
I'm assuming you're writing code in C#. If you are then you could do what your talking about like this: ``` public T FetchValueAsType<T>(string key) ``` You would then call the version like this: ``` FetchValueAsType<int>(key); ``` That being said the the `System.Convert` class provided by the framework works just as well and has similar syntax. You can find the msdn article about it here: <http://msdn.microsoft.com/en-us/library/system.convert.aspx>
One function with varying return types ... possible with Generics?
[ "", "c#", ".net", "generics", "" ]
I've always wondered how to write the **`"A ? B : C"`** syntax in a C++ compatible language. I think it works something like: *(Pseudo code)* ``` If A > B C = A Else C = B ``` *Will any veteran C++ programmer please help me out?*
It works like this: ``` (condition) ? true-clause : false-clause ``` It's most commonly used in assignment operations, although it has other uses as well. The ternary operator `?` is a way of shortening an if-else clause, and is also called an immediate-if statement in other languages (`IIf(condition,true-clause,false-clause)` in VB, for example). For example: ``` bool Three = SOME_VALUE; int x = Three ? 3 : 0; ``` is the same as ``` bool Three = SOME_VALUE; int x; if (Three) x = 3; else x = 0; ```
It works like this: ``` expression ? trueValue : falseValue ``` Which basically means that if `expression` evaluates to true, trueValue will be returned or executed, and falseValue will be returned or evaluated if not. Remember that trueValue and falseValue will only be evaluated and executed if the expression is true or false, respectively. This behavior is called short circuiting.
How do I use the conditional (ternary) operator?
[ "", "c++", "conditional-operator", "" ]
I understand the reflection API (in c#) but I am not sure in what situation would I use it. What are some patterns - anti-patterns for using reflection?
The only place I've used the Reflection stuff in C# was in factory patterns, where I'm creating objects (in my case, network listeners) based on configuration file information. The configuration file supplied the location of the assemblies, the name of the types within them, and any additional arguments needed. The factory picked this stuff up and created the listeners based on that.
In one product I'm working on we use it a lot, but Reflection is a complex, slow beast. Don't go looking for places to use it just because it sounds fun or interesting. You'll use it when you run into a problem that can't be solved in any other way (dynamically loading assemblies for plug ins or frameworks, assembly inspection, factories where types aren't know at build, etc). It's certainly worth looking at reflection tutorials to see how it works, but don't fall into the trap of "having a hammer and everything looking like a nail." It's got very specialized use cases.
When do you use reflection? Patterns/anti-patterns
[ "", "c#", "reflection", "" ]
I started with a query: ``` SELECT strip.name as strip, character.name as character from strips, characters, appearances where strips.id = appearances.strip_id and characters.id = appearances.character.id and appearances.date in (...) ``` Which yielded me some results: ``` strip | character 'Calvin & Hobbes' | 'Calvin' 'Calvin & Hobbes' | 'Hobbes' 'Pearls Before Swine' | 'Pig' 'Pearls Before Swine' | 'Rat' 'Pearls Before Swine' | 'Hobbes' # a guest appearance 'Pearls Before Swine' | 'Calvin' # a guest appearance ``` Then I wanted to also get the `COUNT` of the number of times a character is used (in any strip) within the result set. So I tried: ``` SELECT count(character.id), strip.name as strip, character.name as character from strips, characters, appearances where strips.id = appearances.strip_id and characters.id = appearances.character.id and appearances.date in (...) ``` But that gave me ``` [ERROR 11:20:17] Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause ``` So I tried: ``` SELECT count(character.id), strip.name as strip, character.name as character from strips, characters, appearances where strips.id = appearances.strip_id and characters.id = appearances.character.id and appearances.date in (...) group by character.id ``` Which gave me ``` count | strip | character 4 | 'Calvin & Hobbes' | 'Calvin' 4 | 'Calvin & Hobbes' | 'Hobbes' 2 | 'Pearls Before Swine' | 'Pig' 2 | 'Pearls Before Swine' | 'Rat' ``` That is, I lose all the extra information about exactly which characters appear in which strips. What I'd like to get is this: ``` count | strip | character 4 | 'Calvin & Hobbes' | 'Calvin' 4 | 'Calvin & Hobbes' | 'Hobbes' 2 | 'Pearls Before Swine' | 'Pig' 2 | 'Pearls Before Swine' | 'Rat' 4 | 'Pearls Before Swine' | 'Calvin' 4 | 'Pearls Before Swine' | 'Hobbes' ``` But I can't seem to figure it out. I'm on MySQL if it matters. Perhaps it'll just take two queries.
Does mySQL support analytic functions? Like: ``` SELECT foo.bar, baz.yoo, count(baz.yoo) over (partition by foo.bar) as yoo_count from foo, bar where foo.baz_id = baz.id and baz.id in (...) ``` Alternatively: ``` SELECT foo.bar, baz.yoo, v.yoo_count from foo, bar, ( select foo.baz_id, count(*) as yoo_count from foo group by foo.baz_id ) as v where foo.baz_id = baz.id and baz.id in (...) and v.baz_id = foo.baz_id; ```
What about grouping by foo.bar? ``` SELECT count(baz.id) as count, foo.bar, baz.yoo where foo.baz_id = baz.id and baz.id in (...) group by foo.bar ```
How can I mix COUNT() and non-COUNT() columns without losing information in the query?
[ "", "sql", "" ]
From my understanding, Lua is an embeddable scripting language that can execute methods on objects. What are the pitfalls to avoid? Is is it feasible to use Lua as an interpreter and execute methods in an web environment or as a rule engine?
Lua is very fast - scripts can be precompiled to bytecodes and functions execute close to C++ virtual method calls. That is the reason why it is used in gaming industry for scripting AI, plugins, and other hi-level stuff in games. But you put C# and web server in your question tags. If you are not thinking of embedded web servers - than Lua is not very strong. Lua is ANSI C - it compiles to native code, and as such it is not very welcome to your asp.net server, nor to your C# code. Think of "medium trust" or "binding" or "64bit". Enough of pitfalls. If you are allready using C#, there is no reason to avoid it on web server. It gets compiled and cached. It servers huge sites like this one.
Lua scripting is [on track](http://lua-users.org/lists/lua-l/2008-12/msg00119.html) to becoming a core module for Apache web server. There are a couple tools for binding Lua and C#/.NET code [here](http://lua-users.org/wiki/BindingCodeToLua). [LuaInterface](http://lua-users.org/wiki/LuaInterface) is the most up to date.
What are the most effective ways to use Lua with C#?
[ "", "c#", "performance", "clr", "lua", "" ]
I have a huge list of datetime strings like the following ``` ["Jun 1 2005 1:33PM", "Aug 28 1999 12:00AM"] ``` How do I convert them into [`datetime`](https://docs.python.org/3/library/datetime.html#datetime-objects) objects?
[`datetime.strptime`](https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime) parses an input string in the user-specified format into a *timezone-naive* [`datetime`](https://docs.python.org/3/library/datetime.html#datetime-objects) object: ``` >>> from datetime import datetime >>> datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p') datetime.datetime(2005, 6, 1, 13, 33) ``` To obtain a [`date`](https://docs.python.org/3/library/datetime.html#date-objects) object using an existing `datetime` object, convert it using `.date()`: ``` >>> datetime.strptime('Jun 1 2005', '%b %d %Y').date() date(2005, 6, 1) ``` --- **Links:** * `strptime` docs: [Python 2](https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime "datetime.datetime.strptime"), [Python 3](https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime) * `strptime`/`strftime` format string docs: [Python 2](https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior "strftime-and-strptime-behavior"), [Python 3](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior) * [strftime.org](http://strftime.org/) format string cheatsheet **Notes:** * `strptime` = "string parse time" * `strftime` = "string format time"
Use the third-party [`dateutil`](https://dateutil.readthedocs.io) library: ``` from dateutil import parser parser.parse("Aug 28 1999 12:00AM") # datetime.datetime(1999, 8, 28, 0, 0) ``` It can handle most date formats and is more convenient than `strptime` since it usually guesses the correct format. It is also very useful for writing tests, where readability is more important than performance. Install it with: ``` pip install python-dateutil ```
Convert string "Jun 1 2005 1:33PM" into datetime
[ "", "python", "datetime", "" ]
OK, every other browser works fine with the method I have coded so far but for some reason Internet Explorer will not work. I have spent hours of time (more time than actually developing the feature!) on compatibility and am close to giving up! I have a forum and one of its neat features is the WYSIWYG editor. For that, I essentially have an IFrame that acts as the document: ``` <iframe name="writer" src="/scripts/blank.html" class="writer"></iframe> ``` This is the current state of the JavaScript (constantly updated): ``` function initEditor() { w = frames['writer'] wc = g('writerCopy') if(w == null) return frames['writer'].document.designMode = 'on' frames['writer'].document.body.innerHTML = styleSheet+wc.value frames['writer'].focus() } ``` It works partially now, but fails on the line: ``` frames['writer'].document.body.innerHTML = styleSheet+wc.value ``` in Internet Explorer with "'frames.writer.document.body' is null or not an object".
In the end I used frames['frameName'].document.write('someText') but only if the other method fails.
Have you activated IE's [debugging](https://msdn.microsoft.com/library/bg182326(v=vs.85)) [facilities](https://msdn.microsoft.com/en-us/library/gg699336%28v=vs.85%29.aspx)?
Accessing frames via the DOM in IE
[ "", "javascript", "html", "internet-explorer", "iframe", "" ]
Is there a nice way to split a collection into `n` parts with LINQ? Not necessarily evenly of course. That is, I want to divide the collection into sub-collections, which each contains a subset of the elements, where the last collection can be ragged.
A pure linq and the simplest solution is as shown below. ``` static class LinqExtensions { public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts) { int i = 0; var splits = from item in list group item by i++ % parts into part select part.AsEnumerable(); return splits; } } ```
EDIT: Okay, it looks like I misread the question. I read it as "pieces of length n" rather than "n pieces". Doh! Considering deleting answer... (Original answer) I don't believe there's a built-in way of partitioning, although I intend to write one in my set of additions to LINQ to Objects. Marc Gravell has an [implementation here](https://stackoverflow.com/questions/410717/f-seq-module-implemented-in-c-for-ienumerable#410759) although I would probably modify it to return a read-only view: ``` public static IEnumerable<IEnumerable<T>> Partition<T> (this IEnumerable<T> source, int size) { T[] array = null; int count = 0; foreach (T item in source) { if (array == null) { array = new T[size]; } array[count] = item; count++; if (count == size) { yield return new ReadOnlyCollection<T>(array); array = null; count = 0; } } if (array != null) { Array.Resize(ref array, count); yield return new ReadOnlyCollection<T>(array); } } ```
Split a collection into `n` parts with LINQ?
[ "", "c#", ".net", "linq", "data-structures", "" ]
A *using* declaration does not seem to work with an enum type: ``` class Sample{ public: enum Colour {RED, BLUE, GREEN}; } using Sample::Colour; ``` does not work! Do we need to add a *using* declaration for every enumerators of enum type? Like below: ``` using sample::Colour::RED; ```
A class does not define a namespace, and therefore "using" isn't applicable here. Also, you need to make the enum public. If you're trying to use the enum within the same class, here's an example: ``` class Sample { public: enum Colour { RED, BLUE, GREEN }; void foo(); } void Sample::foo() { Colour foo = RED; } ``` And to access it from outside the class: ``` void bar() { Sample::Colour colour = Sample::RED; } ```
To add to [Steve Lacey's answer](https://stackoverflow.com/questions/438192/using-declaration-with-enum#438210), the problem with the original code is that you refer to a member, but the *using* declaration is not itself a member declaration: 7.3.3/6 has: > A using-declaration for a class member > shall be a member-declaration. To highlight this, the following example does work: ``` class Sample { public: enum Colour { RED,BLUE,GREEN}; }; class Derived : public Sample { public: using Sample::Colour; // OK }; ``` Finally, as [pointed out by Igor Semenov](https://stackoverflow.com/questions/438192/using-declaration-with-enum#438214), even if you move the enum definition into a namespace, thereby allowing the *using* declaration, the *using* declaration will only declare the name of the enum type into the namespace (the 2003 standard reference is 7.3.3/2). ``` namespace Sample { enum Colour { RED,BLUE,GREEN}; } using Sample::Colour; using Sample::BLUE; void foo () { int j = BLUE; // OK int i = RED; // ERROR } ``` **Dependent Base Types** To allow for partial and explicit specializations, when the compiler parses a class template. it does not perform any lookups in dependent base classes. As a result, the following variation with Sample as a template does not compile: ``` template <typename T> class Sample { public: enum Colour { RED,BLUE,GREEN}; }; template <typename T> class Derived : public Sample<T> { public: using Sample<T>::Colour; // What kind of entity is Colour? Colour foo () // Not OK! { return this->RED; } }; ``` The problem is that `Derived::Colour` is treated as an object by the compiler (14.6/2): > A name used in a template declaration or definition and that is dependent on a template-parameter is assumed not to name a type unless the applicable name lookup finds a type name or the name is qualified by the keyword typename. Looking at the two conditions for the name to be a type: 1. Lookup for `Colour` doesn't find a type because the dependent base `Sample<T>` is not searched. 2. The name is not qualified by `typename` The example therefore needs the `typename` keyword: ``` template <typename T> class Derived : public Sample<T> { public: using typename Sample<T>::Colour; // Colour is treated as a typedef-name Colour foo () // OK { return this->RED; } }; ``` **Note:** The 1998 version of the standard didn't allow `typename` to be used with a using declaration and so the above fix was not possible. See *[Accessing types from dependent base classes](https://stackoverflow.com/q/1071119/11698)* and *[CWG11](http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#11)*.
A 'using' declaration with an enum
[ "", "c++", "enums", "using-declaration", "" ]
I have three applications that talk to each other using sockets. They can all live on their own machines but they can also share a machine. Right now I'm having two of them on the same and the third on its own machine. I'm trying to make my communication bullet proof so I unplug cables and kill the applications to make sure everything works as intended. Here's a quick sketch of the thing: [![alt text](https://i.stack.imgur.com/4e0M5.png)](https://i.stack.imgur.com/4e0M5.png) Now, when I unplug the network cable to PC2 (the red connection "Con B"), the internal connection stops talking (the blue connection "Con A"). I send stuff from "App 1" on the socket that never gets to "App 2". I have made a mechanism that discovers this and disconnects and then reconnects and after that I can unplug the cable all I want and "Con A" just keeps working. It's only that first time. I have confirmed having communication through "Con A" before disconnecting "Con B". I connect and reconnect exactly the same way, it's the same code, so there's no difference. What's happening? Additional information trigged by answers: PC 1 and PC 2 share addresses down to the last byte. I have an internal keep alive mechanism, I send a message and expect a response every 10 seconds. When I kill App 3, this does not happen, only when unplugging the cable.
What address are you using for "Con A"? If you are using an address that is bound to the external network adapter, even though you're talking to the same machine, then what you describe could happen. What you can do is use the address `localhost` (127.0.0.1) for "Con A", which should be completely independent of what happens on the external network.
On some platforms (windows) pulling the network cable tells the network stack to activly invalidate open socket connections associated with the interface. In this scenario pulling a network cable is actually a bad test because it provides positive feedback to your application that it may not receive in a real life situation. One common error for people to make when writing client/server applications is to not incporporate an application layer keep-alive or at least enable keepalives at the transport layer. An application recv()ing data can otherwise be forever oblivious to any failure condition until it write()s and the write fails due to transport layer timeout.
What happens to sockets when I unplug a network cable?
[ "", "c#", ".net", "sockets", "" ]
Is there anything like [`Collections.max`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Collections.html#max(java.util.Collection)) which finds the maximal value in an array for regular arrays (such as an `int[]`) in the standard Java runtime library?
No, there is no Arrays.max or a lookalike, at least in Java 6. If you look at the signature and implementation of Collections.max, it makes quite heavy use of parameterized types. In Java, generic arrays are problematic to say the least, so maybe therefore it is not a good idea to provide a generic max implementation for arrays in Java, and keep the focus on (generic) collections. Edit: as newacct correctly points out, the *usage* of generic arrays is not necessarily more problematic than the usage of generic collections, so I've edited the above text since the original was wrong. Still, the main argument of "generic arrays are problematic" is still valid in my opinion, and collections should be preferred over reference type arrays. ``` public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) { if (comp==null) return (T)max((Collection<SelfComparable>) (Collection) coll); Iterator<? extends T> i = coll.iterator(); T candidate = i.next(); while (i.hasNext()) { T next = i.next(); if (comp.compare(next, candidate) > 0) candidate = next; } return candidate; } ```
If you have an array of Objects you can use ``` Collections.max(Arrays.asList(array)); ``` If you have an array of primitive you can just use a simple loop. ``` long[] array; long max = array[0]; for(long l : array) if (max < l) max = l; ```
Maximal element in an array in Java (Collections.max() for integer arrays int[])
[ "", "java", "collections", "max", "" ]
How can I limit a result set to *n* distinct values of a given column(s), where the actual number of rows may be higher? Input table: ``` client_id, employer_id, other_value 1, 2, abc 1, 3, defg 2, 3, dkfjh 3, 1, ldkfjkj 4, 4, dlkfjk 4, 5, 342 4, 6, dkj 5, 1, dlkfj 6, 1, 34kjf 7, 7, 34kjf 8, 6, lkjkj 8, 7, 23kj ``` desired output, where limit distinct=5 distinct values of client\_id: ``` 1, 2, abc 1, 3, defg 2, 3, dkfjh 3, 1, ldkfjkj 4, 4, dlkfjk 4, 5, 342 4, 6, dkj 5, 1, dlkfj ``` Platform this is intended for is MySQL.
You can use a subselect ``` select * from table where client_id in (select distinct client_id from table order by client_id limit 5) ```
This is for SQL Server. I can't remember, MySQL may use a LIMIT keyword instead of TOP. That may make the query more efficient if you can get rid of the inner most subquery by using the LIMIT and DISTINCT in the same subquery. (It looks like Vinko used this method and that LIMIT is correct. I'll leave this here for the second possible answer though.) ``` SELECT client_id, employer_id, other_value FROM MyTable WHERE client_id IN ( SELECT TOP 5 client_id FROM ( SELECT DISTINCT client_id FROM MyTable ) SQ ORDER BY client_id ) ``` Of course, add in your own WHERE clause and ORDER BY clause in the subquery. Another possibility (compare performance and see which works out better) is: ``` SELECT client_id, employer_id, other_value FROM MyTable T1 WHERE T1.code IN ( SELECT T2.code FROM MyTable T2 WHERE (SELECT COUNT(*) FROM MyTable T3 WHERE T3,code < T2.code) < 5 ) ```
How to do equivalent of "limit distinct"?
[ "", "sql", "mysql", "" ]
I am trying to figure out how C and C++ store large objects on the stack. Usually, the stack is the size of an integer, so I don't understand how larger objects are stored there. Do they simply take up multiple stack "slots"?
The stack is a piece of memory. The stack pointer points to the top. Values can be pushed on the stack and popped to retrieve them. For example if we have a function which is called with two parameters (1 byte sized and the other 2 byte sized; just assume we have an 8-bit PC). Both are pushed on the stack this moves the stack pointer up: ``` 03: par2 byte2 02: par2 byte1 01: par1 ``` Now the function is called and the return addres is put on the stack: ``` 05: ret byte2 04: ret byte1 03: par2 byte2 02: par2 byte1 01: par1 ``` OK, within the function we have 2 local variables; one of 2 bytes and one of 4. For these a position is reserved on the stack, but first we save the stack pointer so we know where the variables start by counting up and the parameters are found by counting down. ``` 11: var2 byte4 10: var2 byte3 09: var2 byte2 08: var2 byte1 07: var1 byte2 06: var1 byte1 --------- 05: ret byte2 04: ret byte1 03: par2 byte2 02: par2 byte1 01: par1 ``` As you see, you can put anything on the stack as long as you have space left. And else you will get the phenomena that gives this site its name.
--- ## Stack and Heap are not as different as you think! --- True, some operating systems do have stack limitations. (Some of those also have nasty heap limitations too!) But this isn't 1985 any more. These days, I run Linux! My default *stacksize* is limited to 10 MB. My default *heapsize* is unlimited. It's pretty trivial to unlimit that stacksize. (\*cough\* [tcsh] *unlimit stacksize* \*cough\*. Or *setrlimit()*.) The biggest differences between *stack* and *heap* are: 1. *stack* allocations just offset a pointer (and possibly allocate new memory-pages if the stack has grown large enough). *Heap* has to search through its data-structures to find a suitable memory block. (And possibly allocate new memory pages too.) 2. *stack* goes out of scope when the current block ends. *Heap* goes out of scope when delete/free is called. 3. *Heap* can get fragmented. *Stack* never gets fragmented. Under Linux, both *stack* and *heap* are manged through virtual memory. In terms of allocation time, even heap-searching through badly fragmented memory can't hold a candle to mapping in new pages of memory. **Time-wise the differences are negligible!** Depending on your OS, oftentimes it's only when you actually use those new memory pages that they are mapped in. (**NOT** during the *malloc()* allocation!) (It's a *lazy evaluation* thing.) (*new* would invoke the constructor, which would presumably use those memory pages...) --- You can thrash the VM system by creating and destroying large objects on either the *stack* or the *heap*. It depends on your OS/compiler whether memory can/is reclaimed by the system. If it's not reclaimed, heap might be able to reuse it. (Assuming it hasn't been repurposed by another *malloc()* in the meantime.) Similarly, if stack is not reclaimed, it would just be reused. Though pages that get swapped out would need to be swapped back in, and that's going to be your biggest time-hit. --- Of all these things, **I worry about memory fragmentation the most**! Lifespan (when it goes out of scope) is always the deciding factor. But when you run programs for long periods of time, fragmentation creates a gradually increasing memory footprint. The constant swapping eventually kills me! --- --- --- ## AMENDED TO ADD: --- ## Man, I have been spoiled! Something just wasn't adding up here... I figured either \*I\* was way the hell off base. Or everyone else was. Or, more likely, both. Or, just maybe, neither. Whatever the answer, I had to know what was going on! ...This is going to be long. Bear with me... --- I've spend most of the last 12 years working under Linux. And about 10 years before that under various flavors of Unix. My perspective on computers is somewhat biased. I have been spoiled! I've done a little with Windows, but not enough to speak authoritatively. Nor, tragically, with Mac OS/Darwin either... Though Mac OS/Darwin/BSD is close enough that some of my knowledge carries over. --- With 32-bit pointers, you run out of address space at 4 GB (2^32). Practically speaking, *STACK*+*HEAP* combined is [usually limited to somewhere between 2-4 GB as other things need to get mapped in there.](http://www.cdf.utoronto.ca/~csc369h/summer/lectures/week11-linuxvm.pdf) (There's shared memory, shared libraries, memory-mapped files, the executable image your running is always nice, etc.) --- Under Linux/Unix/MacOS/Darwin/BSD, you can artificially constrain the *HEAP* or the *STACK* to whatever arbitrary values you want at runtime. But ultimately there is a hard system limit. This is the distinction (in tcsh) of *"limit"* vs *"limit -h"*. Or (in bash) of *"ulimit -Sa"* vs *"ulimit -Ha"*. Or, programmatically, of *rlim\_cur* vs *rlim\_max* in *struct rlimit*. --- Now we get to the fun part. With respect to ***Martin York's Code***. (Thank you *Martin*! Good example. Always good to try things out!.) *Martin's* presumably running on a Mac. (A fairly recent one. His compiler build is newer than mine!) Sure, his code won't run on his Mac by default. But it will run just fine if he first invokes *"unlimit stacksize"* (tcsh) or *"ulimit -Ss unlimited"* (bash). --- ## THE HEART OF THE MATTER: --- Testing on an ancient (obsolete) Linux RH9 2.4.x kernel box, allocating large amounts of *STACK*   **OR**   *HEAP*, either one by itself tops out between 2 and 3 GB. (Sadly, the machine's RAM+SWAP tops out at a little under 3.5 GB. It's a 32-bit OS. And this is **NOT** the only process running. We make do with what we have...) **So there really are no limitations on *STACK* size vs *HEAP* size under Linux, other than the artificial ones...** --- ## BUT: --- On a Mac, there's a hard stacksize limit of **65532 kilobytes**. It has to do with how thing are laid out in memory. --- [Normally, you think of an idealized system as having *STACK* at one end of the memory address space, *HEAP* at the other, and they build towards each other. When they meet, you are out of memory.](http://www.cdf.utoronto.ca/~csc369h/summer/lectures/week11-linuxvm.pdf) Macs appear to stick their *Shared system libraries* in between at a fixed offset limiting both sides. You can still run ***Martin York's Code*** with "unlimit stacksize", since he's only allocating something like 8 MiB (< 64 MiB) of data. **But he'll run out of *STACK* long before he runs out of *HEAP*.** **I'm on Linux. I won't.** [Sorry kid. Here's a Nickel. Go get yourself a better OS.](https://stackoverflow.com/questions/84556/whats-your-favorite-programmer-cartoon#88675) [There are workarounds for the Mac. But they get ugly and messy and involve tweaking the kernel or linker parameters.](http://homepage.mac.com/eric.c/hpc/contents/documentation/How%20to%20increase%20the%20stack%20size%20on%20Mac%20OS%20X.pdf) In the long run, unless Apple does something really dumb, 64-bit address spaces will render this whole stack-limitation thing obsolete sometime Real Soon Now. --- ## Moving on to Fragmentation: --- Anytime you push something onto the *STACK*   it's appended to the end. And it's removed (rolled back) whenever the current block exits. As a result, there are no holes in the *STACK*. It's all one big solid block of used memory. With perhaps just a little unused space at the very end all ready for reuse. In contrast, as *HEAP* is allocated and free'd, you wind up with unused-memory holes. These can gradually lead to an increased memory footprint over time. Not what we usually mean by a core leak, but the results are similar. Memory Fragmentation is **NOT** a reason to avoid *HEAP* storage. It's just something to be aware of when you're coding. --- ## Which brings up **SWAP THRASHING**: --- * If you already have a large amount of heap allocated / in use. * If you have lots of fragmented holes scattered about. * And if you have a large number of small allocations. Then you can wind up with a large number of variables, all utilized within a small localized region of the code, that are scattered across a great many virtual memory pages. (As in you are using 4 bytes on this 2k page, and 8 bytes on that 2k page, and so on for a whole lot of pages...) All of which means that your program needs to have a large number of pages swapped in to run. Or it's going to swapping pages in and out constantly. (We call that thrashing.) On the other hand, had these small allocations been made on the *STACK*, they would all be located in a contiguous stretch of memory. Fewer VM memory pages would need to be loaded. (4+8+... < 2k for the win.) > *Sidenote: My reason for calling attention to this stems from a certain electrical engineer I knew who insisted that all arrays be allocated on the HEAP. We were doing matrix math for graphics. A \*LOT\* of 3 or 4 element arrays. Managing new/delete alone was a nightmare. Even abstracted away in classes it caused grief!* --- ## Next topic. Threading: --- Yes, threads are limited to very tiny stacks by default. You can change that with pthread\_attr\_setstacksize(). Though depending on your threading implementation, if multiple threads are sharing the same 32 bit address space, **large individual per-thread stacks will be a problem!** There just ain't that much room! Again, transitioning to 64-bit address spaces (OS's) will help. ``` pthread_t threadData; pthread_attr_t threadAttributes; pthread_attr_init( & threadAttributes ); ASSERT_IS( 0, pthread_attr_setdetachstate( & threadAttributes, PTHREAD_CREATE_DETACHED ) ); ASSERT_IS( 0, pthread_attr_setstacksize ( & threadAttributes, 128 * 1024 * 1024 ) ); ASSERT_IS( 0, pthread_create ( & threadData, & threadAttributes, & runthread, NULL ) ); ``` --- ## With respect to *Martin York's* Stack Frames: --- Perhaps you and I are thinking of different things? When I think of a *stack frame*, I think of a call stack. Each function or method has its own *stack frame* consisting of the return address, arguments, and local data. I've never seen any limitations on the size of a *stack frame*. There are limitations on the *STACK* as a whole, but that's all the *stack frames* combined. [There's a nice diagram and discussion of *stack frames* over on Wiki.](http://en.wikipedia.org/wiki/Call_stack#Structure) --- ## On a final note: --- Under Linux/Unix/MacOS/Darwin/BSD, it is possible to change the maximum *STACK* size limitations programmatically as well as *limit*(tcsh) or *ulimit*(bash): ``` struct rlimit limits; limits.rlim_cur = RLIM_INFINITY; limits.rlim_max = RLIM_INFINITY; ASSERT_IS( 0, setrlimit( RLIMIT_STACK, & limits ) ); ``` Just don't try to set it to INFINITY on a Mac... And change it before you try to use it. ;-) --- ## Further reading: --- * <http://www.informit.com/content/images/0131453483/downloads/gorman_book.pdf> * <http://www.redhat.com/magazine/001nov04/features/vm/> * <http://dirac.org/linux/gdb/02a-Memory_Layout_And_The_Stack.php> * <http://people.redhat.com/alikins/system_tuning.html> * <http://pauillac.inria.fr/~xleroy/linuxthreads/faq.html> * <http://www.kegel.com/stackcheck/> ---
How do C and C++ store large objects on the stack?
[ "", "c++", "c", "memory", "stack", "" ]
Python provides a nice method for getting length of an eager iterable, `len(x)` that is. But I couldn't find anything similar for lazy iterables represented by generator comprehensions and functions. Of course, it is not hard to write something like: ``` def iterlen(x): n = 0 try: while True: next(x) n += 1 except StopIteration: pass return n ``` But I can't get rid of a feeling that I'm reimplementing a bicycle. (While I was typing the function, a thought struck my mind: maybe there really is no such function, because it "destroys" its argument. Not an issue for my case, though). P.S.: concerning the first answers - yes, something like `len(list(x))` would work too, but that drastically increases the usage of memory. P.P.S.: re-checked... Disregard the P.S., seems I made a mistake while trying that, it works fine. Sorry for the trouble.
There isn't one because you can't do it in the general case - what if you have a lazy infinite generator? For example: ``` def fib(): a, b = 0, 1 while True: a, b = b, a + b yield a ``` This never terminates but will generate the Fibonacci numbers. You can get as many Fibonacci numbers as you want by calling `next()`. If you really need to know the number of items there are, then you can't iterate through them linearly one time anyway, so just use a different data structure such as a regular list.
The easiest way is probably just `sum(1 for _ in gen)` where gen is your generator.
Length of generator output
[ "", "python", "generator", "iterable", "" ]
How can I detect which CPU is being used at runtime ? The c++ code needs to differentiate between AMD / Intel architectures ? Using gcc 4.2.
If you're on Linux (or on Windows running under Cygwin), you can figure that out by reading the special file `/proc/cpuinfo` and looking for the line beginning with `vendor_id`. If the string is `GenuineIntel`, you're running on an Intel chip. If you get `AuthenticAMD`, you're running on an AMD chip. ``` void get_vendor_id(char *vendor_id) // must be at least 13 bytes { FILE *cpuinfo = fopen("/proc/cpuinfo", "r"); if(cpuinfo == NULL) ; // handle error char line[256]; while(fgets(line, 256, cpuinfo)) { if(strncmp(line, "vendor_id", 9) == 0) { char *colon = strchr(line, ':'); if(colon == NULL || colon[1] == 0) ; // handle error strncpy(vendor_id, 12, colon + 2); fclose(cpuinfo); return; } } // if we got here, handle error fclose(cpuinfo); } ``` If you know you're running on an x86 architecture, a less portable method would be to use the CPUID instruction: ``` void get_vendor_id(char *vendor_id) // must be at least 13 bytes { // GCC inline assembler __asm__ __volatile__ ("movl $0, %%eax\n\t" "cpuid\n\t" "movl %%ebx, %0\n\t" "movl %%edx, %1\n\t" "movl %%ecx, %2\n\t" : "=m"(vendor_id), "=m"(vendor_id + 4), "=m"(vendor_id + 8) // outputs : // no inputs : "%eax", "%ebx", "%edx", "%ecx", "memory"); // clobbered registers vendor_id[12] = 0; } int main(void) { char vendor_id[13]; get_vendor_id(vendor_id); if(strcmp(vendor_id, "GenuineIntel") == 0) ; // it's Intel else if(strcmp(vendor_id, "AuthenticAMD") == 0) ; // it's AMD else ; // other return 0; } ```
The `cpuid` instruction, used with `EAX=0` will return a 12-character vendor string in `EBX`, `EDX`, `ECX`, in that order. For Intel, this string is "GenuineIntel". For AMD, it's "AuthenticAMD". Other companies that have created x86 chips have their own strings.The [Wikipedia page](http://en.wikipedia.org/wiki/CPUID) for `cpuid` has many (all?) of the strings listed, as well as an example ASM listing for retrieving the details. You really only need to check if ECX matches the last four characters. You can't use the first four, because some Transmeta CPUs also start with "Genuine" * For Intel, this is `0x6c65746e` * For AMD, this is `0x444d4163` If you convert each byte in those to a character, they'll appear to be backwards. This is just a result of the little endian design of x86. If you copied the register to memory and looked at it as a string, it would work just fine. Example Code: ``` bool IsIntel() // returns true on an Intel processor, false on anything else { int id_str; // The first four characters of the vendor ID string __asm__ ("cpuid":\ // run the cpuid instruction with... "=c" (id_str) : // id_str set to the value of EBX after cpuid runs... "a" (0) : // and EAX set to 0 to run the proper cpuid function. "eax", "ebx", "edx"); // cpuid clobbers EAX, ECX, and EDX, in addition to EBX. if(id_str==0x6c65746e) // letn. little endian clobbering of GenuineI[ntel] return true; else return false; } ``` EDIT: One other thing - this can easily be changed into an `IsAMD` function, `IsVIA` function, `IsTransmeta` function, etc. just by changing the magic number in the `if`.
How to detect what CPU is being used during runtime?
[ "", "c++", "gcc", "cpu", "" ]
I'm working on making a simple server application with python, and I'm trying to get the IP to bind the listening socket to. An example I looked at uses this: ``` HOST = gethostbyaddr(gethostname()) ``` With a little more processing after this, it should give me just the host IP as a string. This should return the IPv4 address. But when I run this code, it returns my IPv6 address. Why does it do this and how can I get my IPv4 address? If its relevant, I'm using windows vista and python 2.5
Getting your IP address is harder than you might think. Check [this answer](https://stackoverflow.com/questions/270745/how-do-i-determine-all-of-my-ip-addresses-when-i-have-multiple-nics#274644) I gave for the one reliable way I've found. Here's what the answer says in case you don't like clicking on things: Use the [`netifaces`](http://alastairs-place.net/netifaces/) module. Because networking is complex, using netifaces can be a little tricky, but here's how to do what you want: ``` >>> import netifaces >>> netifaces.interfaces() ['lo', 'eth0'] >>> netifaces.ifaddresses('eth0') {17: [{'broadcast': 'ff:ff:ff:ff:ff:ff', 'addr': '00:11:2f:32:63:45'}], 2: [{'broadcast': '10.0.0.255', 'netmask': '255.255.255.0', 'addr': '10.0.0.2'}], 10: [{'netmask': 'ffff:ffff:ffff:ffff::', 'addr': 'fe80::211:2fff:fe32:6345%eth0'}]} >>> for interface in netifaces.interfaces(): ... print netifaces.ifaddresses(interface)[netifaces.AF_INET] ... [{'peer': '127.0.0.1', 'netmask': '255.0.0.0', 'addr': '127.0.0.1'}] [{'broadcast': '10.0.0.255', 'netmask': '255.255.255.0', 'addr': '10.0.0.2'}] >>> for interface in netifaces.interfaces(): ... for link in netifaces.ifaddresses(interface)[netifaces.AF_INET]: ... print link['addr'] ... 127.0.0.1 10.0.0.2 ``` This can be made a little more readable like this: ``` from netifaces import interfaces, ifaddresses, AF_INET def ip4_addresses(): ip_list = [] for interface in interfaces(): for link in ifaddresses(interface)[AF_INET]: ip_list.append(link['addr']) return ip_list ``` If you want IPv6 addresses, use `AF_INET6` instead of `AF_INET`. If you're wondering why `netifaces` uses lists and dictionaries all over the place, it's because a single computer can have multiple NICs, and each NIC can have multiple addresses, and each address has its own set of options.
IPv6 is taking precedence over IPv4 as it's the newer family, it's generally what you want if your hostname is associated with multiple families. You should be using [getaddrinfo](http://docs.python.org/library/socket.html#socket.getaddrinfo) for family independent resolution, here is an example, ``` import sys, socket; host = socket.gethostname(); result = socket.getaddrinfo(host, None); print "family:%i socktype:%i proto:%i canonname:%s sockaddr:%s"%result[0]; result = socket.getaddrinfo(host, None, socket.AF_INET); print "family:%i socktype:%i proto:%i canonname:%s sockaddr:%s"%result[0]; result = socket.getaddrinfo(host, None, socket.AF_INET6); print "family:%i socktype:%i proto:%i canonname:%s sockaddr:%s"%result[0]; ``` Which on a dual-stack configured host gives me the following, ``` family:10 socktype:1 proto:6 canonname: sockaddr:('2002:dce8:d28e::31', 0, 0, 0) family:2 socktype:1 proto:6 canonname: sockaddr:('10.6.28.31', 0) family:10 socktype:1 proto:6 canonname: sockaddr:('2002:dce8:d28e::31', 0, 0, 0) ```
Why does gethostbyaddr(gethostname()) return my IPv6 IP?
[ "", "python", "sockets", "ip-address", "ipv6", "ipv4", "" ]
What do people here use C++ Abstract Base Class constructors for in the field? I am talking about pure interface classes having no data members and no non-pure virtual members. Can anyone demonstrate any idioms which use ABC constructors in a useful way? Or is it just intrinsic to the nature of using ABCs to implement interfaces that they remain empty, inline and protected?
> Can anyone demonstrate any idioms which use ABC constructors in a useful way? Here's an example, although it's a contrived, uncommon example. You might use it to keep a list of all instances: ``` class IFoo { private: //static members to keep a list of all constructed instances typedef std::set<IFoo*> Set; static Set s_set; protected: //new instance being created IFoo() { s_set.insert(this); } public: //instance being destroyed virtual ~IFoo() { s_set.remove(this); } ... plus some other static method and/or property which accesses the set of all instances ... }; ``` > Or is it just intrinsic to the nature of using ABCs to implement interfaces that they remain empty, inline and protected? More usually they're just not declared at all! There's no reason to declare them: * Empty and inline => why bother to declare it? * Protected => the ABC probably already has some **pure virtual** methods and therefore already can't be instantiated except as a subclass.
Suppose that there is some behavior that is common for all the derived classes. Such as registering itself in some external registry, or checking validity of something. All this common code can be placed in base class's constructor, and it will be called implicitly from the constructors of each of the derived classes.
What do *you* use C++ ABC constructors for?
[ "", "c++", "constructor", "abstract-base-class", "interface-design", "" ]
I'm not good with JavaScript, and this is Google's code. I'm getting a object expected on this, which seems to work fine in other places. It's the 3rd to the last line (the one with `utmSetVar`). ``` <HTML> <HEAD> </HEAD> <BODY > <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> try { var pageTracker = _gat._getTracker("UA-159907-14"); pageTracker._trackPageview(); } catch(err) {} </script> <script type="text/javascript">__utmSetVar('aff/VG-CEGBWI');</script> </BODY> </HTML> ```
The utmSetVar function is a one that was available in the old Google Analytics codebase using the "urchin" tracker. <http://www.google-analytics.com/urchin.js> You can use the following to determine which one you are using <http://www.google.com/support/googleanalytics/bin/answer.py?answer=75129> In order to solve your problem you will need to either revert to the old tracking style (easy hack solution) or to consult the google site on the newest method of achieving what you are after.
The correct code was: ``` <script type="text/javascript">pageTracker._setVar('aff/undefined');</script> ```
javascript object expected
[ "", "javascript", "internet-explorer", "" ]
I'm trying to figure out how to exclude items from a select statement from table A using an exclusion list from table B. The catch is that I'm excluding based on the prefix of a field. So a field value maybe "FORD Muffler" and to exclude it from a basic query I would do: ``` SELECT FieldName FROM TableName WHERE UPPER(ColumnName) NOT LIKE 'FORD%' ``` But to use a list of values to exclude from a different tabel I would use a Subquery like: ``` SELECT FieldName FROM TableName WHERE UPPER(ColumnName) NOT IN (Select FieldName2 FROM TableName2) ``` The problem is that it only excludes exact matches and not LIKE or Wildcards (%). How can I accomplish this task? Redesigning the table isn't an option as it is an existing table in use. EDIT: Sorry I am using SQL Server (2005).
I think this will do it: ``` SELECT FieldName FROM TableName LEFT JOIN TableName2 ON UPPER(ColumnName) LIKE TableName2.FieldName2 + '%' WHERE TableName2.FieldName2 IS NULL ```
Dunno how efficient this would be, but it should work: ``` SELECT FieldName FROM TableName t1 WHERE NOT EXISTS ( SELECT * FROM TableName2 t2 WHERE t1.FieldName LIKE t2.FieldName2 + '%' ) ```
SQL Exclude LIKE items from table
[ "", "sql", "subquery", "" ]
I have a file containing several lines similar to: ``` Name: Peter Address: St. Serrano número 12, España Country: Spain ``` And I need to extract the address using a regular expression, taking into account that it can contain dots, special characters (ñ, ç), áéíóú... The current code works, but it looks quite ugly:. ``` Pattern p = Pattern.compile("^(.+?)Address: ([a-zA-Z0-9ñÑçÇáéíóú., ]+)(.+?)$", Pattern.MULTILINE | Pattern.DOTALL); Matcher m = p.matcher(content); if (m.matches()) { ... } ``` **Edit: The Address field could also be divided into multiple lines** ``` Name: Peter Address: St. Serrano número 12, Madrid España Country: Spain ``` Edit: I can't use a Properties object or a YAML parser, as the file contains other kind of information, too.
I don't know Java's regex objects that well, but something like this pattern will do it: ``` ^Address:\s*((?:(?!^\w+:).)+)$ ``` assuming multiline and dotall modes are on. This will match any line starting with Address, followed by anything until a newline character and a single word followed by a colon. If you know the next field has to be "Country", you can simplify this a little bit: ``` ^Address:\s*((?:(?!^Country:).)+)$ ``` The trick is in the lookahead assertion in the repeating group. '(?!Country:).' will match everything except the start of the string 'Country:', so we just stick it in noncapturing parentheses (?:...) and quantify it with +, then group all of that in normal capturing parentheses.
Assuming "content" is a string containing the file's contents, your main problem is that you're using `matches()` where you should be using `find()`. ``` Pattern p = Pattern.compile("^Address:\\s*(.*)$", Pattern.MULTILINE); Matcher m = p.matcher(content); if ( m.find() ) { ... } ``` There seems to be some confusion in other answers about MULTLINE and DOTALL modes. MULTILINE is what lets the `^` and `$` anchors match the beginning and end, respectively, of a logical line. DOTALL lets the dot (period, full stop, whatever) match line separator characters like `\n` (linefeed) and `\r` (carriage return). This regex **must** use MULTILINE mode and **must not** use DOTALL mode.
Regular Expression to extract label-value pairs in Java
[ "", "java", "regex", "" ]
I would like to be able to perform SQL queries on my e-mail inbox. With the output, I can make graphs about how much e-mails I send or receive for example. I want to analyze my performance and what keeps me busy. My mailbox seems like a good place to start. I'm using Gmail on-line, and Thunderbird, Outlook 2007 and Mail.app trough IMAP. Is there an easy way how I can connect one of those apps with something I can SQL to? Allready tried: * Thunderbird does not have an add-on for this (or I couldn’t find it). * I suspect Outlook to be able to do something together with MS Access, but I wouldn't know how. * None of my client seems to be able to export everyting to something useful, like CVS or Excel's .xls. From there on, I can import to Access and done. UPDATE: Access 2007 does have a wizard on connecting to outlook. But when I run it, Office starts for no reaston to complain that Outlook 2007 is not found (?). UPDATE 2: You can fix this by setting Outlook as the default e-mail client, closing outlook and starting it again.
You can simply connect Outlook to Access via Access Wizards or code (<http://support.microsoft.com/kb/209946/en-us>)
You can parse mbox files (which Thunderbird uses to store it's messages) using any number of scripts like [this](http://blog.devayd.com/2008/07/copy-messages-from-a-thunderbird-mbox-file-to-a-mysql-table-using-php/) then do any sql on the messages you like.
SQL in an e-mail app
[ "", "sql", "ms-access", "email", "outlook", "thunderbird", "" ]
Currently, I only know a way of doing RPC for POJOs in Java, and is with the very complex EJB/JBoss solution. Is there any better way of providing a similar functionality with a thiner layer (within or without a Java EE container), using RMI or something that can serialize and send full blown objects over the wire? I'm not currently interested in HTTP/JSON serialization BTW. *EDIT*: For clarification: I'm trying to replace an old EJB 2.1/JBoss 4 solution with something more easy to manage at the container level. I need to have entire control over the database(planning to use iBATIS which would allow me to use fairly complex SQL very easily), but the only things I want to keep over the wire are: * Invocation of lookup/data modification methods (automagic serialization goes here). * Transparent session control (authentication/authorization). I still have to see how to accomplish this. Both items have to work as a whole, of course. No access should be granted to users without credentials. Because I'm not very fond of writing webapps, I plan to build a GUI (Swing or SWT) that would only manage POJOs, do some reporting and invoke methods from the container. I want the serialization to be as easy as possible.
As is nearly always the case, [Spring](http://www.springsource.org/) comes to the rescue. From the [reference documentation](http://static.springframework.org/spring/docs/2.5.x/reference/index.html), you will want to read [Chapter 17. Remoting and web services using Spring](http://static.springframework.org/spring/docs/2.5.x/reference/remoting.html). There are several methods to choose from. The beauty of Spring is that all your interfaces and implementations are vanilla POJOs. The wiring into RMI or whatever is handled by Spring. You can: 1. [Export services using RMI](http://static.springframework.org/spring/docs/2.5.x/reference/remoting.html#remoting-rmi): probably the simplest approach; 2. [Use HTTP invoker](http://static.springframework.org/spring/docs/2.5.x/reference/remoting.html#remoting-httpinvoker): if remote access is an issue, this might be better for firewalls, etc than pure RMI; or 3. [Use Web Services](http://static.springframework.org/spring/docs/2.5.x/reference/remoting.html#remoting-web-services), in which case I would favour [JAX-WS over JAX-RPC](http://www.ibm.com/developerworks/webservices/library/ws-tip-jaxwsrpc.html). Spring has the additional benefit in that it can do the wiring for both the server and the client, easily and transparently. Personally I would choose either (2) or (3). HTTP is network friendly. It's easy to deploy in a Web container. [Jetty](http://www.mortbay.org/jetty/)'s long-lived connections give you the option over server push (effectively) over HTTP. All of these methods allow complex objects to be sent across the wire but they are subtly different in this regard. You need to consider if your server and client are going to be distributed separately and whether it's an issue if you change the interface that you need to redistribute the class files. Or you can use a customized serialization solution (even XML) to avoid this. But that has issues as well. Using a Web container will allow you to easily plug-in [Spring Security](http://static.springframework.org/spring-security/site/), which can be a bit daunting at first just because there are so many options. Also, `HttpSession` can be used to provide state information between requests.
Simple RPC is exactly what RMI was built for. If you make a serializable interface, you can call methods on one app from another app.
Simpler-than-JBoss way to have POJO RPC in Java with container session management
[ "", "java", "serialization", "jboss", "distributed", "rmi", "" ]
Hey all - I have an app where I'm authenticating the user. They pass username and password. I pass the username and password to a class that has a static method. For example it'm calling a method with the signature below: ``` public class Security { public static bool Security.Member_Authenticate (string username, string password) { //do stuff} } ``` If I have 1000 people hitting this at once, will I have any problems with the returns of the method bleeding into others? I mean, since the methods are static, will there be issues with the a person getting authenticated when in fact they shouldn't be but the person before them was successfully authenticated ASP.Net returns a mismatched result due to the method being static? I've read of issues with static properties vs viewstate but am a bit confused on static methods. If this is a bad way of doing this,what's the prefered way?
This will not happen. When a method is Static (or Shared in VB.NET), then you're safe as long as the method doesn't rely on anything other than the inputs to figure something out. As long as you're not modifying any public variables or objects from anywhere else, you're fine.
A static method is just fine as long as it is not using any of persistent data between successive calls. I am guessing that your method simply runs a query on the database and returns true/false based on that. In this scenario, I think the static method should work without a problem, regardless of how many calls you make to it.
Static methods in a class - okay in this situation?
[ "", "c#", "asp.net", "asp.net-2.0", "" ]
I am looking to develop an audio player in C#, but was wondering what libraries are available for playback. I am looking for a free library that allows for an extensive list of audio formats to be played (for example mp3, wma, wav, ogg, etc.) Thats pretty much the basic functionality I would need. But if I could get picky, a library that can convert audio files between the formats would be handy. Doing a google search I came across the alvas.audio library, but it wasn't free. The VLC library would be nice too, but I couldn't get it to work, and I'd prefer to just package my application with a dll instead of having my users have the VLC software installed on their machine as well. Thanks for any tips or advice on this.
[Bass Audio Library](http://www.un4seen.com/) is one option.
[NAudio](https://github.com/naudio/NAudio) is an open source .NET audio library that can play back WAV, MP3, WMA, AAC and AIFF files, making use of ACM or Media Foundation codecs installed on your computer for decompression purposes. For ogg support, there is an [add-on nuget package](https://nuget.org/packages/NVorbis.NAudioSupport) you can use. (**Edit:** updated with details of supported audio file types in NAudio 1.7. Also, full disclosure: I am the author of this library)
C# Audio Library
[ "", "c#", "audio", "" ]
I don't think this is possible with just regular expressions, but I'm not an expert so i thought it was worth asking. I'm trying to do a massive search and replace of C# code, using .NET regex. What I want to do is find a line of code where a specific function is called on a variable that is of type DateTime. e.g: ``` axRecord.set_Field("CreatedDate", m_createdDate); ``` and I would know that it's a DateTime variable b/c earlier in that code file would be the line: ``` DateTime m_createdDate; ``` but it seems that I can't use a named group in negative lookbehind like: ``` (?<=DateTime \k<1>.+?)axRecord.set_[^ ]+ (?<1>[^ )]+) ``` and if I try to match the all the text between the variable declaration and the function call like this: ``` DateTime (?<1>[^;]+).+?axRecord.set.+?\k<1> ``` it will find the first match - first based on first variable declared - but then it can't find any other matches, because the code is laid out like this: ``` DateTime m_First; DateTime m_Second; ... axRecord.set_Field("something", m_First); axRecord.set_Field("somethingElse", m_Second); ``` and the first match encompasses the second variable declaration. Is there a good way to do this with just regular expressions, or do I have to resort to scripting in my logic?
Try this: ``` @"(?s)set_Field\(""[^""]*"",\s*(?<vname>\w+)(?<=\bDateTime\s+\k<vname>\b.+)" ``` By doing the lookbehind first, you're forcing the regex to search for the method calls in a particular order: the order in which the variables are declared. What you want to do is match a likely-looking method call first, then use the lookbehind to verify the type of the variable. I just made a rough guess at the part that matches the method call. Like the others have said, whatever regex you use is going to have to be tailored to your code; there's no general solution.
Have a look at my answer to this question [Get a methods contents from a C# file](https://stackoverflow.com/questions/261741/get-a-methods-contents-from-a-cs-file#261861) It gives links to pages that show how to use the built in .net language parser to do this simply and reliably (i.e. not by asking "what looks like the usage I'm searching for", but by properly parsing the code with VS code parsing tools). I know it's not a RegEx answer, but I don't think RegEx is the answer.
regular expression lookaround
[ "", "c#", ".net", "regex", "" ]
I am attempting to create a small application to collect data received from an external sensor attached to COM10. I have successfully created a small C# console object and application that opens the port and streams data to a file for a fixed period of time using a for-loop. I would like to convert this application to use the dataReceived event to stream instead. After reading the [Top 5 SerialPort Tips](http://blogs.msdn.com/bclteam/archive/2006/10/10/Top-5-SerialPort-Tips-_5b00_Kim-Hamilton_5D00_.aspx), I still can't seem to get this to work and don't know what I am missing. I rewrote the console application so that all the code is in Main and is pasted below. Can someone please help enlighten me as to why the event handler port\_OnReceiveDatazz is not being called even though I know that there is data being sent to the port by the hardware? *Thanks* Thanks to [@Gabe](https://stackoverflow.com/questions/466474/how-do-i-use-datareceived-event-of-the-serialport-port-object-in-c#466577), [@Jason Down](https://stackoverflow.com/questions/466474/how-do-i-use-datareceived-event-of-the-serialport-port-object-in-c#466510), and [@abatishchev](https://stackoverflow.com/questions/466474/how-do-i-use-datareceived-event-of-the-serialport-port-object-in-c#466518) for all the suggestions. I am stumped and can't seem to get the event handler to work. Perhaps it has something to do with the device. I can live with just reading the port in a thread and streaming the data straight to file. --- **Code** --- ``` namespace serialPortCollection { class Program { static void Main(string[] args) { const int bufSize = 2048; Byte[] buf = new Byte[bufSize]; //To store the received data. SerialPort sp = new SerialPort("COM10", 115200); sp.DataReceived += port_OnReceiveDatazz; // Add DataReceived Event Handler sp.Open(); sp.WriteLine("$"); //Command to start Data Stream // Wait for data or user input to continue. Console.ReadLine(); sp.WriteLine("!"); //Stop Data Stream Command sp.Close(); } // My Event Handler Method private static void port_OnReceiveDatazz(object sender, SerialDataReceivedEventArgs e) { SerialPort spL = (SerialPort) sender; const int bufSize = 12; Byte[] buf = new Byte[bufSize]; Console.WriteLine("DATA RECEIVED!"); Console.WriteLine(spL.Read(buf, 0, bufSize)); } } } ```
~~I think your issue is the line:~~\*\* ~~sp.DataReceived += port\_OnReceiveDatazz;~~ ~~Shouldn't it be:~~ ~~sp.DataReceived += new SerialDataReceivedEventHandler (port\_OnReceiveDatazz);~~ \*\*Nevermind, the syntax is fine (didn't realize the shortcut at the time I originally answered this question). I've also seen suggestions that you should turn the following options on for your serial port: ``` sp.DtrEnable = true; // Data-terminal-ready sp.RtsEnable = true; // Request-to-send ``` You may also have to set the handshake to RequestToSend (via the handshake enumeration). --- **UPDATE:** Found a suggestion that says you should open your port first, then assign the event handler. Maybe it's a bug? So instead of this: ``` sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz); sp.Open(); ``` Do this: ``` sp.Open(); sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz); ``` Let me know how that goes.
First off I recommend you use the following constructor instead of the one you currently use: ``` new SerialPort("COM10", 115200, Parity.None, 8, StopBits.One); ``` Next, you really should remove this code: ``` // Wait 10 Seconds for data... for (int i = 0; i < 1000; i++) { Thread.Sleep(10); Console.WriteLine(sp.Read(buf,0,bufSize)); //prints data directly to the Console } ``` And instead just loop until the user presses a key or something, like so: ``` namespace serialPortCollection { class Program { static void Main(string[] args) { SerialPort sp = new SerialPort("COM10", 115200); sp.DataReceived += port_OnReceiveDatazz; // Add DataReceived Event Handler sp.Open(); sp.WriteLine("$"); //Command to start Data Stream Console.ReadLine(); sp.WriteLine("!"); //Stop Data Stream Command sp.Close(); } // My Event Handler Method private static void port_OnReceiveDatazz(object sender, SerialDataReceivedEventArgs e) { SerialPort spL = (SerialPort) sender; byte[] buf = new byte[spL.BytesToRead]; Console.WriteLine("DATA RECEIVED!"); spL.Read(buf, 0, buf.Length); foreach (Byte b in buf) { Console.Write(b.ToString()); } Console.WriteLine(); } } } ``` Also, note the revisions to the data received event handler, it should actually print the buffer now. **UPDATE 1** --- I just ran the following code successfully on my machine (using a null modem cable between COM33 and COM34) ``` namespace TestApp { class Program { static void Main(string[] args) { Thread writeThread = new Thread(new ThreadStart(WriteThread)); SerialPort sp = new SerialPort("COM33", 115200, Parity.None, 8, StopBits.One); sp.DataReceived += port_OnReceiveDatazz; // Add DataReceived Event Handler sp.Open(); sp.WriteLine("$"); //Command to start Data Stream writeThread.Start(); Console.ReadLine(); sp.WriteLine("!"); //Stop Data Stream Command sp.Close(); } private static void port_OnReceiveDatazz(object sender, SerialDataReceivedEventArgs e) { SerialPort spL = (SerialPort) sender; byte[] buf = new byte[spL.BytesToRead]; Console.WriteLine("DATA RECEIVED!"); spL.Read(buf, 0, buf.Length); foreach (Byte b in buf) { Console.Write(b.ToString() + " "); } Console.WriteLine(); } private static void WriteThread() { SerialPort sp2 = new SerialPort("COM34", 115200, Parity.None, 8, StopBits.One); sp2.Open(); byte[] buf = new byte[100]; for (byte i = 0; i < 100; i++) { buf[i] = i; } sp2.Write(buf, 0, buf.Length); sp2.Close(); } } } ``` **UPDATE 2** --- Given all of the traffic on this question recently. I'm beginning to suspect that either your serial port is not configured properly, or that the device is not responding. I highly recommend you attempt to communicate with the device using some other means (I use hyperterminal frequently). You can then play around with all of these settings (bitrate, parity, data bits, stop bits, flow control) until you find the set that works. The documentation for the device should also specify these settings. Once I figured those out, I would make sure my .NET SerialPort is configured properly to use those settings. Some tips on configuring the serial port: Note that when I said you should use the following constructor, I meant that use that function, not necessarily those parameters! You should fill in the parameters for your device, the settings below are common, but may be different for your device. ``` new SerialPort("COM10", 115200, Parity.None, 8, StopBits.One); ``` It is also important that you setup the .NET SerialPort to use the same flow control as your device (as other people have stated earlier). You can find more info here: <http://www.lammertbies.nl/comm/info/RS-232_flow_control.html>
How do I use dataReceived event of the SerialPort Port Object in C#?
[ "", "c#", "serial-port", "" ]
In an ASP.NET (2.0) application I use FormsAuthentication. In the Global.asax / Application\_AuthenticateRequest method I check if HttpContext.Current.User is null. Is this enough to know if the forms authentication cookie exists, the ticket is not expired, and overall, that the forms authentication mechanism has done its job to validate the user? I need this, because I have certain pages in that application, which sometimes do not need authentication to be accessed (based on some criteria), and I put them in a separate "location" directive in web.config with in order to exclude them from "catch all" forms authentication. I.e. I'm trying to check in Application\_AuthenticateRequest if the page accessed in this "location" needs protection or not, and if yes, to know if the user have been authenticated already, or I need to redirect to Logon. EDIT: As the answers suggest, most probably I'll go with IsAuthenticated. In order for me to grasp it better, here are 2 bonus questions :) (please, edit other answers to add these, thanks) : 1. Can I assume that if IsAuthenticated is true, then HttpContext.Current.User will for sure contain the username for the authenticated user? 2. How can I end up with an "anonymous user" in HttpContext.Current.User, if FormsAuthentication is enforced, and only few pages are excluded with "location" directive?
No, the `User` could just be a reference to the anonymous user. Check [`HttpContext.Current.Request.IsAuthenticated`](http://msdn.microsoft.com/en-us/library/system.web.httprequest.isauthenticated.aspx).
I usually use Request.IsAuthenticated. I couldn't tell you whether your approach should work or not. It sounds like it should, although it might have side effects if you support anonymous logins?
Is (HttpContext.Current.User != null) enough to assume that FormsAuthentication has authenticated the user
[ "", "c#", ".net", "asp.net", ".net-2.0", "forms-authentication", "" ]
(code examples are python) Lets assume we have a list of percentages that add up to 100: ``` mylist = [2.0, 7.0, 12.0, 35.0, 21.0, 23.0] ``` Some values of mylist may be changed, others must stay fixed. Lets assume the first 3 (2.0, 7.0, 12.0) must stay fixed and the last three (35.0, 21.0, 23.0) may be changed. ``` fix = mylist[:3] vari = mylist[3:] ``` The goal is to add a new item to mylist, while sum(mylist) stays 100.0 and vari items keep their relations to each other. For that we need to substract a CERTAIN PERCENTAGE from each vari item. Example: lets assume we want to add 4.0 to mylist. Using an ugly aproximation loop I found out that i need to substract ca. 5.0634% of each vari item (CERTAIN PERCENTAGE = 5.0634): ``` adjusted =[] for number in vari: adjusted.append(number-(number*(5.0634/100.0))) adjusted.extend(fix) adjusted.append(4.0) ``` adjusted now contains my desired result. # My question is how to calculate CERTAIN PERCENTAGE ;.)
How's this? ``` def adjustAppend( v, n ): weight= -n/sum(v) return [ i+i*weight for i in v ] + [n] ``` Given a list of numbers *v*, append a new number, *n*. Weight the existing number to keep the sum the same. ``` sum(v) == sum( v + [n] ) ``` Each element of *v*, *i*, must be reduced by some function of *i*, *r*(*i*) such that ``` sum(r(i)) == -n ``` or ``` sum( map( r, v ) ) == -n ``` Therefore, the weighting function is `-(n*i)/sum(v)`
you're being silly. let's say you want to add 4.0 to the list. You don't need to subtract a certain amount from each one. What you need to do is multiply each item. 100 - 4 = 96. therefore, multiply each item by 0.96 you want to add 20.0 as an item. so then you multiply each item by 0.8, which is (100-20)\*0.01 update: Hrmn I didn't read carefuly enough. think of it like this. (fixed)+(vari)= 100; (fixed)+(vari \* x) + newitem = 100; so basically like what we did before except with just the vari portion. if vari totals to 50, and the new item you're adding is 3.0, then multiply each item in vari by (47/50)
Algorithm to keep a list of percentages to add up to 100%
[ "", "python", "algorithm", "" ]
I'm basically looking for a way to automate typing stuff like the following: ``` cout << "a[" << x << "][" << y << "] =\t" << a[x][y] << endl; ``` Something like: ``` PRINTDBG(a[x][y]); ``` Ideally this would also work for ``` PRINTDBG(func(arg1, arg2)); ``` and even ``` PRINTDBG(if(condition) func(foo);); ``` (which would print e.g. "if(false) func(5)"). Nonportable hacks welcome too :) (no, using a debugger isn't the same, it's much less flexible and I find it confusing)
This is, in the way you want it, not possible. If you have *if(condition) func(foo);* given to a macro, it can stringize that stuff, and it will print *if(condition) func(foo);*, but not with the actual values of the variables substituted. Remember the preprocessor doesn't know about the structure about that code. For debugging, i would use some type-safe printf variant like boost.format or some home brew [printf with boost.fusion](https://stackoverflow.com/questions/455904/print-information-in-test-mode-but-not-in-normal-execution#456184), which make the job of printing stuff like that much more easy: ``` dprintf("a[%][%] = %", (x, y, a[x][y])); ```
This is an area where the `printf` style output can be more concise: ``` cout << "a[" << x << "][" << y << "] =\t" << a[x][y] << endl; printf("a[%d][%d] =\t%d\n", x, y, a[x][y]); ``` Of course, this has the limitation of only working for types that `printf` understands, and it still doesn't address your question. I get the feeling that there might be something of value in the expression decomposition techniques in Boost, but I am not enough of a template ninja to identify what. **Update**: The following almost addresses your question: ``` #define PRINTDBG(x) cout << #x << " =\t" << x << endl; ``` However, when used as `PRINTDBG(a[x][y])` it literally prints: ``` a[x][y] = 5 ``` which doesn't give the actual values of `x` and `y`.
Printing detailed debugging output easily?
[ "", "c++", "debugging", "" ]
i want to do this simple piece of code work. ``` #include <iostream> #include <windows.h> void printSome (int i) { std::cout << i << std::endl; } void spawnThread (void (*threadName)(int i)) { CreateThread ( 0, // default security attributes 0, // use default stack size (LPTHREAD_START_ROUTINE)threadName, // thread function name (LPVOID)i, // argument to thread function 0, // use default creation flags 0 // returns the thread identifier ); } int main () { spawnThread(printSome(155)); } ``` i am on windows, using vs. Any help will be greatly appriciated.
Personally, I wouldn't consider passing in a function pointer like you are trying to do as very C++ like. That's coding C in C++ Instead, I'd wrap that thing in a class. The big advantage there is you can just override the class to have however many members you want, rather than having to perform greazy casting tricks to get at your parameters every time. The code's a little long-winded, so I pushed it to the end. But what it lets you do is something like this: ``` class print_some : public basic_thread { private: int i; public: print_some (int i) : i(i) {}; action_callback () { std::cout << i << std::endl; } } int main () { print_some printer (155); } ``` Here's some exerpted example code from one of our classes that does this: ``` class basic_thread : { public: basic_thread(); protected: unsigned long m_ThreadId; virtual void action_callback () {}; // Internal routine used to bridge between OS callback format and // action_callback. *Must* be static for the OS. static unsigned long __stdcall self_calling_callback (void *parameter); } ``` ...and in the .cpp: ``` unsigned long __stdcall basic_thread::self_calling_callback (void *parameter) { if (parameter) { basic_thread * thread = reinterpret_cast<basic_thread *>(parameter); thread->action_callback(); } return 0; // The value returned only matters if someone starts calling GetExitCodeThread // to retrieve it. } basic_thread::basic_thread () { // Start thread. m_Handle = CreateThread(NULL, 0, self_calling_callback, (PVOID)this, 0, &m_ThreadId ); if( !IsHandleValid() ) throw StartException("CreateThread() failed", GetLastError()); } ```
CreateThread wants 2 arguments: pointer to the function to execute as a thread, and a DWORD argument that will be given to the thread. your spawnThread() function only has 1 argument (threadName); you *think* it has 2 args because of the "i", but that is really part of the definition of the "threadName" type. (you could just as well leave out the "i"; that is, you don't need to name the arguments to "threadName".) anyway, given that you NEED 2 arguments, redefine spawnThread: ``` void spawnThread(void (*threadEntryPoint)(int), int argument) { CreateThread(0,0, (LPTHREAD_START_ROUTINE)threadEntryPoint, (LPVOID)argument, 0,0); } ``` notice that i did not *name* the int argument to the threadEntryPoint; it is sufficient to tell the compiler that the function must have a single int argument. and call it: ``` spawnThread(printSome, 155); ``` anyway, quick and dirty, this will do what you want. hth. reilly.
Passing function Pointers in C++
[ "", "c++", "windows", "multithreading", "function", "pointers", "" ]
I read somewhere (can't find it now) that large exception hierarchies are a waste of time. The justification for this statement seemed sound at the time and the idea stuck with me. In my own code when I have a code base that can have a range of error conditions I use a single exception with an enumeration member to differentiate between them. If the case arises that I need to catch on one of these errors, I catch it, check the enum and rethrow if it was not what I expected. Ideally, this should be rare. I was working with exceptions again and the I had a reflective moment where I questioned my exception habits. I am curious what everyone else does and why? Hierarchy or one exception with data members. BTW, I am assuming you agree with the idea of exception vs error codes. I don't wish to open that can of worms.
Simple rule of thumb: * If you end up rethrowing exceptions after examining them, then you need a more finegrained exception hierarchy (Except for the rare case where the examination entails considerable logic). * If you have Exception classes that are never caught (only their supertypes are), then you need a less finegrained exception hierarchy.
I think having just one exception type with an embedded enum is suboptimal: 1. You are forced to catch the exception more often than necessary (and rethrow it, once you have established that you can't handle it) 2. The enum itself becomes a change hotspot (all programmers need to modify it on a regular basis) 3. An enum is not hierarchical, so for example you cannot handle all IO errors with one handler easily 4. Sometimes you also want to provide the caller with additional information besides the error message text, e.g. the path of the file that has not been found or the error number received from the SQL server. Putting such additional information from all possible error scenarios into the same exception makes handling even more cumbersome. To answer your question, I'm using a hierarchy of exceptions. It's much broader than it is deep.
exception hierarchy vs error enumeration
[ "", "c++", "exception", "" ]
I am programming a simulations for single neurons. Therefore I have to handle a lot of Parameters. Now the Idea is that I have two classes, one for a SingleParameter and a Collection of parameters. I use property() to access the parameter value easy and to make the code more readable. This works perfect for a sinlge parameter but I don't know how to implement it for the collection as I want to name the property in Collection after the SingleParameter. Here an example: ``` class SingleParameter(object): def __init__(self, name, default_value=0, unit='not specified'): self.name = name self.default_value = default_value self.unit = unit self.set(default_value) def get(self): return self._v def set(self, value): self._v = value v = property(fget=get, fset=set, doc='value of parameter') par1 = SingleParameter(name='par1', default_value=10, unit='mV') par2 = SingleParameter(name='par2', default_value=20, unit='mA') # par1 and par2 I can access perfectly via 'p1.v = ...' # or get its value with 'p1.v' class Collection(object): def __init__(self): self.dict = {} def __getitem__(self, name): return self.dict[name] # get the whole object # to get the value instead: # return self.dict[name].v def add(self, parameter): self.dict[parameter.name] = parameter # now comes the part that I don't know how to implement with property(): # It shoule be something like # self.__dict__[parameter.name] = property(...) ? col = Collection() col.add(par1) col.add(par2) col['par1'] # gives the whole object # Now here is what I would like to get: # col.par1 -> should result like col['par1'].v # col.par1 = 5 -> should result like col['par1'].v = 5 ``` --- Other questions that I put to understand property(): * [Why do managed attributes just work for class attributes and not for instance attributes in python?](https://stackoverflow.com/questions/428264 "Why do managed attributes just work for class attributes and not for instance attributes in python?") * [How can I assign a new class attribute via \_\_dict\_\_ in python?](https://stackoverflow.com/questions/432786/ "setting class attributes with setattr()")
Using the same get/set functions for both classes forces you into an ugly hack with the argument list. Very sketchy, this is how I would do it: In class SingleParameter, define get and set as usual: ``` def get(self): return self._s def set(self, value): self._s = value ``` In class Collection, you cannot know the information until you create the property, so you define the metaset/metaget function and particularize them only later with a lambda function: ``` def metaget(self, par): return par.s def metaset(self, value, par): par.s = value def add(self, par): self[par.name] = par setattr(Collection, par.name, property( fget=lambda x : Collection.metaget(x, par), fset=lambda x, y : Collection.metaset(x,y, par)) ```
Look at built-in functions `getattr` and `setattr`. You'll probably be a lot happier.
How to implement property() with dynamic name (in python)
[ "", "python", "oop", "parameters", "properties", "" ]
We've licensed a commercial product (product not important in this context), which is limited by the number of concurrent users. Users access this product by going through a Spring Controller. We have N licenses for this product, and if N+1 users access it, they get a nasty error message about needing to buy more licenses. I want to make sure users don't see this message, and would prefer that requests to the product simply "queue up", rather than having N+1 users actually access it. Of course, they would prefer that I purchase the licenses, so their tool won't let us do this natively. In lieu of being able to control the tool, I'd like to limit the number of concurrent sessions to the controller to never be more than N. Everyone else can wait. We're using Spring MVC. Any ideas?
What you need is a ObjectPool. Check out Apache Commons Pool <http://commons.apache.org/pool> At the application startup you should create a Object Pool with licences or objects of commercial library (Not sure what kind of public interface they have). ``` public class CommercialObjectFactory extends BasePoolableObjectFactory { // for makeObject we'll simply return a new commercial object @Override public Object makeObject() { return new CommercialObject(); } } GenericObjectPool pool = new GenericObjectPool(new CommercialObjectFactory()); // The size of pool in our case it is N pool.setMaxActive(N) // We want to wait if the pool is exhausted pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK) ``` And when you need the commercial object in your code. ``` CommercialObject obj = null; try { obj = (CommercialObject)pool.borrowObject(); // use the commerical object the way you to use it. // .... } finally { // be nice return the borrwed object try { if(obj != null) { pool.returnObject(obj); } } catch(Exception e) { // ignored } } ``` If this is not what you want then you will need to provide more detail about your commercial library.
Spring has a org.springframework.aop.interceptor.ConcurrencyThrottleInterceptor that can be used via AOP (or the underlying code can be used standalone). That might be a lighter weight approach than using a object pool.
Limit Access To a Spring MVC Controller -- N sessions at a time
[ "", "java", "multithreading", "spring", "session", "controller", "" ]
In [this](https://stackoverflow.com/questions/381267/looped-pushback-against-resize-iterator) thread some one commented that the following code should only be used in 'toy' projects. Unfortunately he hasn't come back to say why it's not of production quality so I was hoping some one in the community may be able to either assure me the code is ok (because I quite like it) or identify what is wrong. ``` template< class T1, class T2> void hexascii( T1& out, const T2& in ) { out.resize( in.size() * 2 ); const char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7','8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; T1::iterator outit = out.begin(); for( T2::const_iterator it = in.begin(); it != in.end(); ++it ) { *outit++ = hexDigits[*it >> 4]; *outit++ = hexDigits[*it & 0xF]; } } template<class T1, class T2> void asciihex( T1& out, const T2& in ) { size_t size = in.size; assert( !(size % 2) ); out.resize( size / 2 ); T1::iterator outit = out.begin(); for( T2::const_iterator it = in.begin(); it != in.end(); it += 2, ++outit ) { *outit = ((( (*it > '9' ? *it - 0x07 : *it) - 0x30) << 4) & 0x00f0) + (((*(it+1) > '9' ? *(it+1) - 0x07 : *(it+1)) - 0x30) & 0x000f); } } ``` Edit: Thanks for your help guys, you've made some big improvements. I've written functions in the two suggested styles from your answers. Some rough testing suggests the second method is marginally faster than the first, but IMO this is outweighed by the improved readability of the first. ``` template<class T1> void asciihex2( T1& out, const std::string& in ) { dassert( sizeof(T1::value_type)==1 ); size_t size = in.size(); assert( !(size % 2) ); out.resize( size / 2 ); T1::iterator outit = out.begin(); for( size_t i = 0; i < in.size(); i += 2 ) { int tmp; sscanf( in.c_str() + i, "%02X", &tmp ); *outit++ = tmp; } } template<class T1> void asciihex3( T1& out, const std::string& in ) { dassert( sizeof(T1::value_type)==1 ); size_t size = in.size(); assert( !(size % 2) ); out.resize( size / 2 ); T1::iterator outit = out.begin(); const char hexDigits[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}; for( std::string::const_iterator it = in.begin(); it != in.end(); it += 2, ++outit ) { *outit = (hexDigits[(*it - 0x30) & 0x1f] << 4) + hexDigits[((*(it+1) - 0x30) & 0x1f)]; } } ``` Some of the assumptions surronding this code: 1: They are not intended as a generic, but are used in an anonymous name space to translate data for a specific class. 2: The templating is required as two separate container types are being used (one being std::vector, the other a similar byte array type container from a third party library. 3: The purpose is to be able to convert binary data of indeterminate length into strings and back again (0x1234abcd <-> "1234abcd") 4: assert traps errors in both debug and release modes 5: by the time these functions are called the size of the string will already have been checked, assert is used to terminate processing if something serious has gone wrong 6: It needs some commenting Any other ideas appreciated.
It seems like a lot of templated code to achieve very little, given you have direct hex conversion in the standard C **scanf** and **printf** functions. why bother?
My main comment about it is that it's very difficult to read. Especially: ``` *outit = ((( (*it > '9' ? *it - 0x07 : *it) - 0x30) << 4) & 0x00f0) + (((*(it+1) > '9' ? *(it+1) - 0x07 : *(it+1)) - 0x30) & 0x000f) ``` It would take my brain a little while to grok that, and annoy me if I inherited the code.
Converting binary data to printable hex
[ "", "c++", "templates", "stl", "" ]
I'm using `ShellExecuteEx` to execute a command in C. Is there a way to use `ShellExecuteEx` and capture standard in/out/err? Note: I don't want to use `CreateProcess`.
As mentioned by pilif and Bob, you need to use `CreateProcess`. If you want code that wraps it all up for you, I do have a class for this exact issue at: <http://code.google.com/p/kgui/source/browse/trunk/kguithread.cpp>. The class (`kGUICallThread`) handles Linux, macOS and Windows versions. The code is licensed LGPL.
I use to found the problem like you. Suppose, You want to capture the output from STDOUT that it's generated by **dir** command and save the captured into **out.txt**. 1. Use text editor and type **dir > out.txt** and save it with **mybat.bat** (\*.bat, don't \*.txt) 2. In your c/c++ program, type **WinExec("mybat.bat", SW\_HIDE);** and run your application. 3. Open the **out.txt** you will see the name of folders and files in current directory. Also, you can run any executable files (\*.exe) at the same way as follow. **xxx.exe > out.txt** I hope it can be helps you. Sorry, my English really not good.
Using ShellExecuteEx and capturing standard in/out/err
[ "", "c++", "c", "windows", "winapi", "" ]
i have a weird problem. i would like to delete an assembly(plugin.dll on harddisk) which is already loaded, but the assembly is locked by the operating system (vista), even if i have unloaded it. f.e. ``` AppDomainSetup setup = new AppDomainSetup(); setup.ShadowCopyFiles = "true"; AppDomain appDomain = AppDomain.CreateDomain(assemblyName + "_AppDomain", AppDomain.CurrentDomain.Evidence, setup); IPlugin plugin = (IPlugin)appDomain.CreateInstanceFromAndUnwrap(assemblyName, "Plugin.MyPlugins"); ``` I also need the assemblyinfos, because I don't know which classes in the pluginassembly implements the IPlugin Interface. It should be possible to have more than one Plugin in one Pluginassembly. ``` Assembly assembly = appDomain.Load(assemblyName); if (assembly != null) { Type[] assemblyTypes = assembly.GetTypes(); foreach (Type assemblyTyp in assemblyTypes) { if (typeof(IPlugin).IsAssignableFrom(assemblyTyp)) { IPlugin plugin = (IPlugin)Activator.CreateInstance(assemblyTyp); plugin.AssemblyName = assemblyNameWithEx; plugin.Host = this; } } } AppDomain.Unload(appDomain); ``` How is it possible to get the assemblyinfos from the appDomain without locking the assembly? best regards
I think i've the answer! the answer from Øyvind Skaar will not work, if you would like to delete the loaded assembly. instead of ``` using (FileStream dll = File.OpenRead(path)) { fileContent = new byte[dll.Length]; dll.Read(fileContent, 0, (int)dll.Length); } Assembly assembly = appDomain.Load(fileContent); ``` you have to use ``` byte[] b = File.ReadAllBytes(assemblyName); assembly = Assembly.Load(b); ``` best regards
I know this thread is quite dead, but I am currently working on this and I just got the answer (at 1h30 AM...) ``` AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; AppDomain app = AppDomain.CreateDomain("YaCsi", null, setup); app.DoCallBack(LoaderCallback); AppDomain.Unload(app); File.Delete("__YaCsi_Test01.dll"); static void LoaderCallback() { byte[] raw = File.ReadAllBytes("__YaCsi_Test01.dll"); Assembly yacsi = Assembly.Load(raw); ((IScript)yacsi.CreateInstance("Script")).Go(); } ``` And it actually don't throw any exceptions!!! Hope someone will read this and that it will answer there question!
how to delete the pluginassembly after AppDomain.Unload(domain)
[ "", "c#", "plugins", "assemblies", "" ]
I've read a few posts where people have stated (not suggested, not discussed, not offered) that PHP should not be used for large projects. Being a primarily PHP developer, I ask two questions: 1. What defines a "large project"? 2. Why not? What are the pitfalls of using PHP I run a small development team and I know from experience the quality construction, organization, documentation, commenting and encapsulation are our highest priority. We are able to develop great projects using our own framework and approach but still, I don't want to invest further if I'm wasting my time. Thoughts?
I really hate it when people say flat out that PHP is a terrible language because you can write code which mixes presentation with logic, or that it lets you allow SQL injection. **That's nothing at all to do with the language, that's the developer.** PHP has proved itself to be highly scalable: Wikipedia is one of the largest and most popular sites on the Internet and it runs PHP. Enough said? There are a lot of tools/libraries out there that give you a framework to work in, making it less likely that someone will write poor, less-maintainable code: see CakePHP, Symfony, PDO, Smarty, etc etc etc. It has received a bad rap because it's a language which has very low barriers to entry: it's free, you can get very cheap PHP hosting, **[the documentation is the best there is](https://stackoverflow.com/questions/181421/who-has-the-best-documentation-you-have-ever-seen-language-framework-cms-who-ha#181457)**, there's plenty of tutorials online, plus it makes a lot of things very easy (eg: open a URL and get the contents of the file: `file('http://www.google.com');`). This means that a lot of newbies picked it up and made a lot of very dodgy sites with it, but that's going to happen with whatever language you choose as your first. Work with a solid ORM framework (there's about 30 questions on SO about which is best), and it will treat you good.
A lot of people who say not use it are really saying don't use PHP 4. It comes down to this **you can write good code in any language** and **you can write bad code in any language** PHP can very often lend itself to becoming tangled spaghetti code libraries and make your 'application' really just a series of scripts (see Moodle for a good example of this...) I think a lot of the 'Don't use PHP for large stuff' is coming from PHP being hacked up from it's original purpose: a templating language. Which I can understand, but there are lots of projects that prove you can do it (Drupal, mediawiki, Facebook).
No PHP for large projects? Why not?
[ "", "php", "scalability", "projects", "" ]
I have the following HTML / JS: ``` <html> <body> <script> function foo(){ var html = "<iframe src=\"foo.html\" />"; document.getElementById('content').innerHTML=html; } function bar(){ var html = "<iframe src=\"bar.html\" />"; document.getElementById('content').innerHTML=html; } function show(){ alert(document.getElementById('content').innerHTML); } </script> <button onclick="foo()">foo</button><br /> <button onclick="bar()">bar</button><br /> <button onclick="show()">test</button><br /> <div id="content"></div> </body> </html> ``` This sort of works as expected, even in IE. Until I hit F5. When I first click *foo*, I get an iframe with the contents of `foo.html`, as expected. I then refresh, and hit *bar*. Instead of getting the contents of `bar.html`, I see the contents of `foo.html`. Strangely, when I click *test*, the `alert()` tells me the `src` attribute for the iframe is correctly set to `bar.html`. Firefox has no such issue. Why does this happen, and how do I prevent it? ***edit:*** what I forgot to mention is that I can't put the iframe in and change the src attribute. In the real situation I have, sometimes I need an `<img>` rather than an `<iframe>`.
Have you tried changing the url in your generated iframe? E.g. ``` var randomNum = Math.random(); var html = "<iframe src=\"bar.html?rand="+randomNum+"\" />"; ``` Even better, combine that with geowa4's appendChild() suggestion.
Use this DOM ``` <div id="content" style='display:none;'> <iframe id='contentFrame' src='' /> </div> ``` And this as your script ``` function foo() { var contentDiv = document.getElementById('content'); var contentFrame = document.getElementById('contentFrame'); contentFrame.src = 'foo.html'; contentDiv.style.display='block'; } ``` I have noticed some weird behavior with IE and using innerHTML. I would only use it to clear the contents (innerHTML = ""). If I want to add anything, I use HTMLElement.appendChild(); it hasn't failed for me yet.
IE caches dynamically added iframe. Why, and how do I prevent it?
[ "", "javascript", "html", "internet-explorer", "dom", "cross-browser", "" ]
I got the image like this (it's a graph): [![Gold Trade Graph](https://i.stack.imgur.com/vyayH.gif)](https://i.stack.imgur.com/vyayH.gif) (source: [kitconet.com](http://www.kitconet.com/charts/metals/platinum/tny_pt_en_caoz_2.gif)) I want to change the colours, so the white is black, the graph line is light blue, etc.. is it possible to achieve with GD and PHP?
This will replace the white color with Gray ``` $imgname = "test.gif"; $im = imagecreatefromgif ($imgname); $index = imagecolorclosest ( $im, 255,255,255 ); // get White COlor imagecolorset($im,$index,92,92,92); // SET NEW COLOR $imgname = "result.gif"; imagegif($im, $imgname ); // save image as gif imagedestroy($im); ``` [![enter image description here](https://i.stack.imgur.com/1Wp1f.gif)](https://i.stack.imgur.com/1Wp1f.gif)
I had trouble making this solution work. The image cannot be a true color image. Convert it first with imagetruecolortopalette(); ``` $imgname = "test.gif"; $im = imagecreatefromgif ($imgname); imagetruecolortopalette($im,false, 255); $index = imagecolorclosest ( $im, 255,255,255 ); // get White COlor imagecolorset($im,$index,92,92,92); // SET NEW COLOR $imgname = "result.gif"; imagegif($im, $imgname ); // save image as gif imagedestroy($im); ```
Can I swap colors in image using GD library in PHP?
[ "", "php", "colors", "gd", "swap", "imagefilter", "" ]
I have a form with checkboxes and then text to the right of the checkbox. There are jquery events attached to the click events of the the checkbox. What I want is to allow the user to click on the label or the checkbox and have the checkbox check/uncheck and the event to fire. Below is a simplified version of what I'm trying to do (**DON'T** run the code as below as it creates an endless loop). ``` <script> $(document).ready(function() { $("form p").click(function() { $(this).find("input").click(); }); $("form input").click(function() { alert("clicked"); }); }); </script> <form> <p> <input type="checkbox" name="checker" value="1" /> Click anywhere</p> <p> <input type="checkbox" name="checker2" value="2" /> Click anywhere</p> </form> ```
Use the LABEL tag: <http://www.w3schools.com/tags/tag_label.asp>
clicking on any `<input>` tag triggers the click event of `<p>` tag (because `<input>` tag is inside the `<p>` tag) which then triggers the click event of `<input>` tag leading to an endless loop.
Jquery Event Bubbling CheckBox
[ "", "javascript", "jquery", "events", "" ]
I have one interesting problem. I must parse mail body (regular expression), get some data from mail body, put this data to mail subject and forward this mail to another address. This must be done immediately when mail is received. Is any free WEBMAIL client that allow writing custom filter, or I must make application for this simple task? Which is best open source mail client (PHP or ASP.NET)?
I use this one to parse bounce emails <http://pear.php.net/package/Mail_Mime> good results so far. EDIT: also <http://www.xpertmailer.com/> has a very nice MIME library that can help you.
To get immediate processing of mails without polling, this should be integrated into your mail delivery process (MDA, Mail Delivery Agent). On most Unix boxes, this can be easily done via [procmail](http://www.procmail.org/) and [formail](http://www.stimpy.net/procmail/tutorial/formail.html) (part of procmail). If you have more control over your mailer, tighter integration might be possible for more performance || better error handling.
Mail body parsing - open source mail client (PHP or ASP.NET)
[ "", "php", "asp.net", "email", "" ]
I'm trying to create a randomized maze in C++, but I can't start because I don't know how to create grids or cells. How could I create it? And I also want to create it using ASCII characters. how can i store it in array? (can any one give a sample code and some explanation so i can understand it better) Another question: What data stuctures should I need to learn and use? I'm planning to use Eller's algorithm or Kruskal's algorithm. Thank you guys for helping me! im a begginer programmer, and i want to learn about this, because this is a part of my project, thank you vary much!
You probably want to store your maze in a 2-dimension char array. You can declare an array with or without initializing it in C++. ``` char a[30][10]; // declares a char array of 30 rows and 10 columns. // declare an array with 3 rows and 3 columns, and provide initial values char ticTacToeBoard[3][3] = {{'x', 'x', 'o'}, {'o', 'o', 'x'}, {'x', 'o', ' '} }; ``` You could change the initial values to `'|'` and `'-'` for walls in your maze, and use a space character, `' '`, for the passageways. Either initialization method works, but you always use the elements the same way. Here's how you clear the board in the initialized array above. ``` // clear the board for (int row=0; row<3; row++) { for (int col=0; col<3; col++) { ticTacToeBoard[row][col] = ' '; } } ``` If you want to read the value of an element (useful when you're trying to navigate a maze), you use the same subscript notation as when you're setting its value. ``` char y = a[2][2]; // reads the character in row 2, column 2 ```
Are you looking for [Maze generation algorithms](http://en.wikipedia.org/wiki/Maze_generation_algorithm) ([more](http://www.astrolog.org/labyrnth/algrithm.htm))? Is your problem with the algorithms, or graphics? The typical algorithms work by considering each "cell" in the maze as a vertex of a graph, start with all "walls", and remove a set of walls that corresponds to a spanning tree. (So in order to randomize it, many of them start with random weights and find the minimum spanning tree.) For small mazes at least, you don't need any special data structure to represent the cells; you can just think of each cell as a pair `(x,y)` (its coördinates). And you don't need any data structure (adjacency matrix / adjacency list) to store the edges of the graph either, because the neighbours of `(x,y)` are just `(x,y±1)` and `(x±1,y)` (ignoring those that fall outside the boundaries). In any case, once you have the spanning tree, you know exactly which of the walls "exist" and which do not, so you have a complete description of the maze. If you're going to draw the maze, you know which ones to draw. To draw with ASCII characters, you just pass through each row one by one: draw the "upper walls" (put a "`--`" if the wall between `(x,y)` and `(x,y+1)` exists), then draw the actual row (put a "`|`" if the wall between `(x,y)` and `(x+1,y)` exists). Finally draw the bottom boundary.
How can I create cells or grids in C++ for a randomized maze?
[ "", "c++", "algorithm", "data-structures", "maze", "" ]
Is this a good way to implement a Finally-like behavior in standard C++? (Without special pointers) ``` class Exception : public Exception { public: virtual bool isException() { return true; } }; class NoException : public Exception { public: bool isException() { return false; } }; Object *myObject = 0; try { // OBJECT CREATION AND PROCESSING try { myObject = new Object(); // Do something with myObject. } // EXCEPTION HANDLING catch (Exception &e) { // When there is an excepion, handle or throw, // else NoException will be thrown. } throw NoException(); } // CLEAN UP catch (Exception &e) { delete myObject; if (e.isException()) throw e; } ``` 1. No exception thrown by object -> NoException -> Object cleaned up 2. Exception thrown by object -> Handled -> NoException -> Object cleaned up 3. Exception thrown by object -> Thrown -> Exception -> Object cleaned up -> Thrown
The standard answer is to use some variant of [resource-allocation-is-initialization](http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization) abbreviated RAII. Basically you construct a variable that has the same scope as the block that would be inside the block before the finally, then do the work in the finally block inside the objects destructor. ``` try { // Some work } finally { // Cleanup code } ``` becomes ``` class Cleanup { public: ~Cleanup() { // Cleanup code } } Cleanup cleanupObj; // Some work. ``` This looks terribly inconvenient, but usually there's a pre-existing object that will do the clean up for you. In your case, it looks like you want to destruct the object in the finally block, which means a smart or unique pointer will do what you want: ``` std::unique_ptr<Object> obj(new Object()); ``` or modern C++ ``` auto obj = std::make_unique<Object>(); ``` No matter which exceptions are thrown, the object will be destructed. Getting back to RAII, in this case the resource allocation is allocating the memory for the Object and constructing it and the initialization is the initialization of the unique\_ptr.
No. The Standard way to build a finally like way is to separate the concerns (<http://en.wikipedia.org/wiki/Separation_of_concerns>) and make objects that are used within the try block automatically release resources in their destructor (called "Scope Bound Resource Management"). Since destructors run deterministically, unlike in Java, you can rely on them to clean up safely. This way the objects that aquired the resource will also clean up the resource. One way that is special is dynamic memory allocation. Since you are the one aquiring the resource, you have to clean up again. Here, smart pointers can be used. ``` try { // auto_ptr will release the memory safely upon an exception or normal // flow out of the block. Notice we use the "const auto_ptr idiom". // http://www.gotw.ca/publications/using_auto_ptr_effectively.htm std::auto_ptr<A> const aptr(new A); } // catch... ```
Implementation of finally in C++
[ "", "c++", "exception", "try-catch", "throw", "finally", "" ]
I'm new to the MDX/OLAP and I'm wondering if there is any ORM similar like Django ORM for Python that would support OLAP. I'm a Python/Django developer and if there would be something that would have some level of integration with Django I would be much interested in learning more about it.
Django has some OLAP features that are nearing release. Read <http://www.eflorenzano.com/blog/post/secrets-django-orm/> <http://doughellmann.com/2007/12/30/using-raw-sql-in-django.html>, also If you have a proper star schema design in the first place, then one-dimensional results can have the following form. ``` from myapp.models import SomeFact from collections import defaultdict facts = SomeFact.objects.filter( dimension1__attribute=this, dimension2__attribute=that ) myAggregates = defaultdict( int ) for row in facts: myAggregates[row.dimension3__attribute] += row.someMeasure ``` If you want to create a two-dimensional summary, you have to do something like the following. ``` facts = SomeFact.objects.filter( dimension1__attribute=this, dimension2__attribute=that ) myAggregates = defaultdict( int ) for row in facts: key = ( row.dimension3__attribute, row.dimension4__attribute ) myAggregates[key] += row.someMeasure ``` To compute multiple SUM's and COUNT's and what-not, you have to do something like this. ``` class MyAgg( object ): def __init__( self ): self.count = 0 self.thisSum= 0 self.thatSum= 0 myAggregates= defaultdict( MyAgg ) for row in facts: myAggregates[row.dimension3__attr].count += 1 myAggregates[row.dimension3__attr].thisSum += row.this myAggregates[row.dimension3__attr].thatSum += row.that ``` This -- at first blush -- seems inefficient. You're trolling through the fact table returning lots of rows which you are then aggregating in your application. In some cases, this may be *faster* than the RDBMS's native sum/group\_by. Why? You're using a simple mapping, not the more complex sort-based grouping operation that the RDBMS often has to use for this. Yes, you're getting a lot of rows; but you're doing less to get them. This has the disadvantage that it's not so declarative as we'd like. It has the advantage that it's pure Django ORM.
Same thing as *kpw*, I write my own stuff, except that it is exclusively for Django : <https://code.google.com/p/django-cube/>
Any Python OLAP/MDX ORM engines?
[ "", "python", "django", "orm", "olap", "mdx", "" ]
I am implementing a tree think of it as a folder structure so I have a class that looks like: ``` public class Folder { //Various Props like Name etc. public IList<Folder> Children{get;} public Folder Parent {get;} } ``` Now what I want is to be able to walk up and down the tree so given a root I can find a leaf, and given a leaf I can find the root node. So each child needs a parent. Now the question is what is the best way to add a new node to the tree. I have used two solutions in the past: 1. Add an AddChild(Folder) method to Folder which handles adding the folder, and can set the parent. The problem with this is I now have to lock my Children collection so you can't bypass this method. 2. Create my own Children collection which will be given a reference back to the instance, so it can handle setting the parent on the add. The problem with this I have to implement a new collection. 3. Use a collection which has events when items are added or deleted. I am curious what patterns people generally use, and then if anyone has any suggestions for my specific use case. I am using nHibernate to persist my tree to SQL server. I'd rather not implement a custom collection as it's a lot of code to get this to work for something which is a very small part of my application.
After looking [on MSDN](http://msdn.microsoft.com/en-us/library/e78dcd75.aspx) you could try this: ``` List<Folder> children; public ReadOnlyCollection<Folder> Children { get { return this.children.AsReadOnly(); } } ``` If your private member must be declared as an IList then we can copy that into a list and then return it. But I really don't see a problem with using a concrete implementation as a private member. Changing the implementation later won't break compatibility. ``` IList<Folder> children; public ReadOnlyCollection<Folder> Children { get { return new List<Folder>(this.children).AsReadOnly(); } } ```
Personally, I'd go with method 1. Allowing client code to manipulate the Children collection directly violates encapsulation in any case, so 'locking' the Children collection is the Right Thing™. The 'proper' strategy for keeping your node relationships correct depends on the needs of your clients. I'm presuming that in this specific situation, you'd want clients to be able to alter the child nodes themselves, but not the Children collection. If that's the case, I think Rob Prouse's suggestion (make the Children property return an IEnumerable) is probably the best choice. In other situations, a ReadOnlyCollection would probably be better.
Implementing a tree in c# managing parent-child
[ "", "c#", "nhibernate", "design-patterns", "tree", "" ]
Is there any way to force PHP to blow up (error, whatever) if I misspell a variable name? What about if I'm using an instance of a class and I spell the name of a variable wrong? [I know that I should just get used to it, but maybe there's a way to enforce name checking?] Thanks! **Edit:** Sorry, that wasn't very specific. Here's the code, and I would like to get **two** errors. Right now I only get one (for the last line). ``` error_reporting(E_ALL|E_STRICT); class Joe { public $lastName; } $joe = new Joe(); $joe->lastNombre = "Smith"; echo "And here it is " . $jose; ```
Here is something I whipped up really quickly to show how you can trigger errors when something like that happens: ``` <?php error_reporting( E_ALL | E_STRICT ); class Joe { public $lastName; public function __set( $name, $value ) { if ( !property_exists( $this, $name ) ) { trigger_error( 'Undefined property via __set(): ' . $name, E_USER_NOTICE ); return null; } $this->$name = $value; } public function __get( $name ) { if ( !property_exists( $this, $name ) ) { trigger_error( 'Undefined property via __get(): ' . $name, E_USER_NOTICE ); return null; } return $this->$name; } } $joe = new Joe(); $joe->lastNom = "Smith"; echo $joe->lastNom , "\n"; ?> ```
You could try: ``` error_reporting(E_ALL|E_STRICT); ``` EDIT: OK, I've now read the updated question. I think you're out of luck. That's valid in PHP. Some say it's a feature. :)
Force PHP to error on non-declared variables? In objects?
[ "", "php", "typechecking", "" ]
I need to remove multiple items from a Dictionary. A simple way to do that is as follows : ``` List<string> keystoremove= new List<string>(); foreach (KeyValuePair<string,object> k in MyCollection) if (k.Value.Member==foo) keystoremove.Add(k.Key); foreach (string s in keystoremove) MyCollection.Remove(s); ``` The reason why I can't directly Remove the items in the foreach block is that this would throw an Exception ("Collection was modified...") I'd like to do the following : ``` MyCollection.RemoveAll(x =>x.Member==foo) ``` But the `Dictionary<>` class doesn't expose a `RemoveAll(Predicate<> Match)` method, like the `List<>` Class does. What's the best way (both performance wise and elegant wise) to do that?
Here's an alternate way ``` foreach ( var s in MyCollection.Where(kv => kv.Value.Member == foo).ToList() ) { MyCollection.Remove(s.Key); } ``` Pushing the code into a list directly allows you to avoid the "removing while enumerating" problem. The `.ToList()` will force the enumeration before the foreach really starts.
you can create an [extension method](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods): ``` public static class DictionaryExtensions { public static void RemoveAll<TKey, TValue>(this IDictionary<TKey, TValue> dict, Func<TValue, bool> predicate) { var keys = dict.Keys.Where(k => predicate(dict[k])).ToList(); foreach (var key in keys) { dict.Remove(key); } } } ... dictionary.RemoveAll(x => x.Member == foo); ```
Best way to remove multiple items matching a predicate from a .NET Dictionary?
[ "", "c#", ".net", "linq", "collections", "dictionary", "" ]
I want to be able to run WSGI apps but my current hosting restricts it. Does anybody know a company that can accommodate my requirements?
My automatic response would be [WebFaction](http://www.webfaction.com/). I haven't personally hosted with them, but they are primarily Python-oriented (founded by the guy who wrote CherryPy, for example, and as far as I know they were the first to roll out [Python 3.0 support](http://blog.webfaction.com/python-3-0-is-here)).
I am a big fan of [Slicehost](http://www.slicehost.com/) -- you get root access to a virtual server that takes about 2 minutes to install from stock OS images. The 256m slice, which has been enough for me, is US$20/mo -- it is cheaper than keeping an old box plugged in, and easy to back up. Very easy to recommend.
For Python support, what company would be best to get hosting from?
[ "", "python", "web-hosting", "wsgi", "" ]
Is there a tool that can parse C++ files within a project and generate UML from it?
Here are a few options: Step-by-Step Guide to Reverse Engineering Code into UML Diagrams with Microsoft Visio 2000 - <http://msdn.microsoft.com/en-us/library/aa140255(office.10).aspx> BoUML - <https://www.bouml.fr/features.html> StarUML - <https://staruml.io/> Reverse engineering of the UML class diagram from C++ code in presence of weakly typed containers (2001) - <http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.27.9064> Umbrello UML Modeller - <https://apps.kde.org/umbrello/> A list of other tools to look at - [http://plg.uwaterloo.ca/~migod/uml.html](http://plg.uwaterloo.ca/%7Emigod/uml.html)
If its just diagrams that you want, [doxygen](http://www.doxygen.org) does a pretty good job.
Generating UML from C++ code?
[ "", "c++", "uml", "" ]
I've got a list of People that are returned from an external app and I'm creating an exclusion list in my local app to give me the option of manually removing people from the list. I have a composite key which I have created that is common to both and I want to find an efficient way of removing people from my List using my List e.g ``` class Person { prop string compositeKey { get; set; } } class Exclusions { prop string compositeKey { get; set; } } List<Person> people = GetFromDB; List<Exclusions> exclusions = GetFromOtherDB; List<Person> filteredResults = People - exclustions using the composite key as a comparer ``` I thought LINQ was the ideal way of doing this but after trying joins, extension methods, using yields, etc. I'm still having trouble. If this were SQL I would use a `not in (?,?,?)` query.
Have a look at the [Except](http://msdn.microsoft.com/en-us/library/bb336390.aspx) method, which you use like this: ``` var resultingList = listOfOriginalItems.Except(listOfItemsToLeaveOut, equalityComparer) ``` You'll want to use the overload I've linked to, which lets you specify a custom IEqualityComparer. That way you can specify how items match based on your composite key. (If you've already overridden Equals, though, you shouldn't need the IEqualityComparer.) **Edit:** Since it appears you're using two different types of classes, here's another way that might be simpler. Assuming a `List<Person>` called `persons` and a `List<Exclusion>` called `exclusions`: ``` var exclusionKeys = exclusions.Select(x => x.compositeKey); var resultingPersons = persons.Where(x => !exclusionKeys.Contains(x.compositeKey)); ``` In other words: Select from exclusions just the keys, then pick from persons all the Person objects that *don't* have any of those keys.
I would just use the FindAll method on the List class. i.e.: ``` List<Person> filteredResults = people.FindAll(p => return !exclusions.Contains(p)); ``` Not sure if the syntax will exactly match your objects, but I think you can see where I'm going with this.
Filtering lists using LINQ
[ "", "c#", "linq", "list", "linq-to-objects", "" ]
I wish to draw an image based on computed pixel values, as a means to visualize some data. Essentially, I wish to take a 2-dimensional matrix of color triplets and render it. Do note that this is not image processing, since I'm not transforming an existing image nor doing any sort of whole-image transformations, and it's also not vector graphics as there is no pre-determined structure to the image I'm rendering- I'm probably going to be producing amorphous blobs of color one pixel at a time. I need to render images about 1kx1k pixels for now, but something scalable would be useful. Final target format is PNG or any other lossless format. I've been using PIL at the moment via ImageDraw's draw.point , and I was wondering, given the very specific and relatively basic features I require, is there any faster library available?
If you have `numpy` and `scipy` available (and if you are manipulating large arrays in Python, I would recommend them), then the [`scipy.misc.pilutil.toimage`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.toimage.html) function is very handy. A simple example: ``` import numpy as np import scipy.misc as smp # Create a 1024x1024x3 array of 8 bit unsigned integers data = np.zeros( (1024,1024,3), dtype=np.uint8 ) data[512,512] = [254,0,0] # Makes the middle pixel red data[512,513] = [0,0,255] # Makes the next pixel blue img = smp.toimage( data ) # Create a PIL image img.show() # View in default viewer ``` The nice thing is `toimage` copes with different data types very well, so a 2D array of floating-point numbers gets sensibly converted to grayscale etc. You can download `numpy` and `scipy` from [here](https://www.scipy.org/scipylib/download.html). Or using pip: ``` pip install numpy scipy ```
``` import Image im= Image.new('RGB', (1024, 1024)) im.putdata([(255,0,0), (0,255,0), (0,0,255)]) im.save('test.png') ``` Puts a red, green and blue pixel in the top-left of the image. `im.fromstring()` is faster still if you prefer to deal with byte values.
What is the fastest way to draw an image from discrete pixel values in Python?
[ "", "python", "image", "python-imaging-library", "" ]
I have a CMS with a WYSIWYG editor which produces pretty good xhtml. Based on this fact, I think a HTML parser might be slightly overkill for this small job. I am intending to use regular expressions but so far have been unable to get mine to match what I'm after. I'm using PHP5. I need to match the content of the 3 block level elements the WYSIWYG editor is able to produce: p, ul & ol. I am using preg\_match\_all() currently. Is anyone able to help me? Thank you
This should work as long as you don't have nested p/ul/ol tags: ``` preg_match_all("<(?:p|ul|ol)>(.*?)</(?:p|ul|ol)>", $string, $matches) ``` `?:` prevents anything in the parens from being included in `$matches` and `.*?` prevents the regex from matching past the end of another tag.
I think I just figured it out ``` preg_match_all('/<(p|ul|ol)>(.*)<\/(p|ul|ol)>/iU', $content, $blockElements); ```
Getting the content of XHTML tags: p, ul and/or ol from string
[ "", "php", "regex", "" ]
I am learning Python and trying to figure out an efficient way to tokenize a string of numbers separated by commas into a list. Well formed cases work as I expect, but less well formed cases not so much. If I have this: ``` A = '1,2,3,4' B = [int(x) for x in A.split(',')] B results in [1, 2, 3, 4] ``` which is what I expect, but if the string is something more like ``` A = '1,,2,3,4,' ``` if I'm using the same list comprehension expression for B as above, I get an exception. I think I understand why (because some of the "x" string values are not integers), but I'm thinking that there would be a way to parse this still quite elegantly such that tokenization of the string a works a bit more directly like ***strtok(A,",\n\t")*** would have done when called iteratively in C. To be clear what I am asking; I am looking for an elegant/efficient/typical way in Python to have all of the following example cases of strings: ``` A='1,,2,3,\n,4,\n' A='1,2,3,4' A=',1,2,3,4,\t\n' A='\n\t,1,2,3,,4\n' ``` return with the same list of: ``` B=[1,2,3,4] ``` via some sort of compact expression.
How about this: ``` A = '1, 2,,3,4 ' B = [int(x) for x in A.split(',') if x.strip()] ``` x.strip() trims whitespace from the string, which will make it empty if the string is all whitespace. An empty string is "false" in a boolean context, so it's filtered by the if part of the list comprehension.
For the sake of completeness, I will answer this seven year old question: The C program that uses strtok: ``` int main() { char myLine[]="This is;a-line,with pieces"; char *p; for(p=strtok(myLine, " ;-,"); p != NULL; p=strtok(NULL, " ;-,")) { printf("piece=%s\n", p); } } ``` can be accomplished in python with re.split as: ``` import re myLine="This is;a-line,with pieces" for p in re.split("[ ;\-,]",myLine): print("piece="+p) ```
How do I do what strtok() does in C, in Python?
[ "", "python", "" ]
What I mean is, I'm looking for really short code that returns the lower value. for example: ``` a=[1,2,3,4,5,6,7,8,9,10] b=[1,2,3,4,5,6,7,8] len(a) = 10 len(b) = 8 if (fill-this-in): print(lesser-value) ``` And I forgot to add that if b is lower than a, I want b returned - not len(b) - the variable b.
``` print(min(a, b)) ```
You're not hugely clear about what you want, so some alternatives. Given the following two lists: ``` a = [1,2,3,4,5,6,7,8,9,10] b = [1,2,3,4,5,6,7,8] ``` To print the shortest list, you can just do.. ``` >>> print(min(a, b)) [1, 2, 3, 4, 5, 6, 7, 8] ``` To get the shortest length as an number, you can either `min` the `len()` of each list, or do `len(min())` (both are identical, choose which ever you find most readable).. ``` >>> print(min( len(a), len(b) )) # or.. >>> print(len( min(a, b) )) 8 ``` To print the lowest value in either list, you can supply the list as a single argument to `min()` ``` >>> a.extend(b) # Appends b to a >>> print a [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8] >>> print(min(a)) 1 ``` Finally, another possibility, the list that has the lowest values in total: ``` >>> max( sum(a), sum(b) ) 55 ``` To print the actual list with the highest `sum()`, you could either use the ternary operator, like.. ``` >>> print a if sum(a) > sum(b) else b [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` ..although I never really liked (or use) it, instead using the slight longer, regular if/else statements.. ``` >>> if sum(a) > sum(b): ... print a ... else: ... print b ... [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ```
Short Python Code to say "Pick the lower value"?
[ "", "python", "code-snippets", "" ]
I'd like to write a Python script for Amarok in Linux to automatically copy the stackoverflow podcast to my player. When I plug in the player, it would mount the drive, copy any pending podcasts, and eject the player. How can I listen for the "plugged in" event? I have looked through hald but couldn't find a good example.
**Update**: As said in comments, Hal is not supported in recent distributions, the standard now is udev, Here is a small example that makes use of glib loop and **udev**, I keep the Hal version for historical reasons. This is basically the [example in the pyudev documentation](http://pyudev.readthedocs.org/en/latest/api/pyudev.glib.html#pyudev.glib.MonitorObserver), adapted to work with older versions, and with the glib loop, notice that the filter should be customized for your specific needing: ``` import glib from pyudev import Context, Monitor try: from pyudev.glib import MonitorObserver def device_event(observer, device): print 'event {0} on device {1}'.format(device.action, device) except: from pyudev.glib import GUDevMonitorObserver as MonitorObserver def device_event(observer, action, device): print 'event {0} on device {1}'.format(action, device) context = Context() monitor = Monitor.from_netlink(context) monitor.filter_by(subsystem='usb') observer = MonitorObserver(monitor) observer.connect('device-event', device_event) monitor.start() glib.MainLoop().run() ``` ***Old version with Hal and d-bus:*** You can use D-Bus bindings and listen to `DeviceAdded` and `DeviceRemoved` signals. You will have to check the capabilities of the Added device in order to select the storage devices only. Here is a small example, you can remove the comments and try it. ``` import dbus import gobject class DeviceAddedListener: def __init__(self): ``` You need to connect to Hal Manager using the System Bus. ``` self.bus = dbus.SystemBus() self.hal_manager_obj = self.bus.get_object( "org.freedesktop.Hal", "/org/freedesktop/Hal/Manager") self.hal_manager = dbus.Interface(self.hal_manager_obj, "org.freedesktop.Hal.Manager") ``` And you need to connect a listener to the signals you are interested on, in this case `DeviceAdded`. ``` self.hal_manager.connect_to_signal("DeviceAdded", self._filter) ``` I'm using a filter based on capabilities. It will accept any `volume` and will call `do_something` with if, you can read Hal documentation to find the more suitable queries for your needs, or more information about the properties of the Hal devices. ``` def _filter(self, udi): device_obj = self.bus.get_object ("org.freedesktop.Hal", udi) device = dbus.Interface(device_obj, "org.freedesktop.Hal.Device") if device.QueryCapability("volume"): return self.do_something(device) ``` Example function that shows some information about the volume: ``` def do_something(self, volume): device_file = volume.GetProperty("block.device") label = volume.GetProperty("volume.label") fstype = volume.GetProperty("volume.fstype") mounted = volume.GetProperty("volume.is_mounted") mount_point = volume.GetProperty("volume.mount_point") try: size = volume.GetProperty("volume.size") except: size = 0 print "New storage device detectec:" print " device_file: %s" % device_file print " label: %s" % label print " fstype: %s" % fstype if mounted: print " mount_point: %s" % mount_point else: print " not mounted" print " size: %s (%.2fGB)" % (size, float(size) / 1024**3) if __name__ == '__main__': from dbus.mainloop.glib import DBusGMainLoop DBusGMainLoop(set_as_default=True) loop = gobject.MainLoop() DeviceAddedListener() loop.run() ```
Here is a solution in 5 lines. ``` import pyudev context = pyudev.Context() monitor = pyudev.Monitor.from_netlink(context) monitor.filter_by(subsystem='usb') for device in iter(monitor.poll, None): if device.action == 'add': print('{} connected'.format(device)) # do something very interesting here. ``` Save this to a file say `usb_monitor.py`, run `python monitor.py`. Plug any usb and it will print device details ``` → python usb_monitor.py Device('/sys/devices/pci0000:00/0000:00:14.0/usb1/1-6/1-6:1.0') connected Device('/sys/devices/pci0000:00/0000:00:14.0/usb1/1-1/1-1:1.0') connected ``` Tested on Python 3.5 with `pyudev==0.21.0`.
How can I listen for 'usb device inserted' events in Linux, in Python?
[ "", "python", "linux", "usb", "" ]
I run Selenium tests with Selenium RC from .NET (c#). In some cases, I would like to keep the test case source as HTML (to be able to modify it from Selenium IDE), but I would like to run/include these tests from my c# unit tests. Maybe it is obvious, but I can't find the API method in the Selenium Core to achieve this. Any idea how to do that? (I think the "includePartial" command in Selenium on Rails does the thing that I would need, but for c#.)
I have asked this question some time ago, and since then I have moved forward in automated functional testing, more to the BDD/ATDD/Specification by Example direction with [SpecFlow](http://www.specflow.org). I only realize it now however that I have implemented a solution for this concrete question during my experiments. I share my solution, maybe can help others. I have created a small parser and an interpreter for the Selenium html files (you can download it from here: <http://bit.ly/ciTMA2>). Besides the implementation, these classes add some extension methods to the Selenium's ICommandProcessor interface. Base on that, a test can look like this: List commands = SeParser.ParseSeFile(@"HomePageTest.html"); selenium.Processor.InterpretCommands(commands); selenium.Processor.AssertNoVerifyErrors(); (The InterpretCommands and the AssertNoVerifyErrors are custom extension methods.)
I don't think there was a way to do this the last time I used Selenium RC .NET
How to run a recorded (HTML) selenium test from .NET
[ "", "c#", "testing", "selenium", "" ]
I want to get the ASCII value of characters in a string in C#. If my string has the value "9quali52ty3", I want an array with the ASCII values of each of the 11 characters. How can I get ASCII values in C#?
From [MSDN](http://msdn.microsoft.com/en-us/library/system.text.encoding.convert(VS.71).aspx) ``` string value = "9quali52ty3"; // Convert the string into a byte[]. byte[] asciiBytes = Encoding.ASCII.GetBytes(value); ``` You now have an array of the ASCII value of the bytes. I got the following: 57 113 117 97 108 105 53 50 116 121 51
``` string s = "9quali52ty3"; foreach(char c in s) { Console.WriteLine((int)c); } ```
How to get ASCII value of string in C#
[ "", "c#", "encoding", "ascii", "" ]
Does \* have a special meaning in Python as it does in C? I saw a function like this in the Python Cookbook: ``` def get(self, *a, **kw) ``` Would you please explain it to me or point out where I can find an answer (Google interprets the \* as wild card character and thus I cannot find a satisfactory answer).
See [Function Definitions](https://docs.python.org/2.7/reference/compound_stmts.html#function-definitions) in the Language Reference. > If the form `*identifier` is > present, it is initialized to a tuple > receiving any excess positional > parameters, defaulting to the empty > tuple. If the form `**identifier` is > present, it is initialized to a new > dictionary receiving any excess > keyword arguments, defaulting to a new > empty dictionary. Also, see [Function Calls](https://docs.python.org/2.7/reference/expressions.html#calls). Assuming that one knows what positional and keyword arguments are, here are some examples: Example 1: ``` # Excess keyword argument (python 3) example: def foo(a, b, c, **args): print("a = %s" % (a,)) print("b = %s" % (b,)) print("c = %s" % (c,)) print(args) foo(a="testa", d="excess", c="testc", b="testb", k="another_excess") ``` As you can see in the above example, we only have parameters `a, b, c` in the signature of the `foo` function. Since `d` and `k` are not present, they are put into the args dictionary. The output of the program is: ``` a = testa b = testb c = testc {'k': 'another_excess', 'd': 'excess'} ``` Example 2: ``` # Excess positional argument (python 3) example: def foo(a, b, c, *args): print("a = %s" % (a,)) print("b = %s" % (b,)) print("c = %s" % (c,)) print(args) foo("testa", "testb", "testc", "excess", "another_excess") ``` Here, since we're testing positional arguments, the excess ones have to be on the end, and `*args` packs them into a tuple, so the output of this program is: ``` a = testa b = testb c = testc ('excess', 'another_excess') ``` You can also unpack a dictionary or a tuple into arguments of a function: ``` def foo(a,b,c,**args): print("a=%s" % (a,)) print("b=%s" % (b,)) print("c=%s" % (c,)) print("args=%s" % (args,)) argdict = dict(a="testa", b="testb", c="testc", excessarg="string") foo(**argdict) ``` Prints: ``` a=testa b=testb c=testc args={'excessarg': 'string'} ``` And ``` def foo(a,b,c,*args): print("a=%s" % (a,)) print("b=%s" % (b,)) print("c=%s" % (c,)) print("args=%s" % (args,)) argtuple = ("testa","testb","testc","excess") foo(*argtuple) ``` Prints: ``` a=testa b=testb c=testc args=('excess',) ```
I only have one thing to add that wasn't clear from the other answers (for completeness's sake). You may also use the stars when calling the function. For example, say you have code like this: ``` >>> def foo(*args): ... print(args) ... >>> l = [1,2,3,4,5] ``` You can pass the list l into foo like so... ``` >>> foo(*l) (1, 2, 3, 4, 5) ``` You can do the same for dictionaries... ``` >>> def foo(**argd): ... print(argd) ... >>> d = {'a' : 'b', 'c' : 'd'} >>> foo(**d) {'a': 'b', 'c': 'd'} ```
What does asterisk * mean in Python?
[ "", "python", "" ]
In a C++ project that uses smart pointers, such as `boost::shared_ptr`, what is a good design philosophy regarding use of "**`this`**"? Consider that: * It's dangerous to store the raw pointer contained in any smart pointer for later use. You've given up control of object deletion and trust the smart pointer to do it at the right time. * Non-static class members intrinsically use a **`this`** pointer. It's a raw pointer and that can't be changed. If I ever store `this` in another variable or pass it to another function which could potentially store it for later or bind it in a callback, I'm creating bugs that are introduced when anyone decides to make a shared pointer to my class. **Given that, when is it ever appropriate for me to explicitly use a `this` pointer?** Are there design paradigms that can prevent bugs related to this?
While i don't have a general answer or some idiom, there is [`boost::enable_shared_from_this`](http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/enable_shared_from_this.html) . It allows you to get a shared\_ptr managing an object that is already managed by shared\_ptr. Since in a member function you have no reference to those managing shared\_ptr's, enable\_shared\_ptr does allow you to get a shared\_ptr instance and pass that when you need to pass the this pointer. But this won't solve the issue of passing `this` from within the constructor, since at that time, no shared\_ptr is managing your object yet.
# Wrong question > In a C++ project that uses smart pointers The issue has nothing to do with smart pointers actually. It is only about ownership. ## Smart pointers are just tools They change nothing WRT the concept of ownership, esp. **the need to have well-defined ownership in your program**, the fact that ownership can be voluntarily transferred, but cannot be taken by a client. You must understand that smart pointers (also locks and other RAII objects) represent a value and a relationship WRT this value at the same time. A `shared_ptr` is a reference to an object and establishes a relationship: the object must not be destroyed before this `shared_ptr`, and when this `shared_ptr` is destroyed, if it is the last one aliasing this object, the object must be destroyed immediately. (`unique_ptr` can be viewed as a special case of `shared_ptr` where there is zero aliasing by definition, so the `unique_ptr` is always the last one aliasing an object.) ## Why you should use smart pointers It is recommended to use smart pointers because they express a lot with only variables and functions declarations. Smart pointers can only express a well-defined design, they don't take away the need to define ownership. In contrast, garbage collection takes away the need to define who is responsible for memory deallocation. (But do not take away the need to define who is responsible for other resources clean-up.) Even in non-purely functional garbage collected languages, you need to make ownership clear: you don't want to overwrite the value of an object if other components still need the old value. This is notably true in Java, where the concept of ownership of mutable data structure is extremely important in threaded programs. ## What about raw pointers? The use of a raw pointer does not mean there is no ownership. It's just not described by a variable declaration. It can be described in comments, in your design documents, etc. That's why many C++ programmers consider that using raw pointers instead of the adequate smart pointer is **inferior**: because it's less expressive (I have avoided the terms "good" and "bad" on purpose). I believe the Linux kernel would be more readable with a few C++ objects to express relationships. You can implement a specific design with or without smart pointers. The implementation that uses smart pointer appropriately will be considered superior by many C++ programmers. # Your real question > In a C++ project, what is a good design philosophy regarding use of "this"? That's awfully vague. > It's dangerous to store the raw pointer for later use. Why do you need to a pointer for later use? > You've given up control of object deletion and trust the responsible component to do it at the right time. Indeed, some component is responsible for the lifetime of the variable. You cannot take the responsibility: it has to be transferred. > If I ever store this in another variable or pass it to another function which could potentially store it for later or bind it in a callback, I'm creating bugs that are introduced when anyone decides to use my class. Obviously, since the caller is not informed that the function will hide a pointer and use it later without the control of the caller, you are creating bugs. The solution is obviously to either: * transfer responsibility to handle the lifetime of the object to the function * ensure that the pointer is only saved and used under the control of the caller Only in the first case, you might end up with a smart pointer in the class implementation. ## The source of your problem I think that your problem is that you are trying hard to complicate matters using smart pointers. Smart pointers are tools to make things easier, not harder. If smart pointers complicate your specification, then rethink your spec in term of simpler things. **Don't try to introduce smart pointers as a solution before you have a problem.** Only introduce smart pointers to solve a specific well-defined problem. Because you don't describe a specific well-defined problem, **it is not possible to discuss a specific solution** (involving smart pointers or not).
smart pointers + "this" considered harmful?
[ "", "c++", "pointers", "this", "smart-pointers", "shared-ptr", "" ]
Is it possible to update more than one local variable in a single select? Something like: ``` set @variableOne = avg(someColumn), @variableTwo = avg(otherColumn) from tblTable ``` It seems a bit wasteful to make two separate select operations for something as trivial as this task: ``` set @variableOne = ( select avg(someColumn) from tblTable ) set @variableTwo = ( select avg(otherColumn) from tblTable ) ```
Something like this: ``` select @var1 = avg(someColumn), @var2 = avg(otherColumn) from theTable ```
You can use SELECT assignment to assign multiple variables. This code generates a single row of constants and assigns each to a variable. ``` SELECT @var1 = 1, @var2 = 'Zeus' ``` You can even query tables and do assignment that way: ``` SELECT @var1 = c.Column1, @var2 = c.Column2, FROM Customers c WHERE c.CustomerID = @CustomerID ``` Beware: This code operates like a while loop. * If there are multiple rows, each row will be assigned to the variables and the last row will be the one left in there. If you didn't specify an ordering, you gave up control over which row will be the last row. * If there are no rows, the variables will not be assigned to at all. The variables will not be set to null - they will remain unchanged. This is a key problem if the assignment is done in a loop (typically resulting in an infinite loop as the variables never change). Prefer using SET assignment over SELECT assignment. Only use SELECT assignment when considering both scenarios above.
T-SQL, updating more than one variable in a single select
[ "", "sql", "sql-server", "t-sql", "" ]
I have a file input element that needs to be cloned after the user has browsed and selected a file to upload. I started by using obj.cloneNode() and everything worked fine, that is until I tried using it in IE. I've since tried using jQuery's clone method as follows: ``` var tmp = jQuery('#categoryImageFileInput_'+id).clone(); var clone = tmp[0]; ``` Works as expected in FireFox, but again not in IE. I'm stuck. Anyone have some suggestions?
Editing the file form field is a security risk and thus is disabled on most browsers and *should* be disabled on firefox. It is not a good idea to rely on this feature. Imagine if somebody was able, using javascript, to change a hidden file upload field to, lets say, c:\Users\Person\Documents\Finances Or C:\Users\Person\AppData\Microsoft\Outlook.pst :)
Guessing that you need this functionality so you can clone the input element and put it into a hidden form which then gets POSTed to a hidden iframe... IE's element.clone() implementation doesn't carry over the value for input type="file", so you have to go the other way around: ``` // Clone the "real" input element var real = $("#categoryImageFileInput_" + id); var cloned = real.clone(true); // Put the cloned element directly after the real element // (the cloned element will take the real input element's place in your UI // after you move the real element in the next step) real.hide(); cloned.insertAfter(real); // Move the real element to the hidden form - you can then submit it real.appendTo("#some-hidden-form"); ```
Clone a file input element in Javascript
[ "", "javascript", "jquery", "internet-explorer", "clone", "" ]
I asked about getting iTextSharp to render a PDF from HTML and a CSS sheet before [here](https://stackoverflow.com/questions/430280/render-pdf-in-itextsharp-from-html-with-css) but it seems like that may not be possible... So I guess I will have to try something else. Is there an open source .NET/C# library out there that can take HTML ***and*** CSS as input and render it correctly? I must reiterate... the library MUST be free and preferably something with a fairly liberal license. I'm working with basically no budget here.
I've always used it on the command line and not as a library, but [HTMLDOC](https://www.msweet.org/htmldoc/) gives me excellent results, and it handles at least *some* CSS (I couldn't easily see how much). Here's a sample command line ``` htmldoc --webpage -t pdf --size letter --fontsize 10pt index.html > index.pdf ```
This command line tool is the business! <https://wkhtmltopdf.org/> It uses webkit rendering engine(used in safari and KDE), I tested it on some complex sites and it was by far better than any other tool.
Open Source HTML to PDF Renderer with Full CSS Support
[ "", "c#", "html", "css", "pdf", "pdf-generation", "" ]
Any nice **Paneled user interface** component COM/**ActiveX**/Source-code for **C#**/VB? Like what VS has internally: * Dock to screen edges * Slide open/close (unpinned) * Pin open * Group in tabs And if possible, **open-source**/free. Well, because otherwise I'd have to develop an interface system myself.
**[DockPanel Suite!](http://sourceforge.net/projects/dockpanelsuite/)** Its an open-source **docking library** for .NET Windows Forms development which **mimics Visual Studio .NET**.
We use the DevExpress (devexpress.com) Component Suite, which has a Docking Manager that does that sort of thing.
Good panel interface component for C#?
[ "", "c#", "vb.net", "user-interface", "activex", "" ]
Is there a quick way to set an HTML text input (`<input type=text />`) to only allow numeric keystrokes (plus '.')?
## JavaScript You can filter the input values of a text `<input>` with the following `setInputFilter` function (supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, validity error message, and [all browsers since IE 9](https://caniuse.com/#feat=input-event)): ``` // Restricts input for the given textbox to the given inputFilter function. function setInputFilter(textbox, inputFilter, errMsg) { [ "input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout" ].forEach(function(event) { textbox.addEventListener(event, function(e) { if (inputFilter(this.value)) { // Accepted value. if ([ "keydown", "mousedown", "focusout" ].indexOf(e.type) >= 0){ this.classList.remove("input-error"); this.setCustomValidity(""); } this.oldValue = this.value; this.oldSelectionStart = this.selectionStart; this.oldSelectionEnd = this.selectionEnd; } else if (this.hasOwnProperty("oldValue")) { // Rejected value: restore the previous one. this.classList.add("input-error"); this.setCustomValidity(errMsg); this.reportValidity(); this.value = this.oldValue; this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd); } else { // Rejected value: nothing to restore. this.value = ""; } }); }); } ``` You can now use the `setInputFilter` function to install an input filter: ``` setInputFilter(document.getElementById("myTextBox"), function(value) { return /^\d*\.?\d*$/.test(value); // Allow digits and '.' only, using a RegExp. }, "Only digits and '.' are allowed"); ``` Apply your preferred style to the `input-error` class. Here’s a suggestion: ``` .input-error{ outline: 1px solid red; } ``` Note that you still **must do server side validation**! Another caveat is that this will break the undo stack since it sets `this.value` directly. This means that `Ctrl``Z` will not work to undo inputs after typing an invalid character. ### Demo See the [JSFiddle demo](https://jsfiddle.net/KarmaProd/tgn9d1uL/4/) for more input filter examples or run the Stack snippet below: ``` // Restricts input for the given textbox to the given inputFilter. function setInputFilter(textbox, inputFilter, errMsg) { [ "input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout" ].forEach(function(event) { textbox.addEventListener(event, function(e) { if (inputFilter(this.value)) { // Accepted value. if ([ "keydown", "mousedown", "focusout" ].indexOf(e.type) >= 0) { this.classList.remove("input-error"); this.setCustomValidity(""); } this.oldValue = this.value; this.oldSelectionStart = this.selectionStart; this.oldSelectionEnd = this.selectionEnd; } else if (this.hasOwnProperty("oldValue")) { // Rejected value: restore the previous one. this.classList.add("input-error"); this.setCustomValidity(errMsg); this.reportValidity(); this.value = this.oldValue; this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd); } else { // Rejected value: nothing to restore. this.value = ""; } }); }); } // Install input filters. setInputFilter(document.getElementById("intTextBox"), function(value) { return /^-?\d*$/.test(value); }, "Must be an integer"); setInputFilter(document.getElementById("uintTextBox"), function(value) { return /^\d*$/.test(value); }, "Must be an unsigned integer"); setInputFilter(document.getElementById("intLimitTextBox"), function(value) { return /^\d*$/.test(value) && (value === "" || parseInt(value) <= 500); }, "Must be between 0 and 500"); setInputFilter(document.getElementById("floatTextBox"), function(value) { return /^-?\d*[.,]?\d*$/.test(value); }, "Must be a floating (real) number"); setInputFilter(document.getElementById("currencyTextBox"), function(value) { return /^-?\d*[.,]?\d{0,2}$/.test(value); }, "Must be a currency value"); setInputFilter(document.getElementById("latinTextBox"), function(value) { return /^[a-z]*$/i.test(value); }, "Must use alphabetic latin characters"); setInputFilter(document.getElementById("hexTextBox"), function(value) { return /^[0-9a-f]*$/i.test(value); }, "Must use hexadecimal characters"); ``` ``` .input-error { outline: 1px solid red; } ``` ``` <h2>JavaScript input filter showcase</h2> <p>Supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, and <a href="https://caniuse.com/#feat=input-event" target="_blank">all browsers since IE 9</a>.</p> <p>There is also a <a href="https://jsfiddle.net/emkey08/tvx5e7q3" target="_blank">jQuery version</a> of this.</p> <table> <tr> <td>Integer</td> <td><input id="intTextBox"></td> </tr> <tr> <td>Integer &gt;= 0</td> <td><input id="uintTextBox"></td> </tr> <tr> <td>Integer &gt;= 0 and &lt;= 500</td> <td><input id="intLimitTextBox"></td> </tr> <tr> <td>Float (use . or , as decimal separator)</td> <td><input id="floatTextBox"></td> </tr> <tr> <td>Currency (at most two decimal places)</td> <td><input id="currencyTextBox"></td> </tr> <tr> <td>A-Z only</td> <td><input id="latinTextBox"></td> </tr> <tr> <td>Hexadecimal</td> <td><input id="hexTextBox"></td> </tr> </table> ``` ## TypeScript Here is a TypeScript version of this. ``` function setInputFilter(textbox: Element, inputFilter: (value: string) => boolean, errMsg: string): void { ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout" ].forEach(function(event) { textbox.addEventListener(event, function(this: (HTMLInputElement | HTMLTextAreaElement) & { oldValue: string; oldSelectionStart: number | null, oldSelectionEnd: number | null }) { if (inputFilter(this.value)) { this.oldValue = this.value; this.oldSelectionStart = this.selectionStart; this.oldSelectionEnd = this.selectionEnd; } else if (Object.prototype.hasOwnProperty.call(this, "oldValue")) { this.value = this.oldValue; if (this.oldSelectionStart !== null && this.oldSelectionEnd !== null) { this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd); } } else { this.value = ""; } }); }); } ``` ## jQuery There is also a jQuery version of this. See [this answer](https://stackoverflow.com/a/995193/1070129). ## HTML5 HTML5 has a native solution with `<input type="number">` (see the [specification](https://html.spec.whatwg.org/multipage/input.html#number-state-%28type=number%29) and [documentation](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number)). The documentation has a working demo of this input type. * Instead of reading the `value` property, read the [`valueAsNumber`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement#valueasnumber) property of the input to get the typed value as a *number* rather than a string. * Usage inside a `<form>` is recommended because validation is made easier this way; for example, pressing `Enter` will automatically show an error message if the value is invalid. + You can use the [`checkValidity`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement#checkvalidity) method or the [`requestSubmit`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/requestSubmit) method on the entire form in order to explicitly check the validity. + Note that you might need to use the `required` attribute in order to disallow an empty input. * You can use the [`checkValidity`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/checkValidity) method or the [`validity`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement#validity) property on the input element itself in order to explicitly check the validity. * You can use [`reportValidity`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/reportValidity) to show an error message and use [`setCustomValidity`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setCustomValidity) to set your own message. This approach fundamentally has a different user experience: you are allowed to *input* invalid characters and the validation is performed *separately*. This has the benefit that the undo stack (`Ctrl``Z`) won’t break. Note that server-side validation must be performed, regardless, no matter which approach you choose. But note that browser support varies: * Most browsers will only validate the input when submitting the form, and not when typing. * [Most mobile browsers](https://caniuse.com/#feat=input-number) don’t support the `step`, `min` and `max` attributes. * Chrome (version 71.0.3578.98) still allows the user to enter the characters `e` and `E` into the field. Also see the Q&A [Why does the HTML input with `type="number"` allow the letter `e` to be entered in the field?](https://stackoverflow.com/q/31706611). * Firefox (version 64.0) and Edge (EdgeHTML version 17.17134) still allow the user to enter *any* text into the field. ### Demo ``` document.querySelector("form").addEventListener("submit", (event) => { event.preventDefault(); console.log(`Submit! Number is ${event.target.elements.number.valueAsNumber}, integer is ${event.target.elements.integer.valueAsNumber}, form data is ${JSON.stringify(Object.fromEntries(new FormData(event.target).entries()))}.`); }) ``` ``` label { display: block; } ``` ``` <form> <fieldset> <legend>Get a feel for the UX here:</legend> <label>Enter any number: <input name="number" type="number" step="any" required></label> <label>Enter any integer: <input name="integer" type="number" step="1" required></label> <label>Submit: <input name="submitter" type="submit"></label> </fieldset> </form> ```
Use this DOM ``` <input type='text' onkeypress='validate(event)' /> ``` And this script ``` function validate(evt) { var theEvent = evt || window.event; // Handle paste if (theEvent.type === 'paste') { key = event.clipboardData.getData('text/plain'); } else { // Handle key press var key = theEvent.keyCode || theEvent.which; key = String.fromCharCode(key); } var regex = /[0-9]|\./; if( !regex.test(key) ) { theEvent.returnValue = false; if(theEvent.preventDefault) theEvent.preventDefault(); } } ```
HTML text input allow only numeric input
[ "", "javascript", "jquery", "html", "" ]
How can I use RMI with a applet client behind a firewall? How can I use RMI with a firewalled server and firewalled applet client? (If possible) I know that the RMI server uses port 1099 (by default, but this is configurable); however after this the communication requires a new socket on a different random port. I also know that you can set the proxy on the client for RMI over HTTP tunneling which in theory should solve my issue. But I can't make it work (I tried setting the environmental properties on my XP client, but Internet Explorer keeps ignoring them).
See <http://java.sun.com/javase/6/docs/technotes/guides/rmi/faq.html#firewall>
If the servers code is in your hand you could also restrict RMI to use a predifined port by providing a custom RMISocketFactory as described here: <http://insidecoffe.blogspot.com/2012/02/firewall-friently-rmi-port-fixing.html> (Note specially the hint that it may cause problems if you use JMX in parallel)
How to use RMI with applet client behind a firewall?
[ "", "java", "applet", "rmi", "firewall", "" ]
How do I get the current time in Python?
Use [`datetime`](https://docs.python.org/3/library/datetime.html): ``` >>> import datetime >>> now = datetime.datetime.now() >>> now datetime.datetime(2009, 1, 6, 15, 8, 24, 78915) >>> print(now) 2009-01-06 15:08:24.789150 ``` For just the clock time without the date: ``` >>> now.time() datetime.time(15, 8, 24, 78915) >>> print(now.time()) 15:08:24.789150 ``` --- To save typing, you can import the `datetime` object from the [`datetime`](https://docs.python.org/3/library/datetime.html) module: ``` >>> from datetime import datetime ``` Then remove the prefix `datetime.` from all of the above.
Use [`time.strftime()`](http://docs.python.org/3.3/library/time.html?highlight=time.strftime#time.strftime): ``` >>> from time import gmtime, strftime >>> strftime("%Y-%m-%d %H:%M:%S", gmtime()) '2009-01-05 22:14:39' ```
How do I get the current time in Python?
[ "", "python", "datetime", "time", "" ]
I'm developing a LoB application in Java after a long absence from the platform (having spent the last 8 years or so entrenched in Fortran, C, a smidgin of C++ and latterly .Net). Java, the language, is not much changed from how I remember it. I like it's strengths and I can work around its weaknesses - the platform has grown and deciding upon the myriad of different frameworks which appear to do much the same thing as one another is a different story; but that can wait for another day - all-in-all I'm comfortable with Java. However, over the last couple of weeks I've become enamoured with Groovy, and purely from a selfish point of view: but not just because it makes development against the JVM a more succinct and entertaining (and, well, "groovy") proposition than Java (the language). What strikes me most about Groovy is its inherent maintainability. We all (I hope!) strive to write well documented, easy to understand code. However, sometimes the languages we use themselves defeat us. An example: in 2001 I wrote a library in C to translate EDIFACT EDI messages into ANSI X12 messages. This is not a particularly complicated process, if slightly involved, and I thought at the time I had documented the code properly - and I probably had - but some six years later when I revisited the project (and after becoming acclimatised to C#) I found myself lost in so much C boilerplate (mallocs, pointers, etc. etc.) that it took three days of thoughtful analysis before I finally understood what I'd been doing six years previously. This evening I've written about 2000 lines of Java (it is the day of rest, after all!). I've documented as best as I know how, but, but, of those 2000 lines of Java a significant proportion is Java boiler plate. This is where I see Groovy and other dynamic languages winning through - maintainability and later comprehension. Groovy lets you concentrate on your intent without getting bogged down on the platform specific implementation; it's almost, but not quite, self documenting. I see this as being a huge boon to me when I revisit my current project (which I'll port to Groovy asap) in several years time and to my successors who will inherit it and carry on the good work. So, are there any reasons not to use Groovy?
There are two reasons I can think of not to use Groovy (or Jython, or JRuby): * If you really, truly need performance * If you will miss static type checking Those are both big ifs. Performance is probably less of a factor in most apps than people think, and static type checking is a religious issue. That said, one strength of all of these languages is their ability to mix and match with native Java code. Best of both worlds and all that. Since I'm not responsible for your business, I say "Go for it".
If you use Groovy, you're basically throwing away useful information about types. This leaves your code "groovy": nice and concise. ``` Bird b ``` becomes ``` def b ``` Plus you get to play with all the meta-class stuff and dynamic method calls which are a torture in Java. However -- and **yes** I have tried IntelliJ, Netbeans and Eclipse extensively -- serious automatic refactoring is not possible in Groovy. It's not IntelliJ's fault: the type information **just isn't there.** Developers will say, "but if you have unit tests for every single code path (hmmmm), then you can refactor more easily." But don't believe the hype: adding more code (unit tests) will add to the safety of massive refactoring, but they don't make the work easier. Now you have to hand fix the original code **and** the unit tests. So this means that you **don't refactor as often in Groovy,** especially when a project is mature. While your code will be concise and easy to read, it will not be as brilliant as code that has been automatically refactored daily, hourly and weekly. When you realize that a **concept** represented by a class in Java is no longer necessary, you can just delete it. In Eclipse or Netbeans or whatever, your project hierarchy lights up like a Christmas tree, telling you exactly what you've screwed up with this change. `def thing` tells the compiler (and therefore your IDE) nothing about how a variable will be used, whether the method exists, etc. And IDEs can only do so much guessing. In the end, Java code is filled with "boilerplate," but it's been kneaded into its final form after many refactorings. And to me, that's the only way to get high-quality, readable code for future programmers, including when those future programmers are you-in-the-future.
Are there compelling reasons not to use Groovy?
[ "", "java", "groovy", "jvm", "" ]
**Overall Plan** Get my class information to automatically optimize and select my uni class timetable Overall Algorithm 1. Logon to the website using its Enterprise Sign On Engine login 2. Find my current semester and its related subjects (pre setup) 3. Navigate to the right page and get the data from each related subject (lecture, practical and workshop times) 4. Strip the data of useless information 5. Rank the classes which are closer to each other higher, the ones on random days lower 6. Solve a best time table solution 7. Output me a detailed list of the BEST CASE information 8. Output me a detailed list of the possible class information (some might be full for example) 9. Get the program to select the best classes automatically 10. Keep checking to see if we can achieve 7. 6 in detail Get all the classes, using the lectures as a focus point, would be highest ranked (only one per subject), and try to arrange the classes around that. **Questions** Can anyone supply me with links to something that might be similar to this hopefully written in python? In regards to 6.: what data structure would you recommend to store this information in? A linked list where each object of uniclass? Should i write all information to a text file? I am thinking uniclass to be setup like the following attributes: * Subject * Rank * Time * Type * Teacher I am hardly experienced in Python and thought this would be a good learning project to try to accomplish. Thanks for any help and links provided to help get me started, **open to edits to tag appropriately or what ever is necessary** (not sure what this falls under other than programming and python?) EDIT: can't really get the proper formatting i want for this SO post ><
Depending on how far you plan on taking #6, and how big the dataset is, it may be non-trivial; it certainly smacks of NP-hard global optimisation to me... Still, if you're talking about tens (rather than hundreds) of nodes, a fairly dumb algorithm should give good enough performance. So, you have two constraints: 1. A total ordering on the classes by score; this is flexible. 2. Class clashes; this is not flexible. What I mean by flexible is that you *can* go to more spaced out classes (with lower scores), but you *cannot* be in two classes at once. Interestingly, there's likely to be a positive correlation between score and clashes; higher scoring classes are more likely to clash. My first pass at an algorithm: ``` selected_classes = [] classes = sorted(classes, key=lambda c: c.score) for clas in classes: if not clas.clashes_with(selected_classes): selected_classes.append(clas) ``` Working out clashes might be awkward if classes are of uneven lengths, start at strange times and so on. Mapping start and end times into a simplified representation of "blocks" of time (every 15 minutes / 30 minutes or whatever you need) would make it easier to look for overlaps between the start and end of different classes.
[BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) was mentioned here a few times, e.g [get-list-of-xml-attribute-values-in-python](https://stackoverflow.com/questions/87317/get-list-of-xml-attribute-values-in-python). > Beautiful Soup is a Python HTML/XML parser designed for quick turnaround projects like screen-scraping. Three features make it powerful: > > 1. Beautiful Soup won't choke if you give it bad markup. It yields a parse tree that makes approximately as much sense as your original document. This is usually good enough to collect the data you need and run away. > 2. Beautiful Soup provides a few simple methods and Pythonic idioms for navigating, searching, and modifying a parse tree: a toolkit for dissecting a document and extracting what you need. You don't have to create a custom parser for each application. > 3. Beautiful Soup automatically converts incoming documents to Unicode and outgoing documents to UTF-8. You don't have to think about encodings, unless the document doesn't specify an encoding and Beautiful Soup can't autodetect one. Then you just have to specify the original encoding. > > Beautiful Soup parses anything you give it, and does the tree traversal stuff for you. You can tell it "Find all the links", or "Find all the links of class externalLink", or "Find all the links whose urls match "foo.com", or "Find the table heading that's got bold text, then give me that text." > > Valuable data that was once locked up in poorly-designed websites is now within your reach. Projects that would have taken hours take only minutes with Beautiful Soup.
Automated Class timetable optimize crawler?
[ "", "python", "screen-scraping", "scheduling", "" ]
I see in MSDN links such as "CompareOrdinal Overloads". How can I write such a link in C#? I tried: ``` <seealso cref="MyMethod">MyMethod Overloads</seealso> ``` But the compiler gives me a warning about being an ambiguous reference for the method which has other overloads. (Beginner question: do I actually need to write this tag to link to the overloads, or is it automatically generated by documentation processors?)
Xml documentation doesn't have a means to reference all overloads of a method. The most popular documentation generator for C# projects is Sandcastle. It will automatically create a link to an overloads list page if necessary. Hence in a members list page the name of an overloaded method will appear only once, clicking it will navigate you to the list of overloads page for that method and from there to a specific overload. Placing a link to the overloads list page in Xml documentation would require intimate knowledge of the external tool being used and probably not a good idea. If you really must have this then perhaps one way is to use an anchor with a specificaly formed ID. Most document generators provide some arcane means of pre or post processing generated files and should give you the opportunity to pick these anchors out and provide an appropriate href for them. OTH, it may be more trouble than its worth ;)
To target *specific* members, I believe you just match the signature: ``` /// <seealso cref="Foo(int)"/> static void Foo() { } /// <seealso cref="Foo()"/> /// <seealso cref="Foo(float)"/> <------ complains static void Foo(int a) { } ``` To be honest, I'm not sure how to generate an "all overloads" link; I'd assume that any sensible generator did this automatically.
How to make a cref to method overloads in a <seealso> tag in C#?
[ "", "c#", "xml-documentation", "" ]
I need to filter result sets from sql server based on selections from a multi-select list box. I've been through the idea of doing an instring to determine if the row value exists in the selected filter values, but that's prone to partial matches (e.g. Car matches Carpet). I also went through splitting the string into a table and joining/matching based on that, but I have reservations about how that is going to perform. Seeing as this is a seemingly common task, I'm looking to the Stack Overflow community for some feedback and maybe a couple suggestions on the most commonly utilized approach to solving this problem.
I solved this one by writing a table-valued function (we're using 2005) which takes a delimited string and returns a table. You can then join to that or use WHERE EXISTS or WHERE x IN. We haven't done full stress testing yet, but with limited use and reasonably small sets of items I think that performance should be ok. Below is one of the functions as a starting point for you. I also have one written to specifically accept a delimited list of INTs for ID values in lookup tables, etc. Another possibility is to use LIKE with the delimiters to make sure that partial matches are ignore, but you can't use indexes with that, so performance will be poor for any large table. For example: ``` SELECT my_column FROM My_Table WHERE @my_string LIKE '%|' + my_column + '|%' ``` . ``` /* Name: GetTableFromStringList Description: Returns a table of values extracted from a delimited list Parameters: @StringList - A delimited list of strings @Delimiter - The delimiter used in the delimited list History: Date Name Comments ---------- ------------- ---------------------------------------------------- 2008-12-03 T. Hummel Initial Creation */ CREATE FUNCTION dbo.GetTableFromStringList ( @StringList VARCHAR(1000), @Delimiter CHAR(1) = ',' ) RETURNS @Results TABLE ( String VARCHAR(1000) NOT NULL ) AS BEGIN DECLARE @string VARCHAR(1000), @position SMALLINT SET @StringList = LTRIM(RTRIM(@StringList)) + @Delimiter SET @position = CHARINDEX(@Delimiter, @StringList) WHILE (@position > 0) BEGIN SET @string = LTRIM(RTRIM(LEFT(@StringList, @position - 1))) IF (@string <> '') BEGIN INSERT INTO @Results (String) VALUES (@string) END SET @StringList = RIGHT(@StringList, LEN(@StringList) - @position) SET @position = CHARINDEX(@Delimiter, @StringList, 1) END RETURN END ```
> I've been through the idea of doing an > instring to determine if the row value > exists in the selected filter values, > but that's prone to partial matches > (e.g. Car matches Carpet) It sounds to me like you aren't including a unique ID, or possibly the primary key as part of values in your list box. Ideally each option will have a unique identifier that matches a column in the table you are searching on. If your listbox was like below then you would be able to filter for specifically for cars because you would get the unique value 3. ``` <option value="3">Car</option> <option value="4">Carpret</option> ``` Then you just build a where clause that will allow you to find the values you need. --- Updated, to answer comment. > How would I do the related join > considering that the user can select > and arbitrary number of options from > the list box? SELECT \* FROM tblTable > JOIN tblOptions ON tblTable.FK = ? The > problem here is that I need to join on > multiple values. I answered a similar question [here](https://stackoverflow.com/questions/327274/mysql-prepared-statements-with-a-variable-size-variable-list#327384). One method would be to build a temporary table and add each selected option as a row to the temporary table. Then you would simply do a join to your temporary table. If you want to simply create your sql dynamically you can do something like this. ``` SELECT * FROM tblTable WHERE option IN (selected_option_1, selected_option_2, selected_option_n) ```
Filtering With Multi-Select Boxes With SQL Server
[ "", "sql", "sql-server", "listbox", "" ]
I've stumbled across [this great post](http://blog.getpaint.net/2008/12/06/a-fluent-approach-to-c-parameter-validation/) about validating parameters in C#, and now I wonder how to implement something similar in C++. The main thing I like about this stuff is that is does not cost anything until the first validation fails, as the `Begin()` function returns `null`, and the other functions check for this. Obviously, I can achieve something similar in C++ using `Validate* v = 0; IsNotNull(v, ...).IsInRange(v, ...)` and have each of them pass on the `v` pointer, plus return a proxy object for which I duplicate all functions. Now I wonder whether there is a similar way to achieve this without temporary objects, until the first validation fails. Though I'd guess that allocating something like a `std::vector` on the stack should be for free (is this actually true? I'd suspect an empty vector does no allocations on the heap, right?)
Other than the fact that C++ does not have extension methods (which prevents being able to add in new validations as easily) it should be too hard. ``` class Validation { vector<string> *errors; void AddError(const string &error) { if (errors == NULL) errors = new vector<string>(); errors->push_back(error); } public: Validation() : errors(NULL) {} ~Validation() { delete errors; } const Validation &operator=(const Validation &rhs) { if (errors == NULL && rhs.errors == NULL) return *this; if (rhs.errors == NULL) { delete errors; errors = NULL; return *this; } vector<string> *temp = new vector<string>(*rhs.errors); std::swap(temp, errors); } void Check() { if (errors) throw exception(); } template <typename T> Validation &IsNotNull(T *value) { if (value == NULL) AddError("Cannot be null!"); return *this; } template <typename T, typename S> Validation &IsLessThan(T valueToCheck, S maxValue) { if (valueToCheck < maxValue) AddError("Value is too big!"); return *this; } // etc.. }; class Validate { public: static Validation Begin() { return Validation(); } }; ``` Use.. ``` Validate::Begin().IsNotNull(somePointer).IsLessThan(4, 30).Check(); ```
Can't say much to the rest of the question, but I did want to point out this: > Though I'd guess that allocating > something like a std::vector on the > stack should be for free (is this > actually true? I'd suspect an empty > vector does no allocations on the > heap, right?) No. You still have to allocate any other variables in the vector (such as storage for length) and I believe that it's up to the implementation if they pre-allocate any room for vector elements upon construction. Either way, you are allocating SOMETHING, and while it may not be much allocation is never "free", regardless of taking place on the stack or heap. That being said, I would imagine that the time taken to do such things will be so minimal that it will only really matter if you are doing it many many times over in quick succession.
Lazy object creation in C++, or how to do zero-cost validation
[ "", "c++", "validation", "" ]
I have a form on an HTML page with multiple submit buttons that perform different actions. However, when the user is typing a value into a text input and hit enters, the browsers generally act as though the next submit button sequentially was activated. I want a particular action to occur, so one solution I found was to put in invisible submit buttons into the HTML directly after the text inputs in question, like this: ``` <input type="text" name="something" value="blah"/> <input type=submit name="desired" value="Save Earth" style="display: none"/> ... <input type=submit name="something_else" value="Destroy Earth" /> ... <input id="foobar" type=submit name="desired" value="Save Earth" /> ``` This works like a charm in most browsers, except that it doesn't in webkit browsers like Safari and Chrome. For some reason they skip over the invisible submit button. I've been trying to figure out how to intercept the enter key press and activate the proper submission using Javascript, but I haven't been able to get it to work. Intercepting the keydown and setting focus on the proper submit does not work. Is there any way using Javascript or otherwise to select which submit button will be used when the user hits the enter key in a text input on an HTML form? *Edit: To clarify, the form can't require Javascript to "work" fundamentally. I don't care if the enter key submission is undesireable without Javascript on webkit browsers, but I can't remove or change the order of the submit buttons.* This is what I tried, it doesn't change the submission behavior in webkit browsers. What worked is to change the *focus()* in the following code to *click()*. ``` document.onkeypress = processKey; function processKey(e) { if (null == e) e = window.event ; if (e.keyCode == 13) { document.getElementById("foobar").click(); // previously: focus() } } ``` **EDIT: FINAL SOLUTION:** Works with every browser and only intercepts the enter key when needed: HTML: ``` <input type="text" name="something" value="blah" onkeydown="return processKey(event)" /> <input type=submit name="desired" value="Save Earth" style="display: none"/> ... <input type=submit name="something_else" value="Destroy Earth" /> ... <input id="foobar" type=submit name="desired" value="Save Earth" /> ``` Javascript: ``` function processKey(e) { if (null == e) e = window.event ; if (e.keyCode == 13) { document.getElementById("foobar").click(); return false; } } ```
One way would be to remove all of the submit buttons and use input buttons to submit the form programatically. This would remove the ability to submit the form by hitting the enter key in a textbox. You could also leave one submit button as the default submit functionality, and use regular button inputs for the others and submit the form programatically. The obvious short-fall of this is that the users would require JavaScript to be enabled. If this isn't a problem this is a consideration for you. **EDIT:** Here, I tried to make an example for you using jQuery (the same functionality can easily be created without jQuery)... let me know if this helps... ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Untitled</title> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript"><!-- $(document).ready(function(){ $("#f input").filter(":text").keydown( function(event) { if (event.keyCode==13) { $(this).nextAll().eq(0).click(); } }); }); //--></script> </head> <body> <form name="f" id="f"> <input type="text" id="t1" name="t1" /><input type="button" id="b1" name="b1" value="button-one" onclick="alert('clicked enter on textbox 1');" /><br /> <input type="text" id="t2" name="t2" /><input type="button" id="b2" name="b2" value="button-two" onclick="alert('clicked enter on textbox 2');" /><br /> <input type="text" id="t3" name="t3" /><input type="button" id="b3" name="b3" value="button-three" onclick="alert('clicked enter on textbox 3');" /><br /> </form> </body> </html> ```
The invisible default submit action is a reasonable approach and doesn't drag JavaScript into the equation. However form elements with 'display: none' aren't generally reliable. I tend to use an absolutely-positioned submit button before the others on the page, positioned off the left-hand-side of the page. It's still pretty ugly, but gets the job done.
Use Javascript to change which submit is activated on enter key press
[ "", "javascript", "html", "webforms", "submit", "user-input", "" ]
Pretty self-explanatory, I tried google and got a lot of the dreaded expertsexchange, I searched here as well to no avail. An online tutorial or example would be best. Thanks guys.
If what you're really doing is manipulating a CSV file itself, Nelson's answer makes sense. However, my suspicion is that the CSV is simply an artifact of the problem you're solving. In C++, that probably means you have something like this as your data model: ``` struct Customer { int id; std::string first_name; std::string last_name; struct { std::string street; std::string unit; } address; char state[2]; int zip; }; ``` Thus, when you're working with a collection of data, it makes sense to have `std::vector<Customer>` or `std::set<Customer>`. With that in mind, think of your CSV handling as two operations: ``` // if you wanted to go nuts, you could use a forward iterator concept for both of these class CSVReader { public: CSVReader(const std::string &inputFile); bool hasNextLine(); void readNextLine(std::vector<std::string> &fields); private: /* secrets */ }; class CSVWriter { public: CSVWriter(const std::string &outputFile); void writeNextLine(const std::vector<std::string> &fields); private: /* more secrets */ }; void readCustomers(CSVReader &reader, std::vector<Customer> &customers); void writeCustomers(CSVWriter &writer, const std::vector<Customer> &customers); ``` Read and write a single row at a time, rather than keeping a complete in-memory representation of the file itself. There are a few obvious benefits: 1. Your data is represented in a form that makes sense for your problem (customers), rather than the current solution (CSV files). 2. You can trivially add adapters for other data formats, such as bulk SQL import/export, Excel/OO spreadsheet files, or even an HTML `<table>` rendering. 3. Your memory footprint is likely to be smaller (depends on relative `sizeof(Customer)` vs. the number of bytes in a single row). 4. `CSVReader` and `CSVWriter` can be reused as the basis for an in-memory model (such as Nelson's) without loss of performance or functionality. The converse is not true.
More information would be useful. But the simplest form: ``` #include <iostream> #include <sstream> #include <fstream> #include <string> int main() { std::ifstream data("plop.csv"); std::string line; while(std::getline(data,line)) { std::stringstream lineStream(line); std::string cell; while(std::getline(lineStream,cell,',')) { // You have a cell!!!! } } } ``` Also see this question: [CSV parser in C++](https://stackoverflow.com/a/1120224/14065)
How can I read and manipulate CSV file data in C++?
[ "", "c++", "csv", "" ]
I was wondering what is the best way to parse a DateTime object to your SQL server. Where you are generating the SQL in code. I have always used something like `DateTime.Now.TolongDateString()` and had good results, apart from today where i got a error, and it made me think. ``` System.Data.SqlClient.SqlException: Conversion failed when converting datetime from character string ``` So what is everyone thoughts and recomendations for a way that will work acrss all SQL server no matter what there setup.. Maybe something like `DateTime.Now.ToString("yyyy/MM/dd")`
there are only 2 safe formats ISO and ISO8601 ISO = yymmdd ISO8601 = yyyy-mm-dd Thh:mm:ss:mmm(no spaces) (notice the T) See also here: [Setting a standard DateFormat for SQL Server](http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/setting-a-standard-dateformat-for-sql-se)
Why not parameterise the query and pass the DateTime value as a SQL DateTime input param? e.g `INSERT INTO SomeTable (Blah, MyDateTime) VALUES (1, @MyDateTime)` Then you can be really sure. Even if you're generating the SQL you should be able to handle this specifically?
Best way to parse DateTime to SQL server
[ "", ".net", "sql", "sql-server", "t-sql", "datetime", "" ]
Given `$displayHeight = "800";`, replace whatever number is at `800` with int value `y_res`. ``` resultString = Regex.Replace( im_cfg_contents, @"\$displayHeight[\s]*=[\s]*""(.*)"";", Convert.ToString(y_res)); ``` In Python I'd use re.sub and it would work. In .NET it replaces the whole line, not the matched group. What is a quick fix?
Building on a couple of the answers already posted. The Zero-width assertion allows you to do a regular expression match without placing those characters in the match. By placing the first part of the string in a group we've separated it from the digits that you want to be replaced. Then by using a zero-width lookbehind assertion in that group we allow the regular expression to proceed as normal but omit the characters in that group in the match. Similarly, we've placed the last part of the string in a group, and used a zero-width lookahead assertion. [Grouping Constructs on MSDN](http://msdn.microsoft.com/en-us/library/bs2twtah.aspx "Grouping Constructs MSDN") shows the groups as well as the assertions. ``` resultString = Regex.Replace( im_cfg_contents, @"(?<=\$displayHeight[\s]*=[\s]*"")(.*)(?="";)", Convert.ToString(y_res)); ``` Another approach would be to use the following code. The modification to the regular expression is just placing the first part in a group and the last part in a group. Then in the replace string, we add back in the first and third groups. Not quite as nice as the first approach, but not quite as bad as writing out the $displayHeight part. [Substitutions on MSDN](http://msdn.microsoft.com/en-us/library/ewy2t5e0.aspx "Substitutions on MSDN") shows how the $ characters work. ``` resultString = Regex.Replace( im_cfg_contents, @"(\$displayHeight[\s]*=[\s]*"")(.*)("";)", "${1}" + Convert.ToString(y_res) + "${3}"); ```
Try this: ``` resultString = Regex.Replace( im_cfg_contents, @"\$displayHeight[\s]*=[\s]*""(.*)"";", @"\$displayHeight = """ + Convert.ToString(y_res) + @""";"); ```
C# regex replace unexpected behavior
[ "", "c#", ".net", "regex", "" ]
I am working on a project that needs to use a database driven MVC scheme where the route to the controllers and views are controlled through a single database table. However, I haven't been able to find any tutorials that demonstrate this with a current version of the framework (they all appear to have been written several versions ago) and I was wondering if anyone has done something like this with a more recent version of the framework or if anyone knows of blogs or tutorials that discuss how to accomplish this in a simple manner. The basic idea is that there will be a sitePage table that will contain pageName, controller, module and view fields. When the request is processed I need to query the database for the given pageName and determine the appropriate controller, module and view and then pass this into the necessary Zend class to continue with the normal routing and processing of the request. Thanks in advance.
I realized that a more elegant approach is indeed to use a router, but for that you would need to create a custom one by extending the Zend\_Controller\_Router\_Abstract class and implementing the "route" method. You get a Zend\_Controller\_Request\_Abstract object as the parameter of the "route" method. There you can talk to the database and then you can use: ``` Zend_Controller_Request_Abstract::setModuleName(), Zend_Controller_Request_Abstract::setControllerName(), Zend_Controller_Request_Abstract::setActionName() ``` to define your route. I hope it helps!
You can also use the routeStartup() method in your plugin. eg: ``` class My_Plugin_PageRoute extends Zend_Controller_Plugin_Abstract { public function routeStartup () { $front = Zend_Controller_Front::getInstance(); $pages = new Model_Pages(); $page_data = $pages ->getPageInfo(); $router = $front->getRouter(); foreach($page_data as $page) { $r = new Zend_Controller_Router_Route( '' . $page -> page_name, array('controller' => 'pages', 'action' => 'index', 'page_id' => $page -> page_id) ); $router->addRoute('pages_' . $page -> page_id, $r); } } } ```
Tutorials For Database-Driven Routing in Zend Framework?
[ "", "php", "zend-framework", "url-routing", "model-view-controller", "database-driven", "" ]
What is the meaning of the .NET 3.5 extension method `Enumerable.First()` when you call it on an instance of the `Dictionary` collection? Does the set of keys determine which item is first, or is it just not defined?
Well, I believe the set of keys *will* determine which item is first, but not in a well-defined (or easy to predict) way. In other words, don't assume that it will always work the same way - it's as unsafe as relying on a hash code implementation staying the same between runs. EDIT: I believe that in fact, the ordering of insertion *does* matter, contrary to my previous ideas. However, this *is* implementation-specific (so could easily change in the next version). I believe that with the current implementation, the first entry added will be the first one returned *if* it hasn't been removed. If the first entry added is ever removed, the ordering is broken - it's not that the *earliest* entry is removed. Here's an example: ``` using System; using System.Collections.Generic; class Test { static void Main(string[] args) { var dict = new Dictionary<int, int>(); dict.Add(0, 0); dict.Add(1, 1); dict.Add(2, 2); dict.Remove(0); dict.Add(10, 10); foreach (var entry in dict) { Console.WriteLine(entry.Key); } Console.WriteLine("First key: " + dict.First().Key); } } ``` The results are 10, 1, 2, and "First key: 10" - showing that the *latest* added entry ends up being returned first. However, I'd like to stress again that everything can change between versions of the framework.
If you need the first item in a dictionary, you're best using a SortedDictionary. I would think the First() method will just return the first item which happens to be at the top, but not necessarily the first one that was added.
Who's on Dictionary<>.First()?
[ "", "c#", ".net", "" ]
I want to run a console application that will output a file. I user the following code: ``` Process barProcess = Process.Start("bar.exe", @"C:\foo.txt"); ``` When this runs the console window appears. I want to hide the console window so it is not seen by the user. Is this possible? Is using Process.Start the best way to start another console application?
``` Process p = new Process(); StreamReader sr; StreamReader se; StreamWriter sw; ProcessStartInfo psi = new ProcessStartInfo(@"bar.exe"); psi.UseShellExecute = false; psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; psi.RedirectStandardInput = true; psi.CreateNoWindow = true; p.StartInfo = psi; p.Start(); ``` This will start a child process without displaying the console window, and will allow the capturing of the StandardOutput, etc.
Check into ProcessStartInfo and set the WindowStyle = ProcessWindowStyle.Hidden and the CreateNoWindow = true.
How do I hide a console application user interface when using Process.Start?
[ "", "c#", ".net", "" ]
A little background: I'm creating a set of adapters to allow communication with mobile devices over different cellular networks. This will be achieved using a class factory pattern. At least one of the networks requires a service reference to communicate with their devices through a web service. So far I've got 3 assemblies so far which represent: * An assembly which contains the main adapter library: this contains + The interface definition for each of the adapters + Base classes + The class factory to instantiate the specified adapter at runtime. * An assembly for each network adapter implementation. * An assembly that contains my main application. Given that I don't want to be adding service references and their configuration to the main application assembly [as that's not relevant to the main application], how do I force each assembly's service reference to get its configuration from its own app.config? If I have the service reference configuration in the main app.config, everything works just fine, but if I move the configuration to the adapter's app.config everything stops working throwing the following exception at the point where I new up the Soap1Client. > "Could not find default endpoint element that references contract 'MobileService.Service1Soap' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element."
In the end, I just removed the service reference and added a web reference [i.e. did it the 2.0 way]. For some reason the web reference will access its own app.config instead of the main application's app.config. Far easier than the alternative...
You can set all the options programatically.
How do I move service references to their own assembly?
[ "", "c#", ".net", "asp.net", "vb.net", "web-services", "" ]
we have an application that needs to send out various different types of template email. The current code is very cumbersome and not very flexible. Does any one konw of a library to help with this type of work... We are looking for some kind of templating library for email.
[StringTemplate](http://www.stringtemplate.org) is also a very nice template engine.
Perhaps [Apache Velocity](https://velocity.apache.org/) could work for you?
Suggestions for Java email templating?
[ "", "java", "email", "frameworks", "templates", "" ]
I want to create variables as `a1`,`a2`,`a3`...`a10`. For that I used a for loop. As the variable in loop increments I need to create a variable as above. Can anyone give me an idea? At the time of creation I also need to be able to assign values to them. That's where I'm getting syntax error.
Following what S.Lott said, you can also use a dict, if you really nead unique names and that the order of the items is not important: ``` data = {} for i in range(0, 10): data['a%d' % i] = i >>>data {'a1': 1, 'a0': 0, 'a3': 3, 'a2': 2, 'a5': 5, 'a4': 4, 'a7': 7, 'a6': 6, 'a9': 9, 'a8': 8} ``` I would add that this is very dangerous to automate variable creation like you want to do, as you might overwrite variables that could already exist.
Usually, we use a list, not a bunch of individual variables. ``` a = 10*[0] a[0], a[1], a[2], a[9] ```
need help-variable creation in Python
[ "", "python", "variables", "" ]
I have a table in PostgreSQL where the schema looks like this: ``` CREATE TABLE "foo_table" ( "id" serial NOT NULL PRIMARY KEY, "permalink" varchar(200) NOT NULL, "text" varchar(512) NOT NULL, "timestamp" timestamp with time zone NOT NULL ) ``` Now I want to make the permalink unique across the table by `ALTER`-ing the table.
I figured it out from the PostgreSQL docs, the exact syntax is: ``` ALTER TABLE the_table ADD CONSTRAINT constraint_name UNIQUE (thecolumn); ``` Thanks [Fred](https://stackoverflow.com/users/55774/frederik-gheysels).
Or, have the DB automatically assign a constraint name using: ``` ALTER TABLE foo ADD UNIQUE (thecolumn); ```
How do I ALTER a PostgreSQL table and make a column unique?
[ "", "sql", "postgresql", "unique-constraint", "" ]