Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am trying to make a Java application thread-safe. Unfortunately, it was originally designed for a single-user mode and all the key classes are instantiated as singletons. To make matters worse, there is a whole bunch of interfaces working as constants containers and numerous static fields. What would be considered as a good practice in this case? * There is a single entry point, so I could synchronize that and just use pooling (sort of), but if the calls take more than a minute on average, all other threads in the queue would have to wait for a long time... * Since the test code coverage is not quite optimal and I can't be sure if I overlooked something, some hints about bad implementation patterns (similar to those stated above) in this area would be useful. * I know the best thing would be to rewrite the whole structure, but this isn't an option.
@coldphusion, you'll have to read/analyze code. Using an automated tool, if such a tool exists, would be like shooting yourself in the foot. Plus, not everything has to be thread-safe. If an object will never be accessed from multiple threads, no need to make it thread-safe. If an object is immutable, then it's already thread-safe. Be ready to tell your boss "It won't take a few hours or a day, even you know it, so stop asking." I recommend reading [Java Concurrency In Practice](http://jcip.net/).
It doesn't sound like there is a quick fix for this. You should probably start by refactoring the existing code to use good design patterns, with an eye for multi-threading it in the future. Implement the multi-threading as a later step, after you've cleaned it up.
Thread-safety refactoring
[ "", "java", "refactoring", "thread-safety", "" ]
I've never used the ListView control before and am trying to programmatically insert items at run-time. I have a column named Title. And once the user has selected a path from the FolderBrowserDialog. I need to be able to grab all the names of the files inside the SelectedPath and add the names of files as items inside the Title column. Can anybody please help me to do this? Thank you
I think the best way of doing this would be to use FileInfo as rather than getting the FilePaths just as strings. This way, you can display more information about the file in the ListView if required (say for instance you set the View to detailed, then you could add groups for FileInfo (Size etc.)). You would do this by adding groups to the list view then adding the items with SubItems: ``` DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\myDir"); FileInfo[] files = directoryInfo.GetFiles(); foreach(FileInfo fileInfo in files) { ListViewItem newItem = new ListViewItem(); newItem.Text = fileInfo.Name; newItem.SubItems.Add(fileInfo.Length); //Must have a group added to the ListView (called File Size in this example) listView1.Items.Add(newItem); } ``` Obviously you don't have to use groups and SubItems, this would still work fine without them (just remove the SubItems part).
Try this code: ``` string[] filePaths = Directory.GetFiles("c:\\MyDir\\"); foreach (string str in filePaths) { ListViewItem lvi = new ListViewItem(str); ListView1.Items.Add(lvi) } ```
ListView - Inserting Items
[ "", "c#", "listview", "insert", "" ]
On facebook for example - when you put your mouseover a news item, a remove button appears. How can I go about making this happen? Thanks, Elliot
### Modern Browsers In modern browsers, you can leverage the `:hover` pseudo class in our selector. As an example, consider the following markup: ``` <div class="item"> <p>This is a long string of text</p> <div class="adminControls"> <a href="#" title="Delete">Delete Item</a> </div> </div> ``` By default, we would want the `.adminControls` to be hidden. They should, however, become visible once the user has hovered the `.item` element: ``` .item .adminControls { display: none; } .item:hover .adminControls { display: block; } ``` ### JavaScript and jQuery If you're using [jQuery](http://www.jquery.com), you can accomplish this rather easily using the $.hover() method. If you're using Prototype, you can get the [protoHover plugin](http://code.google.com/p/protohover/) to achieve the same result, or view [this blog post](http://www.zurielbarron.com/2009/01/30/jquery-hover-with-prototype/). ``` $("div.item").hover( function () { $(this).find(".adminControls").show(); }, function () { $(this).find(".adminControls").hide(); } ); ``` That would accomplish the show/hide effect for the following: ``` <div class="item"> <p>This is a long string of text</p> <div class="adminControls"> <a href="#" title="Delete">Delete Item</a> </div> </div> <div class="item"> <p>This is a long string of text</p> <div class="adminControls"> <a href="#" title="Delete">Delete Item</a> </div> </div> <div class="item"> <p>This is a long string of text</p> <div class="adminControls"> <a href="#" title="Delete">Delete Item</a> </div> </div> ```
If you don't need to support IE6, you can use the :hover pseudoclass like so: CSS: ``` .link { display: none; } .item:hover > .link { display: inline; } ``` HTML: ``` <div class="item"> <a href="#" class="link">Remove</a> Lorem Ipsum... </div> ```
Edit link on div mouseover
[ "", "javascript", "" ]
I am trying to copy whole directory tree from server's shared folder to my local machine, I found [Best way to copy the entire contents of a directory in C#](https://stackoverflow.com/questions/58744/best-way-to-copy-the-entire-contents-of-a-directory-in-c) post and decide to use that but as I guess DirectoryInfo doesn't support network shares, how can I change this code to work with network shares as a source? ``` public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target) { foreach (DirectoryInfo dir in source.GetDirectories()) CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name)); foreach (FileInfo file in source.GetFiles()) file.CopyTo(Path.Combine(target.FullName, file.Name)); } ``` **EDIT** and the call is ``` CopyFilesRecursively(new DirectoryInfo ("\\192.168.0.11\Share"), new DirectoryInfo ("D:\Projects\")); ``` and getting error message ``` Could not find a part of the path 'D:\192.168.0.11\Share'. ``` Thanks a lot!
What about escaping the strings? ``` CopyFilesRecursively( new DirectoryInfo(@"\\192.168.0.11\Share"), new DirectoryInfo(@"D:\Projects\")); ``` MSDN says that [DirectoryInfo can handle UNC paths](http://msdn.microsoft.com/en-us/library/system.io.directoryinfo%28VS.80%29.aspx)
Also, try: ``` DirectoryInfo di=new DirectoryInfo(@"\\<server>\<share>"); ``` Specific point being the @ symbol; this works on my local network.
copy whole shared directory from network
[ "", "c#", ".net", "copy", "" ]
I wrote an extension in VB.NET for StringBuilder to add a `AppendFormattedLine` method (so I would not have to use one of the arguments for a new line character): ``` Imports System.Runtime.CompilerServices Public Module sbExtension <Extension()> _ Public Sub AppendFormattedLine(ByVal oStr As System.Text.StringBuilder, _ ByVal format As String, _ ByVal arg0 As Object) oStr.AppendFormat(format, arg0).Append(ControlChars.NewLine) End Sub <Extension()> _ Public Sub AppendFormattedLine(ByVal oStr As System.Text.StringBuilder, _ ByVal format As String, ByVal arg0 As Object, _ ByVal arg1 As Object) oStr.AppendFormat(format, arg0, arg1).Append(ControlChars.NewLine) End Sub <Extension()> _ Public Sub AppendFormattedLine(ByVal oStr As System.Text.StringBuilder, _ ByVal format As String, _ ByVal arg0 As Object, _ ByVal arg1 As Object, _ ByVal arg2 As Object) oStr.AppendFormat(format, arg0, arg1, arg2).Append(ControlChars.NewLine) End Sub <Extension()> _ Public Sub AppendFormattedLine(ByVal oStr As System.Text.StringBuilder, _ ByVal format As String, _ ByVal ParamArray args() As Object) oStr.AppendFormat(format, args).Append(ControlChars.NewLine) End Sub End Module ```
Here is the ported code that I came up with: ``` using System; using System.Text; public static class ExtensionLibrary { public static void AppendFormattedLine(this StringBuilder sb, string format, object arg0) { sb.AppendFormat(format, arg0).Append(Environment.NewLine); } public static void AppendFormattedLine(this StringBuilder sb, string format, object arg0, object arg1) { sb.AppendFormat(format, arg0, arg1).Append(Environment.NewLine); } public static void AppendFormattedLine(this StringBuilder sb, string format, object arg0, object arg1, object arg2) { sb.AppendFormat(format, arg0, arg1, arg2).Append(Environment.NewLine); } public static void AppendFormattedLine(this StringBuilder sb, string format, params object[] args) { sb.AppendFormat(format, args).Append(Environment.NewLine); } } ``` Hopefully this will come in useful for someone! **improved code, thanks joel, luke & jason.**
I wouldn't nest the `string.Format()` calls like that. Did you know that `string.Format()` creates a new StringBuilder behind the scenes and calls it's `AppendFormat()` method? Using the first method up there as an example, this should be much more efficient: ``` sb.AppendFormat(format, arg0).Append(Environment.NewLine); ``` You should make the same change to your VB code as well.
How do I port an extension in VB.NET to C#?
[ "", "c#", "vb.net", "extension-methods", "stringbuilder", "" ]
Thanks to a previous question, I found out how to pull the most recent data based on a linked table. BUT, now I have a related question. The solution that I found used row\_number() and PARTITION to pull the most recent set of data. But what if there's a possibility for zero or more rows in a linked table in the view? For example, the table FollowUpDate might have 0 rows, or 1, or more. I just want the most recent FollowUpDate: ``` SELECT EFD.FormId ,EFD.StatusName ,MAX(EFD.ActionDate) ,EFT.Name AS FormType ,ECOA.Account AS ChargeOffAccount ,ERC.Name AS ReasonCode ,EAC.Description AS ApprovalCode ,MAX(EFU.FollowUpDate) AS FollowUpDate FROM ( SELECT EF.FormId, EFD.ActionDate, EFS.Name AS StatusName, EF.FormTypeId, EF.ChargeOffId, EF.ReasonCodeId, EF.ApprovalCodeId, row_number() OVER ( PARTITION BY EF.FormId ORDER BY EFD.ActionDate DESC ) DateSortKey FROM Extension.FormDate EFD INNER JOIN Extension.Form EF ON EFD.FormId = EF.FormId INNER JOIN Extension.FormStatus EFS ON EFD.StatusId = EFS.StatusId ) EFD INNER JOIN Extension.FormType EFT ON EFD.FormTypeId = EFT.FormTypeId LEFT OUTER JOIN Extension.ChargeOffAccount ECOA ON EFD.ChargeOffId = ECOA.ChargeOffId LEFT OUTER JOIN Extension.ReasonCode ERC ON EFD.ReasonCodeId = ERC.ReasonCodeId LEFT OUTER JOIN Extension.ApprovalCode EAC ON EFD.ApprovalCodeId = EAC.ApprovalCodeId LEFT OUTER JOIN (Select EFU.FormId, EFU.FollowUpDate, row_number() OVER (PARTITION BY EFU.FormId ORDER BY EFU.FollowUpDate DESC) FUDateSortKey FROM Extension.FormFollowUp EFU INNER JOIN Extension.Form EF ON EFU.FormId = EF.FormId) EFU ON EFD.FormId = EFU.FormId WHERE EFD.DateSortKey = 1 GROUP BY EFD.FormId, EFD.ActionDate, EFD.StatusName, EFT.Name, ECOA.Account, ERC.Name, EAC.Description, EFU.FollowUpDate ORDER BY EFD.FormId ``` If I do a similar pull using row\_number() and PARTITION, I get the data only if there is at least one row in FollowUpDate. Kinda defeats the purpose of a LEFT OUTER JOIN. Can anyone help me get this working?
I rewrote your query - you had unnecessary subselects, and used row\_number() for the FUDateSortKey but didn't use the column: ``` SELECT t.formid, t.statusname, MAX(t.actiondate) 'actiondate', t.formtype, t.chargeoffaccount, t.reasoncode, t.approvalcode, MAX(t.followupdate) 'followupdate' FROM ( SELECT t.formid, fs.name 'StatusName', t.actiondate, ft.name 'formtype', coa.account 'ChargeOffAccount', rc.name 'ReasonCode', ac.description 'ApprovalCode', ffu.followupdate, row_number() OVER (PARTITION BY ef.formid ORDER BY t.actiondate DESC) 'DateSortKey' FROM EXTENSION.FORMDATE t JOIN EXTENSION.FORM ef ON ef.formid = t.formid JOIN EXTENSION.FORMSTATUS fs ON fs.statusid = t.statusid JOIN EXTENSION.FORMTYPE ft ON ft.formtypeid = ef.formtypeid LEFT JOIN EXTENSION.CHARGEOFFACCOUNT coa ON coa.chargeoffid = ef.chargeoffid LEFT JOIN EXTENSION.REASONCODE rc ON rc.reasoncodeid = ef.reasoncodeid LEFT JOIN EXTENSION.APPROVALCODE ac ON ac.approvalcodeid = ef.approvalcodeid LEFT JOIN EXTENSION.FORMFOLLOWUP ffu ON ffu.formid = t.formid) t WHERE t.datesortkey = 1 GROUP BY t.formid, t.statusname, t.formtype, t.chargeoffaccount, t.reasoncode, t.approvalcode ORDER BY t.formid ``` The change I made to allow for FollowUpDate was to use a LEFT JOIN onto the FORMFOLLOWUP table - you were doing an INNER JOIN, so you'd only get rows with FORMFOLLOWUP records associated.
It's pretty hard to guess what's going on without table definitions and sample data. Also, this is confusing: "the table FollowUpDate might have 0 rows" and you "want the most recent FollowUpDate." (especially when there is no table named FollowUpDate) There is no "most recent FollowUpDate" if there are zero FollowUpDates. Maybe you want ``` WHERE <follow up date row number> in (1,NULL) ```
Max date in view on left outer join
[ "", "sql", "t-sql", "" ]
I have a LINQ query which returns all the values inside a Dictionary, conditional upon something: ``` var apps = from entry in shape.Decorators where entry.Value == DecoratorLayoutStyle.App select entry.Key; ``` shape.Decorators is a ``` Dictionary<Shape, DecoratorLayoutStyle> ``` Is there something terser, and/or can I use a combination of lambdas or something?
``` var apps = shape.Decorators .Where(x=>x.Value == DecoratorLayoutStyle.App) .Select(x=>x.Key); ``` I think yours is just as fine.
That looks plenty terse to me, I guess you could use the extension functions instead of the from/select linq syntax, but that wouldn't be too different. More imporantly, I'm not sure you ***want*** terser. The current format is very readable, and clearly documents exactly what you're trying to do.
Lambda expression to grab all values inside a Dictionary
[ "", "c#", "linq", "lambda", "" ]
This problem has been getting at me for a while now. Is there an easier way to write nested `for` loops in python? For example if my code went something like this: ``` for y in range(3): for x in range(3): do_something() for y1 in range(3): for x1 in range(3): do_something_else() ``` would there be an easier way to do this? I know that this code works but when you indent instead of using 2 spaces, like me, it can get to be a problem. Oh in the example there were only 4 nested `for` loops to make things easier.
If you're frequently iterating over a Cartesian product like in your example, you might want to investigate [Python 2.6's itertools.product](http://docs.python.org/library/itertools.html#itertools.product) -- or write your own if you're in an earlier Python. ``` from itertools import product for y, x in product(range(3), repeat=2): do_something() for y1, x1 in product(range(3), repeat=2): do_something_else() ```
This is fairly common when looping over multidimensional spaces. My solution is: ``` xy_grid = [(x, y) for x in range(3) for y in range(3)] for x, y in xy_grid: # do something for x1, y1 in xy_grid: # do something else ```
In python is there an easier way to write 6 nested for loops?
[ "", "python", "for-loop", "nested-loops", "" ]
The following code works fine in FF chrome etc but not IE, anyone know why? Basically everything works accept the replacement of the image attribute ``` $("#container #main_image img#largeId").attr({ src: largePath }); ``` Even the rest of the function ie the swapping classes works, just not the image replacement. The full example can be seen here [example](http://www.keith-ingham.com/) click on an image and try and swap between the thumbnails on the right in the modal window. The effect i'm going for is similar to that from this website [webdesignerwall](http://www.webdesignerwall.com/demo/jquery/img-replacement.html), the jQuery is almost exactly the same - although this works with IE!!!! ``` jQuery(document).ready(function($) { $("a.group").fancybox({ 'frameWidth':966, 'frameHeight': 547, 'hideOnContentClick': false, 'overlayOpacity': 0.85, 'callbackOnShow': function() { $("#container ul#thumbnails li a").click(function(){ var largePath = $(this).attr("title"); $("#container #main_image img#largeId").fadeOut().hide(); $("#container #main_image img#largeId").attr({ src: largePath }); $("#container #main_image img#largeId").fadeIn("slow"); $('.active').removeClass('active'); $(this).addClass("active");return false; }); } }); }); ```
Basically this has been resolved by changing the destination element from an 'ID' to a 'class'. This needs to be done because of Fancybox duplicating the id when calling the modal window! Many thanks for everyones helps here!
Ok, I have worked it out. it was painfull and I conclude that the plugin is plain wrong:) The plugin duplicates the hidden content and inserts it into the 'box'. This means you end up with duplicate id's everywhere which of course is invalid and funny things start to happen. When you do you selector for $('#largeId') it actually references the original hidden photo. You can see this if you remove the display:none style from #hidden. Conclusion is to use a lightbox that actually appends the content rather than duplicates it. I do not like what the author has done hear. You could amend the plugin code to use append instead of using (line 112 of the plugin) like this ``` var newHtml = $('<div id="fancy_div" />').append(target); _set_content(newHtml.html(), opts.frameWidth, opts.frameHeight); ``` You will then have to deal with putting the html back when the lightbox is closed. However I would be more inclined to find a better lightbox!
Anyone tell me why this Jquery doesn't work in IE?
[ "", "javascript", "jquery", "internet-explorer", "jquery-plugins", "" ]
Is there a simple way of dynamically scaling an image in php? Id like to specifically use some kind of function where i can insert it into my heml such as ``` <img src=image.php?img=boss.jpg&width=500> ``` and of course it would then scale the image to whatever height constrains it to 500px wide i appreciate all input, thanks. **EDIT** does need to include jpg png and gif file types
I prefer [WideImage](http://wideimage.sourceforge.net/wiki/MainPage) library, because it's really really easy to use. In your case, everything you have to do is: ``` $img_path = $_GET['img']; $new_width = $_GET['width']; $new_img = wiImage::load($img_path)->resize($new_width); header('Content-Type: image/jpeg'); echo $new_img->asString('jpg', 80); ``` And it supports jpeg, png, gif, gd, ...
You could use a GD library and create a simple script that would scale the image as you like. Check the [manual](http://php.net/manual/en/book.image.php)
dynamically scale images in php jpg/png/gif
[ "", "php", "image", "resize", "image-scaling", "" ]
How can I set the column width of a c# winforms `listview` control to auto. Something like width = -1 / -2 ?
You gave the answer: -2 will autosize the column to the length of the text in the column header, -1 will autosize to the longest item in the column. [All according to MSDN](http://msdn.microsoft.com/en-us/library/system.windows.forms.columnheader.width.aspx). Note though that in the case of -1, you will need to set the column width after adding the item(s). So if you add a new item, you will also need to assign the width property of the column (or columns) that you want to autosize according to data in `ListView` control.
Use this: ``` yourListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); yourListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); ``` from [here](https://stackoverflow.com/a/11820994/2040375)
C# ListView Column Width Auto
[ "", "c#", ".net", "winforms", "listview", "width", "" ]
I've added a new column, `packageNo`, to my table: ``` create table Packages( id varchar(20) primary key, -- ok, I know :) orderNo uniqueIdentifier not null, orderlineNo int not null, packageNo int not null default(0) ) ``` Now I want to generate the `packageNo` with the following rules: reset it for each order ascendantfor order, orderline My problem is that the script I wrote uses 15 minutes for 26500 rows on my testServer. Here it is: ``` set NoCount ON declare @Counter int declare @handledCounter int declare @currentorder uniqueIdentifier declare @fetchedOrder uniqueIdentifier declare @fetchedId varchar(20) -- will using PK speed up things? declare PackageNo_Cursor cursor for select orderNo, id from packages order by orderNo, orderlineNo for update of packageNo open PackageNo_Cursor fetch next from PackageNo_Cursor into @fetchedOrder, @fetchedId set @currentOrder = @fetchedOrder set @counter = 0 set @handledCounter = 0 while @@fetch_status = 0 begin if (@currentOrder <> @fetchedOrder) begin -- reset counter for each order set @currentOrder = @fetchedOrder set @counter = 0 end set @counter = @counter + 1 set @handledCounter = @handledCounter +1 if (@handledCounter % 50 = 0) begin print 'handled = ' + cast(@handledCounter as varchar) end update packages set packageNo = @counter where current of PackageNo_Cursor fetch next from PackageNo_Cursor into @fetchedOrder, @fetchedId end close PackageNo_Cursor deallocate PackageNo_Cursor ``` This should result in: ``` id - orderno - lineNo - packageNo (what I need to set) ean1 - guid1 - 1 - 1 ean2 - guid1 - 2 - 2 ean3 - guid2 - 1 - 1 ean15- guid2 - 3 - 2 ean15- guid2 - 4 - 3 ``` Can I make this run any faster?
You don't want to use a cursor, you want to do this as a set, like so: ``` update p set packageNo = r.packageNo from packages p inner join (select orderNo, orderLineNo, ROW_NUMBER() OVER(PARTITION BY orderNo ORDER BY orderLineNo) as packageNo from packages) r on p.orderNo = r.orderNo and p.orderLineNo = r.orderLineNo ``` This will leverage SQL Server's [`ROW_NUMBER`](http://msdn.microsoft.com/en-us/library/ms186734.aspx) function to get you the correct count by each line. Using `UPDATE...FROM`, we can create an `inner join` from which to update. This is vastly more efficient than the cursor. See, cursors add an iterative ability to a procedural and set based language (SQL). The two don't play well together. That `update` statement is being called in order for each row (and opening/committing a transaction, to boot). If you do it all in one statement, SQL can parallelize this to make it much faster. The standard rule is this: **Use cursors as sparingly as possible.** There are some fringe cases where they're necessary, but if you aren't doing massive amounts of SQL administration a day, it's doubtful you'll ever come across those cases.
Something like, not tested ``` update p set packageNo = p2.Ranking from packages p JOIN (SELECT orderNo, orderlineNo, ROW_NUMBER() OVER (PARTITION BY orderNo ORDER BY orderlineNo) AS Ranking FROM packages) p2 ON p.orderNo = p2.orderNo AND p.orderlineNo= p2.orderlineNo ```
Slow SQL Updates within a Cursor
[ "", "sql", "sql-server", "performance", "t-sql", "" ]
Code 1: ``` var Something = { name: "Name", sayHi: function(){ alert(Something.name); } } ``` Code 2: ``` function Something(){ this.name = "Name"; } Something.prototype.sayHi = function(){ alert(Something.name); } ``` **Edit:** So, Guys, you mean the Second one is better? or more "formal" ?
Basically in the first example you declare an [object literal](https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Literals#Object_Literals) which is actually already an object instance. In your second example, you define a constructor function which can be used with the [`new`](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/new_Operator) operator to create object instances. Object literals can be also used to create new instances of objects and do prototypal inheritance, Douglas Crockford promotes also this technique. Basically you can have an `object` operator: ``` function object(o) { function F() {} F.prototype = o; return new F(); } ``` This helper function can be used in a very intuitive and convenient way. It basically receive an object as a parameter, inside the function a *new object instance* is created, the old object is *chained* to the new object's prototype, and its returned. It can be used like this: ``` var oldObject = { firstMethod: function () { alert('first'); }, secondMethod: function () { alert('second'); }, }; var newObject = object(oldObject); newObject.thirdMethod = function () { alert('third'); }; var otherObject = object(newObject); otherObject.firstMethod(); ``` You can go further as you want, making new instances from the previously defined objects. Recommended : * [Prototypal Inheritance in JavaScript](http://javascript.crockford.com/prototypal.html) * [Advanced JavaScript (Video)](http://video.yahoo.com/watch/111585)
In the **first** code snippet, `Something` is a simple object, and not a constructor. In particular, you cannot call: ``` var o = new Something(); ``` Such a form of creating objects is perfect for singletons; objects of which you only need one instance. In the **second** snippet, `Something` is a constructor, and you can use the `new` keyword with it. **Edit:** Also, in your second snippet, since you are using `Something.name` as opposed to `this.name`, it will always alert the name of the constructor itself, which is *"Something"*, unless you override that property with something like `Something.name = "Cool";`. You probably wanted that line to say: ``` alert(this.name); ```
What is the difference between these two code samples?
[ "", "javascript", "" ]
I need to extract records from a table, copy the data to a second table and then update the records in the first table to indicate that they have been copied across successfully. My current SP code is this: ``` SELECT TBL_ADDRESSBOOKADDRESSES.* FROM TBL_ADDRESSBOOKADDRESSES INNER JOIN TBL_CAMPAIGNS ON TBL_ADDRESSBOOKADDRESSES.adds_ABMId = TBL_CAMPAIGNS.campaign_AddressBook WHERE TBL_CAMPAIGNS.campaign_Status = 1 ``` Now once the above is performed i need to insert this data into a second table called TBL\_RECIPIENTS. Assume that the columns are simply named col\_1, col\_2, col\_3 .... col\_5 in TBL\_ADDRESSBOOKADDRESSES and that this is the same in TBL\_RECIPIENTS. Once this action is performed i need to update **TBL\_CAMPAIGNS.campaign\_Status = 2** Ideally this should only be for those records that have actually been updated(in case script gets stopped mid way through due to server crash etc) Please let me know if you need anything clarifying. Many Thanks! --- Ive taken the advise kindly given below and come up with the working code below. Ive read tutorial which suggested adding try/catch to ensure rollback if any errors occurr. Is my code below adequate in this respect?? Any suggest would be gratefully received. Thanks. ``` CREATE PROCEDURE web.SERVER_create_email_recipients AS BEGIN TRY --sets (n) campaigns ready for transfer of emails to mailing list UPDATE TOP(1) TBL_CAMPAIGNS SET TBL_CAMPAIGNS.campaign_Status = 1 WHERE TBL_CAMPAIGNS.campaign_Status = 0 --finds above marked campaigns, retreives addresses then copies them to TBL_CAMPAIGNRECIPIENTS ready for auto mailout INSERT TBL_CAMPAIGNRECIPIENTS (recip_CampaignId, recip_Email, recip_Forename, recip_Surname, recip_adds_Key) SELECT C.Campaign_AddressBook, ABA.adds_Email, ABA.adds_RecipientForename, ABA.adds_RecipientSurname, ABA.adds_Key FROM TBL_ADDRESSBOOKADDRESSES ABA JOIN TBL_CAMPAIGNS C ON ABA.adds_ABMId = C.campaign_AddressBook WHERE C.campaign_Status = 1 --checks that above emails have been copied across and then sets the campaigns status accordingly UPDATE C SET C.campaign_Status = 2 From TBL_CAMPAIGNS C JOIN TBL_ADDRESSBOOKADDRESSES aba ON aba.adds_ABMId = C.campaign_AddressBook JOIN TBL_CAMPAIGNRECIPIENTS r on aba.adds_Key = r.recip_adds_Key WHERE C.campaign_Status = 1 END TRY BEGIN CATCH -- Whoops, there was an error IF @@TRANCOUNT > 0 ROLLBACK -- Raise an error with the details of the exception DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY() --throws out error to logs? RAISERROR(@ErrMsg, @ErrSeverity, 1) END CATCH ```
I've made some guesses about your structure, the joins may not be correct ``` INSERT TBL_RECIPIENTS (Col1, Col2, COl3) SELECT ABA.Col1, ABA.Col2,ABA.Col3 FROM TBL_ADDRESSBOOKADDRESSES ABA INNER JOIN TBL_CAMPAIGNS C ON ABA.adds_ABMId = C.campaign_AddressBook WHERE TBL_CAMPAIGNS.campaign_Status = 1 UPDATE C SET C.campaign_Status = 2 From TBL_CAMPAIGNS C JOIN TBL_ADDRESSBOOKADDRESSES aba on aba.adds_ABMId = C.campaign_AddressBook JOIN TBL_RECIPIENTS r on aba.id = r.sameid WHERE TBL_CAMPAIGNS.campaign_Status = 1 ``` Note I did not use select \* which should never be used in production code. Also I used aliases to make the code easier to read.
Have you considered to put it all inside a transaction? Example: DECLARE @ErrorCode INT ``` BEGIN TRAN UPDATE Authors SET Phone = '911' WHERE au_id = 2 SELECT @ErrorCode = @@ERROR IF (@intErrorCode <> 0) GOTO ErrExit DELETE Authors WHERE Phone = '911' au_id <> 2 SELECT @ErrorCode = @@ERROR IF @ErrorCode <> 0) GOTO ErrExit COMMIT TRAN ErrExit; IF (@intErrorCode <> 0) ROLLBACK TRAN ``` If the update or the delete gives an error the transaction will be rolled back. If the system crashes before the commit the sql server does a rollback, because there is an uncommited transaction
Combining INSERT and UPDATE statement (SQL2005 Stored Procedure)
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "stored-procedures", "" ]
I use the Exiv2 command line tool on Linux to edit image metadata like so: ``` exiv2 -M"set Iptc.Application2.Caption String This is my caption....." modify IMG.jpg ``` I want to execute this from PHP, using a caption provide by a user. This will work if the user enters no special characters: ``` exec('/usr/local/bin/exiv2 -M"set Iptc.Application2.Caption String '.$caption.'" modify IMG.jpg'); ``` I need to allow the user special characters such as single and double quotes. I would like to use escapeshellcmd() to prevent malicious data. How can I correctly escape the command and the argument so that it works? I have tried many options but I can't get it right.
Yes, this is a hard problem, because the command is using non-standard shell arguments (like it's own little meta-language). ImageMagick has the same issues. If you simply use escapeshellarg() within a double-quoted string, it is rendered useless. escapeshellcmd() does escape all special characters, and is safe for use in a double-quoted string. So you need to hard code single quotes around it to make it work right. ``` exec('/usr/local/bin/exiv2 -M"set Iptc.Application2.Caption String \'' . escapeshellcmd($caption) . '\'" modify IMG.jpg'); ``` --- The reason escapeshellarg() will not work in a single quoted string is: ``` # for this input: The smith's "; rm -rf *; echo "went to town # after escapeshellarg() 'The smith\'s "; rm -rf *; echo "went to town' # Works fine if left as a top-level argument /usr/bin/command 'The smith\'s "; rm -rf *; echo "went to town' # BUT if put in a double-quoted string: /usr/bin/command "subcommand1 'The smith\'s "; rm -rf *; echo "went to town'" # it is broken into 3 shell commands: /usr/bin/command "something and 'The smith\'s "; rm -rf *; echo "went to town'" # bad day... ```
Because of Exiv2's non-standard shell arguments, it is not easy to reach a simple and robust solution to handle user-supplied quotes correctly. There is another solution that is likely to be far more reliable and easy to maintain with a small performance penalty. Write the Exiv2 instructions to a file `cmds.txt`, then call: ``` exiv2 -m cmds.txt IMG.jpg ``` to read the instructions from the file. Update: I have implemented this method and it requires no escaping of the user-supplied data. This data is written directly to a text file which is read in by Exiv2. The Exiv2 command file format is very simple and newline-terminated, allow no escaping within values, so all I need to do is prevent newlines from passing through, which I was not allowing anyway.
How to escape php exec() command with quotes
[ "", "php", "escaping", "exec", "exiv2", "" ]
I need a script that I can put on any page in an application and it will run X amount of time. When it hits the amount of time that is specified in the JS it will open either an overlay on the page or a child popup window. Inside either window, I will give you what the text should say. In the new window, they will have two buttons `resume` `logout` if they click resume you will kill the overlay or popup window and refresh the parent page. If they click logout you will redirect to a URL. All of this should be configured in the JS. The overlay window will be simple so I don't need anything complex like jQuery. Just some nice clean OOP JS handmade will be fine.
Yet another approach: *Usage:* ``` var timer = reloadTimer({ seconds:5, logoutURL: '/logout', message:'Do you want to stay logged in?'}); timer.start(); ``` *Implementation:* ``` var reloadTimer = function (options) { var seconds = options.seconds || 0, logoutURL = options.logoutURL, message = options.message; this.start = function () { setTimeout(function (){ if ( confirm(message) ) { window.location.reload(true); } else { window.location.href = logoutURL; } }, seconds * 1000); } return this; }; ```
I'm assuming that this has something to do with refreshing a session to preserve a login. If that is the case then you should keep in mind that the user may not respond to your dialog for some time after it pops up. Meaning, your popup may come up after 10 minutes and your session may last for 15 minutes, but if it takes longer than 5 minutes for the user to respond then the session will expire and the refresh of the page will not help you. ``` <body onload="setTimeout(refreshLogin, 600000)"> <script> function refreshLogin() { if (confirm("Press OK to refresh this page and renew your login.")) { window.location.reload(); // refresh the page } else { window.location.href="http://example.com" //redirect to somewhere } } </script> </body> ```
JavaScript timeout script
[ "", "javascript", "" ]
I am curious about both, a h single and multi-threaded implementation. Thanks
Your question is vague, but it sounds like you want the [Curiously recurring template pattern](http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern) There are a lot better people than I to explain this on the web it is used a lot in the boost library. check out [boost.iterator](http://www.boost.org/doc/libs/1_39_0/libs/iterator/doc/index.html) documentation and code for a good example
[Here you go](http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface)... Google, isn't it amazing? :P
How is Non-Virtual Interface pattern imlemented in C++?
[ "", "c++", "design-patterns", "" ]
I am trying to read some settings from php.ini using zend. The API that I am using is ``` long zend_ini_long(char *name, uint name_length, int orig) ``` But it always returns 0. I have double checked the name and also made sure that the value I am specifying in php.ini is greater then 0. Is there anything I am missing?
``` long maxwait = zend_ini_long("max_execution_time", sizeof("max_execution_time"), 0); ``` The problem is that ZEND\_STRL is not returning the right length for the way that this API is intended to be used, so don't use it. I should add that most of the hash tables maintained internally by PHP assume that the NUL terminator character is included in the length of the string being hashed (its part of the overall binary safety concept), which is why we use sizeof() rather than strlen() or sizeof()-1.
You can use the standard php function: ini\_get('var-name'); Example: ``` ini_get('include_path'); ```
Reading php.ini using zend for PHP extension (not PHP language)
[ "", "c", "windows", "php", "php-extension", "php-internals", "" ]
I've been getting stuck into some linq queries for the first time today and I'm struggling with some of the more complicated ones. I'm building a query to extract data from a table to build a graph. The tables colums I'm interested in are **Id**, **Time** and **Value**. The user will select a start time, an end time and the number of intervals (points) to graph. The value column will averaged for each interval. I can do this with a linq request for each interval but I'm trying to write it in one query so I only need to go to the database once. So far I have got: ``` var timeSpan = endTime.Subtract(startTime); var intervalInSeconds = timeSpan.TotalSeconds / intervals; var wattList = (from t in _table where t.Id == id && t.Time >= startTime && t.Time <= endTime group t by intervalInSeconds // This is the bit I'm struggling with into g orderby g.Key select g.Average(a => a.Value)) ).ToList(); ``` Any help on grouping over time ranges will be most welcome.
I've done this myself for exactly the same situation you describe. For speed, modified the database's datapoints table to include an integer-based time column, `SecondsSince2000`, and then worked with that value in my LINQ to SQL query. `SecondsSince2000` is a computed column defined as: ``` datediff(second, dateadd(month,1200,0), DataPointTimeColumn) PERSISTED ``` Where `DataPointTimeColumn` is the name of the column that stores the datapoint's time. The magic function call `dateadd(month,1200,0)` returns 2000-01-01 at midnight, so the column stores the number of seconds since that time. The LINQ to SQL query is then made much simpler, and faster: ``` int timeSlotInSeconds = 60; var wattList = (from t in _table where t.Id == id && t.Time >= startTime && t.Time <= endTime group t by t.SecondsSince2000 - (t.SecondsSince2000 % timeSlotInSeconds) into g orderby g.Key select g.Average(a => a.Value))).ToList(); ``` If you can't modify your database, you can still do this: ``` var baseTime = new DateTime(2000, 1, 1); var wattList = (from t in _table where t.Id == id && t.Time >= startTime && t.Time <= endTime let secondsSince2000 = (int)(t.Time- baseTime).TotalSeconds group t by secondsSince2000 - (secondsSince2000 % timeSlotInSeconds) into g orderby g.Key select g.Average(a => a.Value))).ToList(); ``` The query will be quite a bit slower.
Check out this example I wrote a while ago. It sounds like what you are trying to do, but I'm not sure if it does the grouping in SQL or by .NET. <http://mikeinmadison.wordpress.com/2008/03/12/datetimeround/>
Grouping by Time ranges in Linq
[ "", "c#", ".net", "linq", "" ]
I would like to ask which kind of credentials do I need to put on for importing data using the Google App Engine BulkLoader class ``` appcfg.py upload_data --config_file=models.py --filename=listcountries.csv --kind=CMSCountry --url=http://localhost:8178/remote_api vit/ ``` And then it asks me for credentials: > Please enter login credentials for > localhost Here is an extraction of the content of the models.py, I use this [listcountries.csv](http://www.andrewpatton.com/countrylist.html) file ``` class CMSCountry(db.Model): sortorder = db.StringProperty() name = db.StringProperty(required=True) formalname = db.StringProperty() type = db.StringProperty() subtype = db.StringProperty() sovereignt = db.StringProperty() capital = db.StringProperty() currencycode = db.StringProperty() currencyname = db.StringProperty() telephonecode = db.StringProperty() lettercode = db.StringProperty() lettercode2 = db.StringProperty() number = db.StringProperty() countrycode = db.StringProperty() class CMSCountryLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'CMSCountry', [('sortorder', str), ('name', str), ('formalname', str), ('type', str), ('subtype', str), ('sovereignt', str), ('capital', str), ('currencycode', str), ('currencyname', str), ('telephonecode', str), ('lettercode', str), ('lettercode2', str), ('number', str), ('countrycode', str) ]) loaders = [CMSCountryLoader] ``` Every tries to enter the email and password result in "Authentication Failed", so I could not import the data to the development server. I don't think that I have any problem with my files neither my models because I have successfully uploaded the data to the appspot.com application. So what should I put in for localhost credentials? I also tried to use **Eclipse with Pydev** but I still got the same message :( Here is the output: ``` Uploading data records. [INFO ] Logging to bulkloader-log-20090820.121659 [INFO ] Opening database: bulkloader-progress-20090820.121659.sql3 [INFO ] [Thread-1] WorkerThread: started [INFO ] [Thread-2] WorkerThread: started [INFO ] [Thread-3] WorkerThread: started [INFO ] [Thread-4] WorkerThread: started [INFO ] [Thread-5] WorkerThread: started [INFO ] [Thread-6] WorkerThread: started [INFO ] [Thread-7] WorkerThread: started [INFO ] [Thread-8] WorkerThread: started [INFO ] [Thread-9] WorkerThread: started [INFO ] [Thread-10] WorkerThread: started Password for foobar@nowhere.com: [DEBUG ] Configuring remote_api. url_path = /remote_api, servername = localhost:8178 [DEBUG ] Bulkloader using app_id: abc [INFO ] Connecting to /remote_api [ERROR ] Exception during authentication Traceback (most recent call last): File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\bulkloader.py", line 2802, in Run request_manager.Authenticate() File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\bulkloader.py", line 1126, in Authenticate remote_api_stub.MaybeInvokeAuthentication() File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\remote_api\remote_api_stub.py", line 488, in MaybeInvokeAuthentication datastore_stub._server.Send(datastore_stub._path, payload=None) File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\appengine_rpc.py", line 344, in Send f = self.opener.open(req) File "C:\Python25\lib\urllib2.py", line 381, in open response = self._open(req, data) File "C:\Python25\lib\urllib2.py", line 399, in _open '_open', req) File "C:\Python25\lib\urllib2.py", line 360, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 1107, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python25\lib\urllib2.py", line 1082, in do_open raise URLError(err) URLError: <urlopen error (10061, 'Connection refused')> [INFO ] Authentication Failed ``` Thank you!
I recommend you follow the advice given [here](http://blog.suinova.com/2009/03/tutorial-on-bulkloading-data-onto-app.html), and I quote: > add this to app.yaml file: > > ``` > -- url: /loadusers > script: myloader.py > login: admin > ``` > > Note that if you run it **on local > development machine, comment off the > last line login:admin so that you > don't need a credential to run the > bulkloader**. (my emphasis).
**EUREKA:** I found the way to use the `bulkloader.py` tool without having to manually enter login credentials. Here are the 2 steps: --- Set your `app.yaml` file up. Example: ``` - url: /remote_api script: $PYTHON_LIB/google/appengine/ext/remote_api/handler.py login: admin ``` You should put it BEFORE your `- url: .*` line in `app.yaml`, otherwise you will never access the `/remote_api` url. Note that I've left the `login: admin` part, as removing it is a VERY BAD practice, since you might deploy that into production... --- 2 Launch this command (adapt it to your needs). ``` echo 'XX' | python2.5 ../google_appengine/bulkloader.py --dump --kind=NAMEOFMODEL --url=http://localhost:8080/remote_api --filename=FILENAME --app_id=APPID --email=foobar@nowhere.com --passin . ``` The trick is to use the combination of those 2 parameters: * `--email=` (you can put whichever email address you want, I use `foobar@nowhere.com`) * `--passin` Specifying `--email=` will suppress the "enter credentials" prompt, and `--passin` will allow to read the password from `stdin` (that's where the `echo 'XX' |` comes into play!) --- Enjoy! P.S.: Don't forget to vote so that Google can provide an easier to use way to do that: [Issue 2440](http://code.google.com/p/googleappengine/issues/detail?id=2440).
Which credentials should I put in for Google App Engine BulkLoader at development server?
[ "", "python", "google-app-engine", "" ]
I am trying to use boost string algorithms for case insensitive search. total newbie here. if I am using it this way, I get an error. ``` std::string str1("Hello world"); std::string str2("hello"); if ( boost::ifind_first(str1, str2) ) some code; ``` Converting to char pointers resolves the problem. ``` boost::ifind_first( (char*)str1.c_str(), (char*)str2.c_str() ); ``` Is there a way to search std::string objects directly? Also, maybe there is another way to know if string is present inside another string with case-insensitive search?
You need to use boost::iterator\_range. This works: ``` typedef const boost::iterator_range<std::string::const_iterator> StringRange; std::string str1("Hello world"); std::string str2("hello"); if ( boost::ifind_first( StringRange(str1.begin(), str1.end()), StringRange(str2.begin(), str2.end()) ) ) std::cout << "Found!" << std::endl; ``` EDIT: Using a const iterator\_range in the typedef allows passing a temporary range.
The more simplicity way ``` std::string str1("Hello world"); std::string str2("hello"); if (boost::icontains(str1, str2)) { ... } ```
boost::ifind_first with std::string objects
[ "", "c++", "algorithm", "string", "boost", "" ]
I'd like to know if this kind of stored procedure is possible, do i need some sort of looping structure or something? I want to do this, basically in this order: 1. get all rows from one table or view. (table1) 2. based on columns from table 1, i want to set variables for use in insert/update table2. 3. i want to reference another table, (table3), to find a key from table1, that will "Override", any cases that the row data might fall into. 4. Insert or Update the table2. If this is possible, could i PLEASE get some sort of draft in the answer? Thank you for reading! plz try to help! Here's another sort-of "diagram" of what I'm thinking: 1. select \* from table1 2. case [table1].[table1column] - [table1].[table1column] <=0, parameter1= "a" (many cases) 3. case [table1].[tableID] Exists in table3, parameter1 = [table3].[parameter] 4. case [table1].[tableID] Exists in table2, update, else insert Thanks for all the attempts so far!!If i figure this out I'm gonna post it.
I'm going to jump the gun and assume that you're talking about MS SQL Server. Yes, that kind of thing is possible. Here's a bit of psuedo code to get you started: ``` declare @someTable ( idx int identity(1,1), column1 type, column2 type, etc type ) declare @counter set @counter = 1 insert into @someTable (column1, column2, etc) select column1, column2, etc from table1 while @counter < (select max(idx) from @someTable) begin -- loop through records and perform logic insert result into table3 set @counter = @counter + 1 end ``` **If at all possible though...try to use a single query. Join your tables and use Case statements to perform the logic.**
We need more information, but I'll give you 98% or better odds that this can all be done in two queries (one for the insert, one for the updates). Here's a generic example for the insert: ``` INSERT INTO [Table2] SELECT t1.[col1], /* use columns from table1 to update table2 */ COALESCE(t3.[col2], t1.[col2]) /* table3 "overrides" table1 */ FROM [Table1] t1 -- get all rows from table1 LEFT JOIN [Table3] t3 ON t3.ID = t1.Table3ID LEFT JOIN [Table2] t2 ON t2.ID = t1.Table2ID WHERE t2.OtherColumn IS NULL /* insert - only make changes where the record doesn't already exist */ ``` and the update: ``` UPDATE t2 SET t2.[col1] = t1.[col1], t2.[col2] = COALESCE(t3.[col2], t1.[col2]) FROM [table1] t1 LEFT JOIN [Table3] t3 ON t3.ID = t1.Table3ID INNER JOIN [Table2] t2 ON t2.ID = t1.Table2ID /* update - only make changes where the record does already exist */ ```
Stored procedure that Selects, Conditions, sets variables, then inserts/updates into a table
[ "", "sql", "stored-procedures", "insert-update", "" ]
I want to post parameters to a URL using the POST method but I cannot use a form. Even if I do use a form, it would have to be auto-posted with out user interaction. Is this possible? How can I do this?
You could use JavaScript and XMLHTTPRequest (AJAX) to perform a POST without using a form. Check [this link](http://www.openjs.com/articles/ajax_xmlhttp_using_post.php) out. Keep in mind that you will need JavaScript enabled in your browser though.
Using [jQuery.post](http://docs.jquery.com/Ajax/jQuery.post) ``` $.post( "http://theurl.com", { key1: "value1", key2: "value2" }, function(data) { alert("Response: " + data); } ); ```
Posting parameters to a url using the POST method without using a form
[ "", "javascript", "forms", "post", "" ]
``` >>> import psycopg2 Traceback (most recent call last): File "", line 1, in File "C:\Python26\lib\site-packages\psycopg2\__init__.py", line 60, in from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID ImportError: DLL load failed: The application has failed to start because its si de-by-side configuration is incorrect. Please see the application event log for more detail. ``` I get this error when trying to import [psycopg2](http://stickpeople.com/projects/python/win-psycopg).. I've searched for days, and found no solutions. I've tried installing the Visual C++ 2008 Package, but I still get the same error.
According to this [thread](http://groups.google.com/group/django-users/browse_thread/thread/e1b628f0f75896f0) you need to install an earlier version since there were problems with the latest build. > Simply install an earlier version, (2.0.10 works great), even with > PostgreSQL 8.4.x series.
On Windows, make sure your path includes the Postgres bin directory. In my machine it's c:\Programs\PostgreSQL\9.3\bin.
ImportError: DLL load failed : - when trying to import psycopg2 library
[ "", "python", "django", "postgresql", "psycopg2", "" ]
I need to make files and folders hidden on both Windows and Linux. I know that appending a '.' to the front of a file or folder will make it hidden on Linux. How do I make a file or folder hidden on Windows?
For Java 6 and below, You will need to use a native call, here is one way for windows ``` Runtime.getRuntime().exec("attrib +H myHiddenFile.java"); ``` You should learn a bit about win32-api or Java Native.
The functionality that you desire is a feature of NIO.2 in the upcoming Java 7. Here's an article describing how will it be used for what you need: [Managing Metadata (File and File Store Attributes)](http://java.sun.com/docs/books/tutorial/essential/io/fileAttr.html). There's an example with [DOS File Attributes](http://java.sun.com/docs/books/tutorial/essential/io/fileAttr.html#dos): ``` Path file = ...; try { DosFileAttributes attr = Attributes.readDosFileAttributes(file); System.out.println("isReadOnly is " + attr.isReadOnly()); System.out.println("isHidden is " + attr.isHidden()); System.out.println("isArchive is " + attr.isArchive()); System.out.println("isSystem is " + attr.isSystem()); } catch (IOException x) { System.err.println("DOS file attributes not supported:" + x); } ``` Setting attributes can be done using [DosFileAttributeView](http://openjdk.java.net/projects/nio/javadoc/java/nio/file/attribute/DosFileAttributeView.html) Considering these facts, I doubt that there's a standard and elegant way to accomplish that in Java 6 or Java 5.
Make a File/Folder Hidden on Windows with Java
[ "", "java", "file", "directory", "hidden", "" ]
(I'm pretty new to WPF, so this question may seem obvious or inconsistent.) There is a requirement to edit some piece of application's underlying business data from a child modal window, and to update the data only if the user presses OK button in this window. Let's call this window SettingsDialog. In this case, is it still reasonable to use WPF data binding to bind SettingsDialog's controls to business data? (And if so, how to update business data only when the user presses SettingsDialog's OK button?) Or is it better to manually assign SettingsDialog's controls' values from business data while SettingsDialog is showing, and then assign them back only if user presses OK button? What are arguments of correct choice (smaller or clearer code, performance, extensibility)? Is there some acknowledged design pattern for similar cases? **EDIT:** I marked Bubblewrap's answer as accepted, because it fits my own concrete case the most. Though, Guard's and John's answers also seem acceptable. To summarize: using data binding has some advantages. It allows SettingsDialog to know nothing about business object internal connections and dependencies (if there are any), allows to switch later from modal to non-modal mode easily, reduces dependencies between GUI and business data. To implement changing of object upon OK button click, object cloning/assigning may be used, or object may implement IEditableObject interface. In some trivial cases, though, using data binding may have some unnecessary overhead.
I have encountered similar requirements before, and prefer two variants, both using databinding. In the first variant we clone the object and bind to the clone. When the user presses OK, the cloned object replaces to real object. This is mostly useful when editing one object at a time, and the object is not referenced directly by other objects. If it is referenced, then instead you could copy the values from your clone to your original, so that references remain intact. This saves work because no extra work is required in the editors, at most you must define 2 methods on your object, a Clone and possible an Apply method to copy the values from the clone. The second variant we bind to the original object, but we store the original values in our editing dialog, either in local fields or in a temporary data-object. When the user presses OK, nothing special has to happen, but when the user presses cancel we revert the values. This is mostly useful when you edit only a few simple properties in the dialog. I prefer databinding solutions because it doesnt pollute the editing dialogs with apply/cancel logic, which if implemented in the editors is very dependent on your XAML: controls can be renamed, a combobox can be replaced by a textbox etc, all of which would affect code which manually assings data from controls. The Clone/Apply methods only need to be on your business objects, which in theory are more stable than your UI editors. Even if the XAML changes, in most cases your bindings can remain the same. For example a change from combobox to textbox only means you bind to Text instead of SelectedValue, but the actual binding is the same.
One option is to have your business object implement [IEditableObject](http://msdn.microsoft.com/en-us/library/system.componentmodel.ieditableobject.aspx). * Before showing the window, call [BeginEdit](http://msdn.microsoft.com/en-us/library/system.componentmodel.ieditableobject.beginedit.aspx) on your object * If the user clicks OK, call [EndEdit](http://msdn.microsoft.com/en-us/library/system.componentmodel.ieditableobject.endedit.aspx) * If the user clicks Cancel, call [CancelEdit](http://msdn.microsoft.com/en-us/library/system.componentmodel.ieditableobject.canceledit.aspx) IEditableObject is typically used in data grid scenarios, but it works well for the case you described too. Plus, if your UI ever changes to allow inline editing in a DataGrid, you won't have to change your business object.
WPF: is data binding considerable for modal dialogs?
[ "", "c#", "wpf", "data-binding", "modal-dialog", "" ]
I saw someone using this in one answer: ``` void methodA(const int*& var); ``` I couldn't understand what the argument means. AFAIK: * `const int var` => `const int` value which can't be changed * `const int* var` => pointer to `const int`, ie `*var` can't be changed but `var` can be changed * `const int& var` => reference to `const int`, ie value of `var` can't be changed What does `const int*& var` mean? Is `const int& *var` also possible? Can you please give some example as well, like what can and can't be done with it? **UPDATE**: I am not sure if I am thinking the right way, but I began to think of a reference as an alias of the variable that was passed as argument, so: `const int * p;` `methodA(p)` => here we are passing `p` as `const int *` but we don't know if this is pass by value or what, until we see the definition of `methodA`, so if `methodA` is like this: `methodA(const int * & p2)` ==> here `p2` is another name to `p`, ie `p` and `p2` are the same from now on `methodA(const int* p2)` ==> here `p2` is passed as value, ie `p2` is just local to this method Please correct me if I am thinking the wrong way. If yes, I might need to study some more about this. Can you please point to some nice references? **UPDATE 2**: If some beginner like me wants to know more about this thing, you can use the **c++decl** / **cdecl** program from [here](https://stackoverflow.com/questions/859634/c-pointer-to-array-array-of-pointers-disambiguation/859676#859676), which I just discovered to be very useful. ``` $ c++decl Type `help' or `?' for help c++decl> explain const int&* p declare p as pointer to reference to const int c++decl> explain const int*& p declare p as reference to pointer to const int ``` But, as every one here pointed out, the first example isn't legal in C++.
It is a reference to a pointer to an int that is const. There is another post somewhat related, actually, [here](https://stackoverflow.com/questions/859634/c-pointer-to-array-array-of-pointers-disambiguation/859676#859676). My answer gives a sorta of general algorithm to figuring these things out. This: `const int& *var` has no meaning, because you cannot have a pointer to reference. If the const's and pointers are getting in the way, remember you can typedef these things: ``` typedef int* IntPointer; typedef const IntPointer ConstIntPointer; void foo(ConstIntPointer&); // pass by reference void bar(const ConstIntPointer&); // pass by const reference void baz(ConstIntPointer); // pass by value ``` Might make it easier to read. --- If you need more help on C++, [read this](https://isocpp.org/faq/). More specifically, [references](https://isocpp.org/wiki/faq/references). References as variables do *not* take space: ``` int i; // takes sizeof(int) int*pi = &i; // takes sizeof(int*) int& ri = i; // takes no space. // any operations done to ri // are simply done to i ``` References as parameters use pointers to achieve the end effect: ``` void foo(int& i) { i = 12; } void foo_transformed(int *i) { *i = 12; } int main() { int i; foo(i); // same as: foo_transformed(&i); // to the compiler (only sort of) } ``` So it's actually passing the address of `i` on the stack, so takes `sizeof(int*)` space on the stack. But don't start thinking about references as pointers. They are *not* the same.
Some folks find it easier reading this from right to left. So > const int\*& is a reference to a pointer to an integer that is const. As you know, references cannot be changed, only what they refer to can be changed. So the reference will refer to just one pointer to an integer that is const. Since the pointer is not const - the integer is const - you can change the pointer to point to a different integer. Compare this to > int\* const & This is a reference to a constant pointer to an integer. Again the reference is immutable, and in this case it is a reference to a constant pointer. What you can change in this case is the integer value since there was no const either side of the int keyword. Just to add confusion, const int and int const are the same. However int const \* and int \* const are very different. The first is a pointer to a constant integer, so the pointer is mutable. The second is a constant pointer to an integer, so the integer is mutable. Hope this helps!
What does this mean const int*& var?
[ "", "c++", "" ]
I'm using ASP.NET MVC 1.0 along with the Oracle ASP.NET Membership Providers. I'm running into a case sensitivity problem. When a user logs into the system, it appears that the Membership provider sets the `User.Identity.Name` value to whatever the user typed in. That is, if I created the user as `Foo` and the user logs in as `fOo` then everywhere where I use `User.Identity.Name` on my site, it'll show `fOo`. Is there an easy way to work around this? I tried ``` var user = Membership.GetUser(User.Identity.Name).UserName; ``` but that gives me the exact same `fOo` value.
As a followup to cdmckay, if you'd want to have the User.Identity.Name correct as well, use ``` IIdentity newIdentity = new GenericIdentity(properlyCasedUser.UserName); if (User is RolePrincipal) User = new RolePrincipal(((RolePrincipal)User).ProviderName, newIdentity, ((RolePrincipal)User).ToEncryptedTicket()); else User = new GenericPrincipal(newIdentity, null); ```
Here's a solution I found but I feel like it should be more direct than this: ``` MembershipUser user = _provider.GetUser(userName, false); MembershipUser properlyCasedUser = _provider.GetUser(user.ProviderUserKey, false); ```
User.Identity.Name casing issue
[ "", "c#", ".net", "asp.net-mvc", "oracle", "asp.net-membership", "" ]
Is there any way to encrypt or secure log4net output?
I'm assuming you want to encrypt the log's output. In that case you will need to write your own Appender which can handle the encryption. I would suggest figuring out what output mechanism you intend to use without encryption (i.e. FileAppender, EventLogAppender, etc.), and then extend that Appender and override the functionality that actually writes out the output. The reference documentation on the appenders can be found [here](http://logging.apache.org/log4net/release/sdk/index.html). For instance, extend the FileAppender with an EncryptedFileAppender and override/implement the members you need to in order to hook into the file writing. Alternatively, you could extend from IAppender and create an appender completely from scratch. That would give you more control, but might require more work if all you're trying to do is encrypt your payload.
There's no out-of-the-box support for encryption. So as others have stated here, you will have to implement that yourself. That said, I would suggest subclassing a [ForwardingAppender](https://logging.apache.org/log4net/release/sdk/html/T_log4net_Appender_ForwardingAppender.htm) to do the encryption. This will basically let you put your appender "in front of" whatever standard appender you would choose to do the actual writing to disk.
How to encrypt log4net log files
[ "", "c#", "log4net", "" ]
I'm having some trouble with certain input areas of my program. There are a few parts where the user inputs a specific integer. Even if they enter the wrong one that's all fine and dandy, but I noticed if they enter anything not of integer type like 'm' then it will loop the error message repeatedly. I have a couple functions that have integer input in them. Here's one for an example. ``` void Room::move(vector<Room>& v, int exone, int extwo, int exthree, int current) { v[current].is_occupied = false; int room_choice; cout << "\nEnter room to move to: "; while(true) { cin >> room_choice; if(room_choice == exone || room_choice == extwo || room_choice == exthree) { v[room_choice].is_occupied = true; break; } else cout << "Incorrect entry. Try again: "; } } ```
You can use `cin.good()` or `cin.fail()` to determine whether cin could successfully deal with the input value provided. You can then use `cin.clear()`, if necessary, to clear the error state before continuing processing.
There is still a problem in your "solved" code. You should check for fail() before checking the values. (And obviously, there is the problem of eof() and IO failure as opposed to format problems). Idiomatic reading is ``` if (cin >> choice) { // read succeeded } else if (cin.bad()) { // IO error } else if (cin.eof()) { // EOF reached (perhaps combined with a format problem) } else { // format problem } ```
User Input of Integers - Error Handling
[ "", "c++", "error-handling", "" ]
why is 24 \* 60 \* 60 \* 1000 \* 1000 divided by 24 \* 60 \* 60 \* 1000 not equal to 1000 in Java?
Because the multiplication overflows 32 bit integers. In 64 bits it's okay: ``` public class Test { public static void main(String[] args) { int intProduct = 24 * 60 * 60 * 1000 * 1000; long longProduct = 24L * 60 * 60 * 1000 * 1000; System.out.println(intProduct); // Prints 500654080 System.out.println(longProduct); // Prints 86400000000 } } ``` Obviously after the multiplication has overflowed, the division isn't going to "undo" that overflow.
You need to start with 24L \* 60 \* ... because the int overflows. Your question BTW is a copy/paste of **Puzzle 3: Long Division** from [Java Puzzlers](http://www.javapuzzlers.com/contents.html) ;)
why is 24 * 60 * 60 * 1000 * 1000 divided by 24 * 60 * 60 * 1000 not equal to 1000 in Java?
[ "", "java", "puzzle", "math", "" ]
I would like to write a java script which: 1. When the page loads takes the content of a `<div>` tag and 2. Places that content on a popup page. any ideas for the script? I know how to navigate to the element but have no idea how to copy the content. The content of the div will be something like this ``` <div id="validationDiv"> <div id="ctl00_Main_OTClaim1_valControls" class="errorpanel" style="color:Red;"> <ul><li>Approver Name - required field.</li><li>Week Commencing Date - required field.</li><li>Summary of Hours Worked must be completed.</li><li>At least one item must be claimed to proceed.</li></ul> </div> </div> ``` where valadation div contains what i want to copy to the new window cheers
``` window.onload = function() { var el = document.getElementById("ctl00_Main_OTClaim1_valControls"); var html = ""; if (el) { html = document.getElementById("ctl00_Main_OTClaim1_valControls").innerHTML; var xopen = window.open("about:blank"); xopen.document.write(html); } } ``` --UPDATE ``` window.onload = function() { var el = document.getElementById("ctl00_Main_OTClaim1_valControls"); //the element you want expanded var html = ""; if (el) { html = el.innerHTML; var xopen = window.open("about:blank"); xopen.document.write(html); } } ```
Like: ``` var copy = document.getElementById("validationDiv").innerHTML; ``` Then to create the new window: ``` var newWin = window.open("", "My window", "width=250,height=250,scrollbars=1,resizable=1") newWin.document.write("<html><head></head><body>" + copy + "</body></html>") ```
JavaScript - window.onload - put content of a <div></div> onto a new window
[ "", "javascript", "html", "" ]
let's say I'm working on a site that has 8 to 10 different html/php templates I want to use several common elements on every page, like most people do, masthead, footer, sidebar, the usual but these common elements often need minor adjustments for each template, like one template has sub navigation in the sidebar and one does not I'm wondering what approach is best option 1 should I have a separate include or require for each different common element, like one for the html head one for footer, one for the sidebar, etc option 2 should I require just one larger file that holds all my common elements, and then I can use $\_SERVER['SCRIPT\_NAME'] and conditionals to test which template is being called and make modifications to the common elements as needed Does it really make any difference as far as performance goes or load on the server? how many conditionals is too many? how many includes is too many? am I making sense folks? :-)
Your priority should be maintainability, not performance. And for that reason, it's definitely preferable to have multiple templates that are included as required. Ideally, adjustments should be expressed through parameters/flags i.e. have the main script set `$showSubnavigation=true` and the navigation template tests for that rather than for the name of the main script. Better yet, implement the navigation template as a function that you can call with parameters.
Would it matter? If the template is not needed it wouldn't be included right? As far as I know having more files on a server, as long as they are not in use, doesn't effect server load.
should I include a bunch of files of have one big file with conditionals?
[ "", "php", "" ]
HI I have a forum and I'm trying to think of how to do an "attachment" feature. You know if you make a thread you can chose to upload a file and attach it in the thread. Should I make a table called attachment with id of the file id in table files?? Whats the best way. And I want you to be able to upload more than 1 attachment. and if it's a picture show a little miniature of the picture. How should I check if the file exist etc? How would you do this? Sorry for my poor english
I honestly would create a Column on the table of posts that says 'Attachments', and then do a comma delimited string of attachment file names `file1.png,file2.png,file3.png` then when you get it into PHP, simply explode it `$attachments = explode(',', $string);` and check for each file that you have already put in your upload directory: ``` foreach($attachments as $file) { if(!is_file($upload_directory.$file)) { $error[] = $file . " is not a valid attachment"; // run cleanup script } } ``` To get the attachments, it is really simple code, but you need to validate and sanitize the incoming file. ``` foreach($_FILES as $array) { // Sanitize Here die("SANITIZE HERE!"); move_uploaded_file($array['tmp_name'], $upload_dir); } ```
You question is too broad but I'll give you some pointers: * store the images on the disk, something like /uploads/--thread\_id--/1.jpg, /uploads/--thread\_id--/2.jpg and so on (this way you don't have to make any changes to your DB) Regarding the upload process, validation and image resizing you can read more at (I recommend you read them in this order): ``` http://pt.php.net/manual/en/function.exif-imagetype.php -> image validation http://php.net/manual/en/function.move-uploaded-file.php -> upload process http://pt.php.net/manual/en/book.image.php -> image resizing & manipulation ```
PHP question Forum Attachment Feature Help
[ "", "php", "" ]
I am trying to merge 1000 PDF Files thru iText. I am not sure where the memory leakage is happening. Below is the sample code. Note that i am removing the child-pdf file as soon as i merge to the parent file. Please pointout bug in below code or is there any better way to do this with out memory conception. This process is done thru servlet (not standalone program) ``` FileInputStream local_fis = null; BufferedInputStream local_bis = null; File localFileObj = null; for(int taIdx=0;taIdx<totalSize;taIdx++){ frObj = (Form3AReportObject)reportRows.get(taIdx); localfilename = companyId + "_" + frObj.empNumber + ".pdf"; local_fis = new FileInputStream(localfilename); local_bis = new BufferedInputStream(local_fis); pdfReader = new PdfReader(local_bis); cb = pdfWriter.getDirectContent(); document.newPage(); page = pdfWriter.getImportedPage(pdfReader, 1); cb.addTemplate(page, 0, 0); local_bis.close(); local_fis.close(); localFileObj = new File(localfilename); localFileObj.delete(); } document.close(); ```
You might want to try something like the following (exception handling, file close and delete removed for clarity): ``` for(int taIdx = 0; taIdx < totalSize; taIdx++) { Form3AReportObject frObj = (Form3AReportObject)reportRows.get(taIdx); localfilename = companyId + "_" + frObj.empNumber + ".pdf"; FileInputStream local_fis = new FileInputStream(localfilename); pdfWriter.freeReader(new PdfReader(local_fis)); pdfWriter.flush(); } pdfWriter.close(); ```
Who says there is a memory leak? Your merged document needs to fit into memory in its entirety, there's no way around it, and it may well be larger than the default heap size of 64MB *in memory* (rather than on disc). I don't see a problem with your code, but if you want to diagnose it in detail, [use visualvm's heap profiler](http://rejeev.blogspot.com/2009/04/analyzing-memory-leak-in-java.html) (comes with the JDK since Java 6 update 10 or so).
Merging 1000 PDF thru iText throws java.lang.OutOfMemoryError: Java heap space
[ "", "java", "itext", "out-of-memory", "" ]
I've had this troubling experience with a Tomcat server, which runs: * our [Hudson](http://java.net/projects/hudson/) server; * a staging version of our web application, redeployed 5-8 times per day. The problem is that we end up with continuous garbage collection, but the old generation is nowhere near to being filled. I've noticed that the survivor spaces are next to inexisting, and the garbage collector output is similar to: ``` [GC 103688K->103688K(3140544K), 0.0226020 secs] [Full GC 103688K->103677K(3140544K), 1.7742510 secs] [GC 103677K->103677K(3140544K), 0.0228900 secs] [Full GC 103677K->103677K(3140544K), 1.7771920 secs] [GC 103677K->103677K(3143040K), 0.0216210 secs] [Full GC 103677K->103677K(3143040K), 1.7717220 secs] [GC 103679K->103677K(3143040K), 0.0219180 secs] [Full GC 103677K->103677K(3143040K), 1.7685010 secs] [GC 103677K->103677K(3145408K), 0.0189870 secs] [Full GC 103677K->103676K(3145408K), 1.7735280 secs] ``` The heap information before restarting Tomcat is: ``` Attaching to process ID 10171, please wait... Debugger attached successfully. Server compiler detected. JVM version is 14.1-b02 using thread-local object allocation. Parallel GC with 8 thread(s) Heap Configuration: MinHeapFreeRatio = 40 MaxHeapFreeRatio = 70 MaxHeapSize = 3221225472 (3072.0MB) NewSize = 2686976 (2.5625MB) MaxNewSize = 17592186044415 MB OldSize = 5439488 (5.1875MB) NewRatio = 2 SurvivorRatio = 8 PermSize = 21757952 (20.75MB) MaxPermSize = 268435456 (256.0MB) Heap Usage: PS Young Generation Eden Space: capacity = 1073479680 (1023.75MB) used = 0 (0.0MB) free = 1073479680 (1023.75MB) 0.0% used From Space: capacity = 131072 (0.125MB) used = 0 (0.0MB) free = 131072 (0.125MB) 0.0% used To Space: capacity = 131072 (0.125MB) used = 0 (0.0MB) free = 131072 (0.125MB) 0.0% used PS Old Generation capacity = 2147483648 (2048.0MB) used = 106164824 (101.24666595458984MB) free = 2041318824 (1946.7533340454102MB) 4.943684861063957% used PS Perm Generation capacity = 268435456 (256.0MB) used = 268435272 (255.99982452392578MB) free = 184 (1.7547607421875E-4MB) 99.99993145465851% used ``` The relevant JVM flags passed to Tomcat are: ``` -verbose:gc -Dsun.rmi.dgc.client.gcInterval=0x7FFFFFFFFFFFFFFE -Xmx3g -XX:MaxPermSize=256m ``` Please note that the survivor spaces are sized at about 40 MB at startup. How can I avoid this problem? --- **Updates:** The JVM version is ``` $ java -version java version "1.6.0_15" Java(TM) SE Runtime Environment (build 1.6.0_15-b03) Java HotSpot(TM) 64-Bit Server VM (build 14.1-b02, mixed mode) ``` I'm going to look into bumping up the `PermGen` size and seeing if that helps - probably the sizing of the survivor spaces was unrelated.
The key is probably `PS Perm Generation` which is at 99.999% (only 184 ***bytes*** out of 256\*\*\*MB\*\*\* free). Usually, I'd suggest that you give it more perm gen but you already gave it 256MB which should be plenty. My guess is that you have a memory leak in some code generation library. Perm Gen is mostly used for bytecode for classes.
It's very easy to have ClassLoader leaks - all it takes is a single object loaded through the ClassLoader being referred by an object not loaded by it. A constantly redeployed app will then quickly fill PermGenSpace. [This article](http://blogs.oracle.com/fkieviet/entry/classloader_leaks_the_dreaded_java) explains what to look out for, and [a followup](http://blogs.oracle.com/fkieviet/entry/how_to_fix_the_dreaded) describes how to diagnose and fix the problem.
Shrinking survivor spaces lead to continuous full GC
[ "", "java", "garbage-collection", "jvm", "" ]
Where is a good mathematical sets implementation for JavaScript? It should include efficient implementations of intersection, union, complement, and (for bonus points) the Cartesian product. No, it's not homework. I got a yubikey, it is a USB keyboard that types a sequence chosen from 16 keycodes to type a 128-bit one time password (otp). To make it more useful, software should detect the keyboard layout based on the characters produced and map those characters back to what they would be in the "us" layout for compatibility with the existing backend. So I've got 93 different sequences of 16 characters representing everything the yubikey can type in each of 430 keyboard layouts. (Many layouts are the same for this purpose.) The possible mappings for a particular otp is each 16-character sequence that contains every character in the otp. To find this efficiently I use a reverse index mapping each possible character to a list of the keyboard layouts that use that character. The answer is the intersection of each entry of the reverse index for each unique character in the otp. This almost always winds up with exactly 1 element. It would be easier to write this cross-browser with a good implementation of `Set()`. Code so far is at <http://dingoskidneys.com/~dholth/yubikey/>
I don't know of any existing implementations, but if your set elements are strings (or have a unique string representation) you can use JavaScript objects pretty easily. The elements would be the object properties, and the value could be anything. ``` // Make a set from an array of elements function makeSet(items) { var set = {}; for (var i = 0; i < items.length; i++) { set[items[i]] = true; } return set; } function copyInto(s, copy) { for (var item in s) { if (s[item] === true) { copy[item] = true; } } } function union(s1, s2) { var u = {}; copyInto(s1, u); copyInto(s2, u); return u; } function intersection(s1, s2) { var i = {}; for (var item in s1) { if (s1[item] === true && s2[item] === true) { i[item] = true; } } return i; } function difference(s1, s2) { var diff = {}; copyInto(s1, diff); for (var item in s2) { if (s2[item] === true) { delete diff[item]; } } return diff; } // etc. ``` You could also use `item in set` or `set.hasOwnProperty(item)` instead of `set[item] === true`, but checking by for `true` explicitly, you automatically ignore any functions that might be attached to the object (in case someone modified Object.prototype, or it's not a plain object).
By using [jPaq](http://jpaq.org/) or another JavaScript library that implements the Array.prototype.reduce and Array.prototype.forEach functions, you can create a cartesian product function that accepts two or more arrays. Here is code for a function that computes the cartesian product of two or more arrays: ``` function cartesianProductOf() { return Array.prototype.reduce.call(arguments, function(a, b) { var ret = []; a.forEach(function(a) { b.forEach(function(b) { ret.push(a.concat([b])); }); }); return ret; }, [[]]); } ``` As far as this being in a library, I am open to suggestions for the naming of the function so that I can add it into [jPaq](http://jpaq.org/). By the way, so as not to plagiarize, I did get the idea of using reduce from [this post](https://stackoverflow.com/questions/4796678/javascript-golf-cartesian-product/4797658#4797658).
What's a good mathematical sets implementation in JavaScript?
[ "", "javascript", "math", "set", "intersection", "" ]
I have a live web application that is failing in one specific scenario, and locally it works fine. I don't have remote debugging setup, and I want to check the value of some of the variables in the code. What would be the fastest way for me to log/email/debug the code to view those values? Just to be clear, there is no error/exception being thrown. Something is different, and its causing the application to give unexpected results. Thanks in advance!
The *fastest* way is to simply implement some logging in the Application\_Error event within your Global.asax file. If you do not have a Global.asax file, simply create one with the VS New File wizard and it'll handle that event for you. It won't help you get to local variables at the scope of the error, but you can log global variables from there and at least get some feedback on what the error is. EDIT: In response to your comment, I recommend you output your Trace data to a file that you can analyze. I haven't tried this myself, but I've seen it recommended. To your web.config, add something called a *TraceListener* like so: ``` <system.diagnostics> <trace autoflush="true"> <listeners> <add name="TestTracer" type="System.Diagnostics.TextWriterTraceListener, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" initializeData="<app root directory>\Asptesttrace.log" /> </listeners> </trace> </system.diagnostics> ``` You're going to need to play around with it locally, I'm sure. For instance, make sure the trace is not visible to the client (this may involve using the Trace class to turn the trace on or off, and changing the streams it writes to).
You can always turn on local only debugging and then remote on to the server and use the app. Might be the fastest way to see your problem.
What is the fastest way to inject some logging on a live web application?
[ "", "c#", "asp.net", "debugging", "logging", "remote-debugging", "" ]
I think I heard that ASP.NET applications will shut down after a while of being idle (i.e. no visitors). Is there a way to prevent this behavior from happening? I have a timer that runs some code from the global.asax.cs application\_start event, and want to make sure that it continues to run, even when no visitors are hitting the site. Thanks in advance!
You can do it a few ways. 1. If you have control over IIS, you can change the "Idle Timeout" within the application pool, by default it is 20 minutes. 2. If you do NOT have control over IIS (Shared or other hosting), you can use an external service to ping the site. [MyWebKeepAlive](http://www.mywebkeepalive.com) or [Pingdom](http://www.pingdom.com) are good options for this. If you are under option two, I strongly recommend an external source, as it is less to manage, and if you don't have IIS available to configure, you most likely don't have the server available to add a ping application to. In addition, I do not recommend something that sits in-process with the web application, as I have found that those can cause issues when the application really does need to recycle... **One last thought** If you do go the route of modifying the IIS Idle timeout, I do recommend setting a regular recycle of the application pool. As many web applications do benefit from a periodic recycle, and most commonly the idle timeout is the biggest regular recycle factor.
Besides external keep alive you can make an internal keep alive inside `global.asax`: ``` static Thread keepAliveThread = new Thread(KeepAlive); protected void Application_Start() { keepAliveThread.Start(); } protected void Application_End() { keepAliveThread.Abort(); } static void KeepAlive() { while (true) { WebRequest req = WebRequest.Create("http://www.mywebsite.com/DummyPage.aspx"); req.GetResponse(); try { Thread.Sleep(60000); } catch (ThreadAbortException) { break; } } } ```
Can you prevent your ASP.NET application from shutting down?
[ "", "c#", "asp.net", "iis", "" ]
What is the list of valid `@SuppressWarnings` warning names in Java? The bit that comes in between the `("")` in `@SuppressWarnings("")`.
It depends on your IDE or compiler. Here is a [list](http://www.breakitdownblog.com/supported-values-for-suppresswarnings/) for Eclipse Galileo: > * **all** to suppress all warnings > * **boxing** to suppress warnings relative to boxing/unboxing operations > * **cast** to suppress warnings relative to cast operations > * **dep-ann** to suppress warnings relative to deprecated annotation > * **deprecation** to suppress warnings relative to deprecation > * **fallthrough** to suppress warnings relative to missing breaks in switch > statements > * **finally** to suppress warnings relative to finally block that don’t > return > * **hiding** to suppress warnings relative to locals that hide variable > * **incomplete-switch** to suppress warnings relative to missing entries > in a switch statement (enum case) > * **nls** to suppress warnings relative to non-nls string literals > * **null** to suppress warnings relative to null analysis > * **restriction** to suppress warnings relative to usage of discouraged or > forbidden references > * **serial** to suppress warnings relative to missing serialVersionUID > field for a serializable class > * **static-access** to suppress warnings relative to incorrect static > access > * **synthetic-access** to suppress warnings relative to unoptimized > access from inner classes > * **unchecked** to suppress warnings relative to unchecked operations > * **unqualified-field-access** to suppress warnings relative to field > access unqualified > * **unused** to suppress warnings relative to unused code [List](http://help.eclipse.org/indigo/index.jsp?topic=/org.eclipse.jdt.doc.isv/guide/jdt_api_compile.htm) for Indigo adds: > * **javadoc** to suppress warnings relative to javadoc warnings > * **rawtypes** to suppress warnings relative to usage of raw types > * **static-method** to suppress warnings relative to methods that could be declared as static > * **super** to suppress warnings relative to overriding a method without super invocations [List](http://help.eclipse.org/juno/index.jsp?topic=/org.eclipse.jdt.doc.user/tasks/task-suppress_warnings.htm) for Juno adds: > * **resource** to suppress warnings relative to usage of resources of type Closeable > * **sync-override** to suppress warnings because of missing synchronize when overriding a synchronized method Kepler and Luna use the same token list as Juno ([list](http://help.eclipse.org/luna/index.jsp?topic=/org.eclipse.jdt.doc.user/tasks/task-suppress_warnings.htm)). Others will be similar but vary.
All values are permitted (unrecognized ones are ignored). The list of recognized ones is compiler specific. In [The Java Tutorials](https://docs.oracle.com/javase/tutorial/java/annotations/predefined.html) `unchecked` and `deprecation` are listed as the two warnings required by The Java Language Specification, therefore, they should be valid with all compilers: > Every compiler warning belongs to a category. The Java Language Specification lists two categories: deprecation and unchecked. The specific sections inside [The Java Language Specification](https://docs.oracle.com/javase/specs/) where they are defined is not consistent across versions. In the Java SE 8 Specification `unchecked` and `deprecation` are listed as compiler warnings in sections **9.6.4.5. @SuppressWarnings** and **9.6.4.6 @Deprecated**, respectively. For Sun's compiler, running `javac -X` gives a list of all values recognized by that version. For 1.5.0\_17, the list appears to be: * all * deprecation * unchecked * fallthrough * path * serial * finally
What is the list of valid @SuppressWarnings warning names in Java?
[ "", "java", "eclipse", "warnings", "compiler-warnings", "suppress-warnings", "" ]
Using: C#, VS2008 I have the following main form class: **[Main.cs]** ``` namespace Server { public partial class PipeServerform : System.Windows.Forms.Form { ... } } ``` But it's big, and long, and contains GUI + logic code. So I seperate the class into multiple files for easier management and create this file that only holds the logic details: **[DoCommands.cs]** ``` namespace Server { public partial class PipeServerform : System.Windows.Forms.Form { ... } } ``` This works... ***BUT!*** The '*DoCommands.cs*' file within the VS2008 project now has a default blank GUI 'form' window associated with it. It makes sense, as it's still part of the main form class, but I assumed the separation between different files would inform VS2008 that it is simply a logic file holder of simply commands, and doesn't contain any GUI form code. Is there an easy way to solve this view? Such that the '*DoCommands.cs*' file doesn't have the associated blank GUI form with it? Or do I have to literally split it into different classes? Thanks.
If order to get it to subordinate itself under PipeServerForm, open the project file in a text editor. You will find a block looking like this: ``` <Compile Include="DoCommands.cs"> <SubType>Form</SubType> </Compile> ``` Change it into this: ``` <Compile Include="DoCommands.cs"> <DependentUpon>Main.cs</DependentUpon> </Compile> ``` Now, when you load the project, `DoCommands.cs` should appear under `Main.cs`, just as `Main.Designer.cs`. I did note that VS seem to add the `SubType` element automatically, so that `DoCommands.cs` will still open in the Forms Designer by default. Perhaps there is a simple solution around for that as well.
I'm pretty sure you don't have to specify all inheritances for a partial class. So if you just drop System.Windows.Forms.Form from the inheritance list for the DoCommands.cs file you should be golden. **Edit**: Also, given the size of your main form, you might want to consider refactoring. Consider following a [MVC](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) or [MVP](http://en.wikipedia.org/wiki/Model-view-presenter) pattern. Separate your concerns into separate classes and possibly even modules.
C#: splitting a class into multiple files (with a form)
[ "", "c#", "file", "" ]
I've come across [`__stdcall`](http://msdn.microsoft.com/en-us/library/zxk0tw93%28VS.80%29.aspx) a lot these days. MSDN doesn't explain very clearly what it really means, when and why should it be used, if at all. I would appreciate if someone would provide an explanation, preferably with an example or two.
All functions in C/C++ have a particular calling convention. The point of a calling convention is to establish how data is passed between the caller and callee and who is responsible for operations such as cleaning out the call stack. The most popular calling conventions on windows are * `__stdcall`, Pushes parameters on the stack, in reverse order (right to left) * `__cdecl`, Pushes parameters on the stack, in reverse order (right to left) * `__clrcall`, Load parameters onto CLR expression stack in order (left to right). * `__fastcall`, Stored in registers, then pushed on stack * `__thiscall`, Pushed on stack; this pointer stored in ECX Adding this specifier to the function declaration essentially tells the compiler that you want this particular function to have this particular calling convention. The calling conventions are documented here * <https://learn.microsoft.com/en-us/cpp/cpp/calling-conventions> Raymond Chen also did a long series on the history of the various calling conventions (5 parts) starting here. * <https://devblogs.microsoft.com/oldnewthing/20040102-00/?p=41213>
This answer covers 32-bit mode. (Windows x64 only uses 2 conventions: the normal one (which is called `__fastcall` if it has a name at all) and `__vectorcall`, which is the same except for how SIMD vector args like `__m128i` are passed). --- Traditionally, C function calls are made with the caller pushing some parameters onto the stack, calling the function, and then popping the stack to clean up those pushed arguments. ``` /* example of __cdecl */ push arg1 push arg2 push arg3 call function add esp,12 ; effectively "pop; pop; pop" ``` Note: The default convention — shown above — is known as \_\_cdecl. The other most popular convention is \_\_stdcall. In it the parameters are again pushed by the caller, but the stack is cleaned up by the callee. It is the standard convention for Win32 API functions (as defined by the WINAPI macro in <windows.h>), and it's also sometimes called the "Pascal" calling convention. ``` /* example of __stdcall */ push arg1 push arg2 push arg3 call function // no stack cleanup - callee does this ``` This looks like a minor technical detail, but if there is a disagreement on how the stack is managed between the caller and the callee, the stack will be destroyed in a way that is unlikely to be recovered. Since \_\_stdcall does stack cleanup, the (very tiny) code to perform this task is found in only one place, rather than being duplicated in every caller as it is in \_\_cdecl. This makes the code very slightly smaller, though the size impact is only visible in large programs. (Optimizing compilers can sometimes leave space for args allocated across multiple cdecl calls made from the same function and `mov` args into it, instead of always `add esp, n` / `push`. That saves instructions but can increase code-size. For example `gcc -maccumulate-outgoing-args` always does this, and was good for performance on older CPUs before `push` was efficient.) Variadic functions like printf() are [impossible to get right with \_\_stdcall](https://stackoverflow.com/questions/65863892/stack-cleanup-in-stdcall-callee-pops-for-variable-arguments), because only the caller really knows how many arguments were passed in order to clean them up. The callee can make some good guesses (say, by looking at a format string), but it's legal in C to pass more args to printf than the format-string references (they'll be silently ignored). Hence only \_\_cdecl supports variadic functions, where the caller does the cleanup. **Linker symbol name decorations:** As mentioned in a bullet point above, calling a function with the "wrong" convention can be disastrous, so Microsoft has a mechanism to avoid this from happening. It works well, though it can be maddening if one does not know what the reasons are. They have chosen to resolve this by encoding the calling convention into the low-level function names with extra characters (which are often called "decorations"), and these are treated as unrelated names by the linker. The default calling convention is \_\_cdecl, but each one can be requested explicitly with the /G? parameter to the compiler. ### \_\_cdecl (cl /Gd ...) All function names of this type are prefixed with an underscore, and the number of parameters does not really matter because the caller is responsible for stack setup and stack cleanup. It is possible for a caller and callee to be confused over the number of parameters actually passed, but at least the stack discipline is maintained properly. ### \_\_stdcall (cl /Gz ...) These function names are prefixed with an underscore and appended with @ plus the number of bytes of parameters passed. By this mechanism, it's not possible to call a function with the wrong amount of parameters. The caller and callee definitely agree on returning with a [`ret 12`](https://www.felixcloutier.com/x86/ret) instruction for example, to pop 12 bytes of stack args along with the return address. You'll get a link-time or runtime DLL error instead of having a function return with ESP pointing somewhere the caller isn't expecting. (For example if you added a new arg and didn't recompile both the main program and the library. Assuming you didn't fool the system by making an earlier arg narrower, like `int64_t` -> `int32_t`.) ### \_\_fastcall (cl /Gr ...) These function names start with an @ sign and are suffixed with the @bytes count, much like \_\_stdcall. The first 2 args are passed in ECX and EDX, the rest are passed on the stack. The byte count includes the register args. As with \_\_stdcall, a narrow arg like `char` still uses up a 4-byte arg-passing slot (a register, or a dword on the stack). Examples: ``` Declaration -----------------------> decorated name void __cdecl foo(void); -----------------------> _foo void __cdecl foo(int a); -----------------------> _foo void __cdecl foo(int a, int b); -----------------------> _foo void __stdcall foo(void); -----------------------> _foo@0 void __stdcall foo(int a); -----------------------> _foo@4 void __stdcall foo(int a, int b); -----------------------> _foo@8 void __fastcall foo(void); -----------------------> @foo@0 void __fastcall foo(int a); -----------------------> @foo@4 void __fastcall foo(int a, int b); -----------------------> @foo@8 ``` Note that in C++, the normal name-mangling mechanism that allows function overloading is used *instead* of `@8`, not as well. So you'll only see actual numbers in `extern "C"` functions. For example, <https://godbolt.org/z/v7EaWs> for example.
What is the meaning and usage of __stdcall?
[ "", "c++", "windows", "calling-convention", "" ]
In a project I am working on, there are really huge collections (1M-1B elements), and things are modified as collections mostly. It's a real-time app, and so the performance is paramount. For some of the operations, like Reverse, BinarySearch (possible?), etc will suffer more than others like Select, etc. Is it feasible to implement one's own IEnumerable with possible MoveNext, MovePrev, etc and own implemented LINQ extensions that take advantages of these? If this is gonna happen, it's gonna happen at the end of the project. Because we need to get it working first, then make it faster. All in all this shouldn't be too much work, right?
It's very definitely possible to create your own implementation of `Enumerable` which might special-case some situations. You'd basically want to detect your own collection types (or possibly just collections such as `List<T>`) and use a more efficient implementation where applicable. I have a [sample project](http://csharpindepth.com/Files/LinqIn60Minutes.zip) which I used to demo "implementing LINQ to Objects in an hour" which you might like to look at for examples. It's not a full implementation and in particular it's *less* efficient than the real LINQ to Objects - but you may still find it interesting. Alternatively, you may find that [i4o (Indexed LINQ)](http://www.codeplex.com/i4o) does everything you need out of the box - or that you would be better off contributing to that than starting from scratch. Worth checking out. Just remember that at the end of the day, LINQ is basically a nice design coupled with syntactic sugar. The C# compiler doesn't know *anything* special about `System.Linq.Enumerable`, for example.
If you really want performance, you can do quite a lot. Remember that the following selection: ``` var result = from element in collection where element.Id == id select element; ``` Compiles as: ``` var result = collection.Where(element => element.Id == id); ``` If you create the following method for the type of `collection`, then you can exploit the fact that the primary action is equality of the Id member and handle the request in an optimized manner. The important thing is correctly identifying the performance-critical operations on your collection and choosing the correct algorithms (i.e. complexity) to perform them. ``` public IEnumerable<TElement> Where(Expression<Func<TElement, bool>> selector) { // detect equality of the Id member and return some special value } ```
Implementing your own LINQ & IEnumerable<T>
[ "", "c#", ".net", "linq", "performance", "ienumerable", "" ]
I'm very new to C# so please bear with me... I'm implementing a partial class, and would like to add two properties like so: ``` public partial class SomeModel { public bool IsSomething { get; set; } public List<string> SomeList { get; set; } ... Additional methods using the above data members ... } ``` I would like to initialize both data members: `IsSomething` to `True` and `SomeList` to `new List<string>()`. Normally I would do it in a constructor, however because it's a partial class I don't want to touch the constructor (should I?). What's the best way to achieve this? Thanks PS I'm working in ASP.NET MVC, adding functionality to a a certain model, hence the partial class.
**Updated for C# 6** C# 6 has added the ability to assign a default value to auto-properties. The value can be any expression (it doesn't have to be a constant). Here's a few examples: ``` // Initialize to a string literal public string SomeProperty {get;set;} = "This is the default value"; // Initialize with a simple expression public DateTime ConstructedAt {get;} = DateTime.Now; // Initialize with a conditional expression public bool IsFoo { get; } = SomeClass.SomeProperty ? true : false; ``` --- **Original Answer** Automatically implemented properties can be initialized in the class constructor, but not on the propery itself. ``` public SomeModel { IsSomething = false; SomeList = new List<string>(); } ``` ...or you can use a field-backed property (slightly more work) and initialize the field itself... ``` private bool _IsSomething = false; public bool IsSomething { get { return _IsSomething; } set { _IsSomething = value; } } ``` **Update:** My above answer doesn't clarify the issue of this being in a partial class. [Mehrdad's answer](https://stackoverflow.com/questions/1272602/c-how-to-set-default-value-for-a-property-in-a-partial-class/1272647#1272647) offers the solution of using a partial method, which is in line with my first suggestion. My second suggestion of using non-automatically implemented properties (manually implemented properties?) will work for this situation.
The first property (IsSomething) is a boolean. It will be false by default. The second property, since it's a reference type, will default to null without any effort on your part. You don't need to touch the constructor, since reference types (classes) will automatically start off as null in .NET. If you wanted to use a non-default value, you'd have two options - First, use a backing storage field: ``` private bool isSomething = true; public bool IsSomething { get { return this.isSomething; } set { this.isSomething = value; } } ``` Second option - add it to the constructor. Note that the first option has no extra overhead - it's basically what the compiler does when you use an automatic property.
C#: How to set default value for a property in a partial class?
[ "", "c#", "properties", "default", "partial-classes", "" ]
I'm trying to go through our development DB right now and clean up some of the old test procs/tables. Is it possible to determine what user created objects in a SQL Server 2005 database? If so, how would I go about finding that information? Edit: Just wanted to clarify that the objects in question already exist. Setting up auditing and triggers probably wouldn't do me much good. I guess I was mostly looking for a way to use the system tables/views to get to the information.
The answer is "no, you probably can't". While there is stuff in there that might say who created a given object, there are a lot of "ifs" behind them. A quick (and not necessarily complete) review: sys.objects (and thus sys.tables, sys.procedures, sys.views, etc.) has column principal\_id. This value is a foreign key that relates to the list of database users, which in turn can be joined with the list of SQL (instance) logins. (All of this info can be found in further system views.) But. A quick check on our setup here and a cursory review of BOL indicates that this value is only set (i.e. not null) if it is "different from the schema owner". In our development system, and we've got dbo + two other schemas, everything comes up as NULL. This is probably because everyone has dbo rights within these databases. This is using NT authentication. SQL authentication probably works much the same. Also, does everyone have *and use* a unique login, or are they shared? If you have employee turnover and domain (or SQL) logins get dropped, once again the data may not be there or may be incomplete. You can look this data over (select \* from sys.objects), but if principal\_id is null, you are probably out of luck.
If the object was recently created, you can check the Schema Changes History report, within the SQL Server Management Studio, which "provides a history of all committed DDL statement executions within the Database recorded by the default trace": ![enter image description here](https://i.stack.imgur.com/bxM8J.png) You then can search for the create statements of the objects. Among all the information displayed, there is the login name of whom executed the DDL statement.
Determine what user created objects in SQL Server
[ "", "sql", "sql-server-2005", "t-sql", "" ]
I have some Matlab image processing code which runs pretty slowly and I'm prepared to convert it over to C/C++. I don't really know much about how matlab works and how code is executed but I'm just interested to hear what kind of speedups I might expect. Clearly there are many variables that will affect this but I'm just looking for a guide perhaps from your own experiences. Thanks Zenna
It mostly depends on the tightness of your loops in Matlab. If you are simply calling a series of built-in Matlab image processing functions, you will most likely not be able to improve performance (most likely you will hurt it). If you are looping over image pixels or doing some kind of block processing, you may see big improvements. If you are doing some looping, but the amount of processing within each iteration is substantial, you may only see little or no improvement. The way I look at Matlab is that every executed line has some amount of overhead. If you can put your solution into the form of a matrix multiply, or some other vector/matrix operation, you only suffer that overhead once and it is negligible. However, with loops, you suffer that overhead every time the loop iterates. Also, most of Matlab's image processing functions are just making calls out to optimized libraries, so don't try to recreate them unless you know for sure where they can be improved. I found that the best approach is to use a combination of C and Matlab. I use Matlab when the operation can be easily vectorized (put in terms of vector/matrix operations). This may mean coming at the solution from a different angle than what seems the most straightforward. Also, it is hard to beat Matlab's plotting and visualization so I would definitely not move to an all C/C++ solution unless you have a plan for how to display with C/C++ (if that is part of your project). If I can't come up with a relatively easy way to vectorize, I just implement the part of processing that needs tight loops in a C mex function that can be called from Matlab. I tend to use C instead of C++ in this case since the process should be relatively small and not need a lot of complicated data abstraction, but C++ would work fine too. Make sure you access image data in column-major order to maximize cache hits since this is how Matlab organizes its matrices.
It really depends on the quality of your Matlab code and what it is you are doing. Idiomatic Matlab code written by a Matlab expert is going to be hard to beat, particularly if you're not an optimization guru and purely expecting a speed up due to the switch of language. For instance, I found even some of the more well regarded C-based FFT libraries were no match for Matlab's FFT. That said, comparing a poorly written Matlab program to an averagely written c++ one, I'd say you're looking at an order of magnitude in my experience.
Speedup Matlab to C++ Conversion
[ "", "c++", "performance", "matlab", "image-processing", "" ]
## Background: I have one Access database (.mdb) file, with half a dozen tables in it. This file is ~300MB large, so not *huge*, but big enough that I want to be efficient. In it, there is one major table, a client table. The other tables store data like consultations made, a few extra many-to-one to one fields, that sort of thing. ## Task: I have to write a program to convert this Access database to a set of XML files, one per client. This is a database conversion application. ## Options: (As I see it) 1. Load the entire Access database into memory in the form of `List`'s of immutable objects, then use Linq to do lookups in these lists for associated data I need. * Benefits: + Easy parallelised. Startup a `ThreadPool` thread for each client. Because all the objects are immutable, they can be freely shared between the threads, which means all threads have access to all data at all times, and it is all loaded exactly once. * (Possible) Cons: + May use extra memory, loading orphaned items, items that aren't needed anymore, etc. 2. Use Jet to run queries on the database to extract data as needed. * Benefits: + Potentially lighter weight. Only loads data that is needed, and as it is needed. * (Possible) Cons: + Potentially heavier! May load items more than once and hence use **more** memory. + Possibly hard to paralellise, unless Jet/OleDb supports concurrent queries (can someone confirm/deny this?) 3. Some other idea? What are StackOverflows thoughts on the best way to approach this problem?
From the sounds of this, it would be a one-time operation. I strongly discourage the actual process of loading the entire setup into memory, that just does not seem like an efficient method of doing this at all. Also, depending on your needs, you might be able to extract directly from Access -> XML if that is your true end game. Regardless, with a database that small, doing them one at a time, with a few specifically written queries in my opinion would be easier to manage, faster to write, and less error prone.
Generate XML parts from SQL. Store each fetched record in the file as you fetch it. Sample: ``` SELECT '<NODE><Column1>' + Column1 + '</Column1><Column2>' + Column2 + '</Column2></Node>' from MyTable ```
Best way to process a large database?
[ "", "c#", "database", "ms-access", "jet", "" ]
Does any one know there have any way I can share a information (it could be cookie, session, variable...) within 2 difference domains but in the same server? Example: I have 2 domain inside the same server, one is called exmaple.com.au and the other one is friendly.com.au. Does there any way that I can share a variable for both domains? (let say $valiable = 'exampleLogin')
Not with cookies or sessions (as I understand them). You could store stuff in files or a database if both sites have access. Alternatively, you may want to look into [cURL](http://curl.haxx.se/).
Browsers adhere to a "same origin" policy for cookies, so setting a cookie from one site can't affect another. The physical server doesn't matter in this case. You could use one site for login purposes and exchange data via POST or GET, but you'd still have to maintain two separate cookies. If both sites have access to the same database, it's probably best to use separate login forms for both, but post a notice ala "You can use your login from sitex.com if you're already registered!"
Any way I can share a information within 2 difference domain?
[ "", "php", "" ]
In C# There seem to be quite a few different lists. Off the top of my head I was able to come up with a couple, however I'm sure there are many more. ``` List<String> Types = new List<String>(); ArrayList Types2 = new ArrayList(); LinkedList<String> Types4 = new LinkedList<String>(); ``` My question is when is it beneficial to use one over the other? More specifically I am returning lists of unknown size from functions and I was wondering if there is a particular list that was better at this.
``` List<String> Types = new List<String>(); LinkedList<String> Types4 = new LinkedList<String>(); ``` are generic lists, i.e. you define the data type that would go in there which decreased boxing and un-boxing. for difference in list vs linklist, see this --> [When should I use a List vs a LinkedList](https://stackoverflow.com/questions/169973/when-should-i-use-a-list-vs-a-linkedlist) ArrayList is a non-generic collection, which can be used to store any type of data type.
99% of the time **List** is what you'll want. Avoid the non-generic collections at all costs. LinkedList is useful for adding or removing without shuffling items around, although you have to forego random access as a result. One advantage it does have is you can remove items whilst iterating through the nodes.
ASP.NET C# Lists Which and When?
[ "", "c#", "asp.net", "list", "" ]
I have an interesting stack of assemblies I want to put together: 1. Common Assembly (C# or C++-CLI) ``` public class MyBase { public void MethodA() { ... } private void MethodB() { ... } protected virtual MethodC() { ... } } ``` 2. Test Code Assemblies (all C++-CLI) ``` public class MySpecific : public MyBase{ protected: override MethodC(); }; ``` 3. Test Simulator (C#) ``` MySpecific obj = new MySpecific(); obj.MethodC(); ``` While assembly 1 could be C++-CLI to keep things simpler, I'd really like to keep assembly 3 in C#. This is largely an exercise to see if inheritance could be done in either direction, but I also have a real-world case where this stack is useful. The first problem I find is that the C++-CLI assembly does not compile because it doesn't recognize MyBase as a class, even though I have a reference to assembly 1 and what looks like the proper namespace. How do I write classes that are language-portable?
I think you have to declare MySpecific as a managed class like this: ``` public ref class MySpecific : public MyBase { ... } ``` See the CLI/C++ documentation for details. You will not be able to use old C++ code without modifications, but I think everything you have in mind should be possible.
Found the answer: ``` `#using "..\common\bin\debug\common.dll"` ``` That, in addition to the /clr switch (the c++ side needs to be mananged) seems to be working, so far.
C# and C++ class inheritance intermingling
[ "", "c#", "inheritance", "c++-cli", "" ]
I'm a big user of properties (with PropertyPlaceholderConfigurer) for making my application as "dynamic" as possible. Almost all the constants are defined as such. Anyway, I'm currently defining a `default.properties` which comes shipped with the default WAR. In other environments (Acceptance/Production) I need to overwrite of the configurations. I'm doing this as following: ``` <bean id="propertyManager" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:com/company/default.properties</value> <value>file:${COMPANY_PROPERTIES_LOCATION}\kbo-select-settings.properties</value> </list> </property> </bean> ``` With this means I can use a promotable build for each of the environments. HOWEVER, I do dislike the fact that I can't change any of my properties from inside WebSphere. Instead I have to go to each of the servers (we have 8 clustered) and change the properties accordingly. It would be a lot more user friendly if I could change those from inside WebSphere and just perform a restart afterwards... Anyone has an idea on how I could do such a promotable build? I already define JNDI configuration for datasources/java mail/etc. Thanks!
We solved this problem by using an extension on the property file for each environment (local, dev, int, tst ...) and each file contained specific values for those environments. The only addition you then require is a VM argument on the server to set -Druntime.env=X. Your lookups in your config file will then look like this ``` <bean id="propertyManager" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:com/company/default.properties.${runtime.env}</value> <value>file:${COMPANY_PROPERTIES_LOCATION}\kbo-select-settings.properties</value> </list> </property> </bean> ``` Of course this only works if you have fairly static environments, as it still doesn't lend itself to changing it at runtime, but it does makes promotion of the application dead simple. If you want to be able to change the values without redeploying your application, you will have to have them stored outside your application, which you already seem to be doing for the *kbo-select-settings.properties*
One potential issue is that you are hardcoding the location of your properties file. You could specify the location of the properties file as a JNDI resource and falling back on the defaults specified on the classpath: ``` <!-- try to lookup the configuration from a URL, if that doesn't work, fall back to the properties on the classpath --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <bean class="org.springframework.core.io.UrlResource"> <constructor-arg> <jee:jndi-lookup jndi-name="url/config" default-value="file:///tmp" /> <!-- dummy default value ensures that the URL lookup doesn't fall over if the JNDI resource isn't defined --> </constructor-arg> </bean> </property> <property name="properties"> <bean class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>classpath:com/company/default.properties</value> </list> </property> </bean> </property> <property name="ignoreResourceNotFound" value="true"/> </bean> ``` That way you can specify different file names for different environments using the WAS console in Resources > URL > URLs by creating a resource with the JNDI-name "url/config" and pointing it to the correct file (file:///your/path/to/properties). As an alternative solution, if you want to manage individual properties through the console, you instead of using the PropertyPlaceholderConfigurer you could use jee:jndi-lookup to get values from the web.xml env-entries (which you can manage using the WAS console). See [this answer](https://stackoverflow.com/questions/1866415/how-to-store-mail-password-on-server-side/1866992#1866992)
WebSphere and PropertyPlaceholderConfigurer
[ "", "java", "spring", "websphere", "" ]
I have a ModalPopupExtender that allows a customer to apply payment info. It has been working great. Then the customer asked to see the total due on the ModalPopup. This did not seem like a big deal to just take the total due from the parent control and pass it into the ModalPopup control. It seems like there is no easy way do to this. Here is my HTML code, keep in mind this code is wrapped in a UpdatePanel ``` <asp:LinkButton ID="lnkMakePayment" runat="server" Visible="true" OnClick="lnkMakePayment_Click" > <asp:Label ID="lblMakePayment" runat="server" Text="Make Payment"/></asp:LinkButton> <asp:Button ID="btnDummy" style="display: none;" runat="server" OnClick="btnDummy_Click" /> <ajaxToolkit:ModalPopupExtender ID="mdlPopupPayment" runat="server" TargetControlID="btnDummy" PopupControlID="pnlMakePayment" CancelControlID="popUpCancel" DropShadow="true" BackgroundCssClass="modalBackground"> </ajaxToolkit:ModalPopupExtender> <asp:Panel ID="pnlMakePayment" runat="server" Style="display: none;" SkinID="PopUpPanel" class="ContentBoxColor" Width="400px" Height="170px"> <MP1:MakePaymentPopup ID="MakePayment" runat="server" /> <div style="text-align: right; width: 100%; margin-top: 5px;"> <asp:Button ID="popUpCancel" runat="server" Text="Cancel" Width="0px" /> </div> </asp:Panel> ``` Now here is the codebehind ``` protected void btnDummy_Click(object sender, EventArgs e) { } protected void lnkMakePayment_Click(object sender, EventArgs e) { mdlPopupPayment.Show(); } ``` So when the user clicks the make payment link the ModalPopup works fine. And it even fires an event that the parent control listens for to apply payment info and all the associated payment details that the user fills out in the popup. Again this all works fine. My first attempt at sending the total due to the ModalPopup is as follows: ``` protected void lnkMakePayment_Click(object sender, EventArgs e) { // MakePayment is the actual ModalPopup control and total due is a public property MakePayment.TotalDue = txtTotalDue.Text mdlPopupPayment.Show(); } ``` The problem with this is that when I click the link to show the ModalPopup the PageLoad event does not fire so I have no way to assign my property to a label inside the ModalPopup. I even attempted to use the session object but had the same issue. I can not even make a trip to the database because I can not pass in a customer ID. Any ideas? I am a novice at Javascript and perfer a server side soultion but at this point I am willing to try anything. The MakePayment user control contains 3 asp textboxes. One for the user to input a payment amount, another for payment type, and a third for notes like check numbers. Also on the control there is an apply and cancel button. The parent control is a basic ascx page which is a data entry screen that contains the ModalPopupExtender and all html code to activate it.
Once I realized what I was doing wrong the solution I came up with was pretty straight forward. I must thank Arnold Matusz for it was his blog entry that showed me the light. <http://blog.dreamlabsolutions.com/post/2009/01/10/ModalPopupExtender-to-show-a-MessageBox.aspx> Instead of having the ModalPopup entender call a user control that just displayed some html. I made a user control that was the ModalPopupExtender. This way I can call it and pass in some data. My MakePayment user control's HTML looks like ``` <asp:Button ID="btnDummy" style="display: none;" runat="server" OnClick="btnDummy_Click" /> <ajaxToolkit:ModalPopupExtender ID="mdlPopupPayment" runat="server" TargetControlID="btnDummy" PopupControlID="pnlMakePayment" CancelControlID="popUpCancel" DropShadow="true" BackgroundCssClass="modalBackground"> </ajaxToolkit:ModalPopupExtender> <asp:Panel ID="pnlMakePayment" runat="server" Style="display: none;" SkinID="PopUpPanel" class="ContentBoxColor" Width="400px" Height="170px"> <div class="contentbox"> <div class="contentboxHeader1"> <asp:Label ID="lblPopupTitle" Width="350px" runat="server" Text=""></asp:Label> </div> <div class="contentbox"> <div style="text-align: left"> <asp:Label ID="lblTotalDue" Width="100px" runat="server" Text=""> </asp:Label> <asp:Label ID="lblTotalDueValue" Width="100px" runat="server"> </asp:Label> </div> <div style="text-align: left"> <asp:Label ID="lblPayment" Width="100px" runat="server" Text=""></asp:Label> <asp:TextBox ID="txtPayment" Width="100px" runat="server"></asp:TextBox> <ajaxToolkit:FilteredTextBoxExtender ID="ftbePayment" runat="server" TargetControlID="txtPayment" FilterType="Custom, Numbers" ValidChars="."> </ajaxToolkit:FilteredTextBoxExtender> </div> <div style="text-align: left"> <asp:Label ID="lblPaymentRefNo" Width="100px" runat="server" Text=""> </asp:Label> <asp:TextBox ID="txtPaymentRefNo" Width="100px" runat="server"> </asp:TextBox> </div> <div style="text-align: left"> <asp:Label ID="lblPaymentType" Width="100px" runat="server" Text=""></asp:Label> <asp:TextBox ID="txtPaymentType" Width="250px" runat="server"></asp:TextBox> </div> </div> <div class="contentbox" style="text-align=right"> <asp:Button ID="btnApplyPayment" runat="server" Text="" OnClick="btnApplyPayment_Click" /> <asp:Button ID="btnCancel" runat="server" Text="" OnClick="btnCancel_Click" /> </div> </div> <div style="text-align: right; width: 100%; margin-top: 5px;"> <asp:Button ID="popUpCancel" runat="server" Text="Cancel" Width="0px" /> </div> </asp:Panel> ``` And in the code behind I have a public method ``` public void MakePayment(string szAmountDue) { lblTotalDueValue.Text = szAmountDue; mdlPopupPayment.Show(); } ``` On my main form I have a link called Make Payment ``` <asp:LinkButton ID="lnkMakePayment" runat="server" Visible="true" OnClick="lnkMakePayment_Click" > <asp:Label ID="lblMakePayment" runat="server" Text=""/> </asp:LinkButton> ``` When the Make Payment link is clicked the code behind calls the MakePayment control passing in any data I wish to display. ``` protected void lnkMakePayment_Click(object sender, EventArgs e) { MakePayment.MakePayment(lblTotalValue.Text.ToString()); } ```
It is not necessary to create a user control to pass data into a modal popup. I would only create a user control if I needed to reuse it in different locations. If you don't need to reuse it in multiple locations then you don't need a user control. Instead do this: Suppose you need a popup that displays a string and has OK and Cancel buttons, but you need to set the string value before it pops up. 1. Create a Panel. 2. Place an UpdatePanel inside the Panel from step 1. 3. Place a Button and ModalPopupExtender inside the UpdatePanel. 4. Place a Label, the Ok and Cancel buttons inside the UpdatePanel, underneath the popup extender. This is shown below: ``` <asp:Panel ID="Panel1" runat="server" CssClass="popup" Width="320px" Style="display:none"> <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"> <ContentTemplate> <asp:Button ID="Button1" runat="server" Style="display:none" /> <cc1:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="Button1" PopupControlID="Panel1" CancelControlID="CancelButton"> </cc1:ModalPopupExtender> <asp:Label ID="Label1" runat="server" /> <asp:Button ID="OkButton" runat="server" Text="Ok" CausesValidation="true" OnClick="OkButton_OnClick" />&nbsp; <asp:Button ID="CancelButton" runat="server" Text="Cancel" CausesValidation="false" /> </ContentTemplate> </asp:UpdatePanel> </asp:Panel> ``` 5. Next, on your page, place a Button and a TextBox like this: ``` <asp:TextBox ID="MyTextBox" runat="server" /> <asp:Button ID="MyButton" runat="server" Text="Popup" OnClick="MyButton_OnClick" /> ``` 6. Now, in the code behind for your page, place the handler for `MyButton`: ``` protected void MyButton_OnClick(object sender, EventArgs e) { Label1.Text = MyTextBox.Text; UpdatePanel1.Update(); ModalPopupExtender1.Show(); } ```
Passing data into a ModalPopupExtender
[ "", "c#", "html", "asp.net-ajax", "" ]
I have a url, ``` example.com/?/page1 ``` and i want to find out what the GET part of the url is, for example: ``` ?/page1 ``` how do i do this? like, without having to split strings and stuff?
The following variable will contain the entirety of the query string (that is, the portion of the url following the ? character): ``` $_SERVER['QUERY_STRING'] ``` If you're curious about the rest of the contents of the $\_SERVER array, they're listed in the PHP manual [here](https://www.php.net/manual/en/reserved.variables.server.php).
That is a strange GET URL because the normal format is: `domain.com/page.html?a=1&b=2` PHPinfo will help a whole lot: ``` <?php phpinfo(); ?> ``` Output of relevance: ``` <?php // imagine URL is 'domain.com/page.html?a=1&b=2' phpinfo(); echo $_GET['a']; // echoes '1' echo $_GET['b']; // echoes '2' echo $_SERVER['QUERY_STRING']; // echoes 'a=1&b=2' echo $_SERVER['REQUEST_URI']; // echoes '/path/to/page.php?a=1&b=2' ?> ```
How do you just get the vars in a url using php?
[ "", "php", "url", "get", "" ]
Ok, I'm sorry, this is probably a noob question but I'm kinda stuck. So what I'm doing (on my asp.net application) is loading an image from the file system: ``` System.Drawing.Image tempImage; tempImage = System.Drawing.Image.FromFile(HttpContext.Server.MapPath(originalPath)); ``` Then I do some resizing: ``` tempImage = my awesomeResizingFunction(tempImage, newSize); ``` and intend to save it to the file system in another location using this: ``` string newPath = "/myAwesomePath/newImageName.jpg"; tempImage.Save(newPath); ``` and what I get is this error: ``` "A generic error occurred in GDI+." ``` I know the image is "ok" because I can write it out to the browser and see the resized image, I only get the error when I try to save it. I'm kinda new and stuck, am I doing this totally wrong? (Well, i guess that's obvious but you know what I mean...)
Try this code... I have used the same code for resizing image and saving. ``` System.Drawing.Bitmap bmpOut = new System.Drawing.Bitmap(NewWidth, NewHeight); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmpOut); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.FillRectangle(System.Drawing.Brushes.White, 0, 0, NewWidth, NewHeight); g.DrawImage(new System.Drawing.Bitmap(fupProduct.PostedFile.InputStream), 0, 0, NewWidth, NewHeight); MemoryStream stream = new MemoryStream(); switch (fupProduct.FileName.Substring(fupProduct.FileName.IndexOf('.') + 1).ToLower()) { case "jpg": bmpOut.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); break; case "jpeg": bmpOut.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); break; case "tiff": bmpOut.Save(stream, System.Drawing.Imaging.ImageFormat.Tiff); break; case "png": bmpOut.Save(stream, System.Drawing.Imaging.ImageFormat.Png); break; case "gif": bmpOut.Save(stream, System.Drawing.Imaging.ImageFormat.Gif); break; } String saveImagePath = Server.MapPath("../") + "Images/Thumbnail/" + fupProduct.FileName.Substring(fupProduct.FileName.IndexOf('.')); bmpOut.Save(saveImagePath); ``` where `fupProduct` is fileupload control ID
Are you sure that the originalPath and newPath point to different files ? When you use Image.FromFile, the file remains locked until you call Dispose on the Image, which can lead to the exception you mentioned. You could load the image like that instead : ``` Image tempImage = null; using (FileStream fs = new FileStream(originalPath, FileMode.Open, FileAccess.Read)) { tempImage = Image.FromStream(fs); } ... ``` This approach guarantees that the file is closed at the end of the using block
Create a new image on the file system from System.Drawing.Image?
[ "", "c#", "asp.net", "gdi+", "thumbnails", "image-resizing", "" ]
I'm thinking of developing a desktop app in C#. Although windows will be my main target, later I'll try and run the app in MacOS X and linux. Can I do this today, in a simple way? I'm aware of the mono project, but it is not clear to me if I can do this in a simple way. Also, what is the relation between WPF and Silverlight? AFAIK Silverlight follows a plugin model much like Flash or Java. Can I develop my desktop app with Silverlight and deploy it on windows, linux and os x without much changes? Any pointers will be greatly appreciated.
The Mono project does not support .Net 3 and WPF yet, and it will probably been some time before that happens. Silverlight might be sufficient for your needs. As of Silverlight 3.0 you can run Silverlight outside the browser, even create a shortcut to it on the desktop.
Last I heard, the Mono project has no plans to implement WPF, however they are working on other .NET 3.5 features, especially LINQ and ASP.NET MVC. The problem with implementing WPF in Mono (beyond the size and complexity of the API) is that on Windows it uses DirectX for rendering, so an implementation for Mono would need to use OpenGL. Definitely not a trivial undertaking.
Cross platform apps with WPF
[ "", "c#", "wpf", "mono", "cross-platform", "" ]
Does anyone know of a tool to remove redundant `using` statements from classes, or a whole solution? I'm using the Refactor! addin which has a "move type to separate file" smart tag, but it takes all the `using` clauses from the original class with it.
[PowerCommands](http://code.msdn.microsoft.com/PowerCommands) for Visual Studio upgrades the default VS.NET 2008 functionality of "Remove Usings" to an entire project or solution. I use it all the time. It also has a lot of other useful features- check it out. Best of all it is FREE.
VisualStudio 2008 does this out of the box. Simply right click in the code window -> Organise Usings -> Remove Unused Usings. You can set up a shortcut key to do this, as explained [here](http://www.semdendoncker.com/blog/?p=74).
Removing redundant using statements
[ "", "c#", "visual-studio", "using-statement", "" ]
I am scraping a list of RSS feeds by using cURL, and then I am reading and parsing the RSS data with SimpleXML. The sorted data is then inserted into a mySQL database. However, as notice on <http://dansays.co.uk/research/MNA/rss.php> I am having several issues with characters not displaying correctly. Examples: ``` âGuitar Hero: Van Halenâ Trailer And Tracklist Available NV 10/10/09 – Salt Lake City, UT 10/11/09 – Denver, CO 10/13/09 – ``` I have tried using htmlentities and htmlspecialchars on the data before inserting them into the database, but it doesn't seem to help resolve issue. How could I possibly resolve this issue I am having? Thanks for any advices. *Updated* I've tried what Greg suggested, and the issue is still here... Here is the code I used to do SET NAMES in PDO: ``` $dbh = new PDO($dbstring, $username, $password); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbh->query('SET NAMES "utf8"'); ``` I did a bit of echo'ing with the simplexml data before it is sorted and inserted into the database, and I now believe it is something to do with the cURL... Here is what I have for cURL: ``` $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8'); $data = curl_exec($ch); curl_close($ch); $doc = new SimpleXmlElement($data, LIBXML_NOCDATA); ``` *Issue Resolved* I had to set the content charset in the RSS/HTML page to "UTF-8" to resolve this issue. I guess this isn't a real fix as the char problems are still there in the raw data. Looking forward to proper support for it in PHP6!
Like all debugging, you start by isolating the problem: *I am scraping a list of RSS feeds by using cURL,* - look at the xml from the RSS feed that's giving the problem (there's more than one feed, so it's possible for some feeds to be right and for the feeds that are wrong to be wrong in different ways) *and then I am reading and parsing the RSS data with SimpleXML.* - print out the field that SimpleXML read out - is it ok or does a problem show up? *The sorted data is then inserted into a mySQL database.* - print out hex(field), length(field), and char\_length(field) for the piece of data that's giving the problem. EDIT Take the feed <http://hangout.altsounds.com/external.php?type=RSS2> , put it into the validator <http://validator.w3.org/feed/> . They're declaring their content type as iso-8859-1 but some of the actual content, such as the quotes, is in something like cp1252 - for example they're using the byte 0x93 to represent the left quote - <http://www.fileformat.info/info/unicode/char/201C/charset_support.htm> . What's annoying about this is that this doesn't show up in some tools - Firefox seems to guess what's going on and show the quotes correctly, and more to the point, SimpleXML converts the 0x93 into utf8, so it comes out as 0xc293, which exacerbates the problem. EDIT 2 A workaround to get that feed to read a bit more correctly is to replace "ISO-8859-1" by "Windows-1252" before passing to Simple XML. It won't work 100% because it turns out that some parts of the feed are in UTF8. The general approach, assuming that you can't get everyone in the world to correct their feeds, is to isolate whatever workarounds you require to the interface with the external system that's emitting the malformed data, and to pass in pure clear utf8 to the hub of your system. Save a dated copy of the raw external feed so you can remember in future why the workaround was required, separate off and comment the code lines that implement the workaround so it's easy to get at and change if and when the external organisation corrects its feed (or breaks it in a different way), and check it again from time to time. Unfortunately instead of programming to a spec you're programming to the current state of a bug, so there's no permanent, clean solution - the best you can do is isolate, document, and monitor.
Your page is being served as UTF-8 so I'd point my finger at the database. Make sure the connection is in UTF-8 before any SELECTs or INSERTS - in MySQL: ``` SET NAMES "utf8" ```
PHP: UTF 8 characters encoding
[ "", "php", "utf-8", "curl", "simplexml", "" ]
I have the following array: ``` Array ( [1] => Array ( [spubid] => A00319 [sentered_by] => pubs_batchadd.php [sarticle] => Lateral mixing of the waters of the Orinoco, Atabapo [spublication] => Acta Cientifica Venezolana [stags] => acta,confluence,orinoco,rivers,venezuela,waters [authors] => Array ( [1] => Array ( [stype] => Author [iorder] => 1 [sfirst] => A [slast] => Andersen ) [2] => Array ( [stype] => Author [iorder] => 2 [sfirst] => S. [slast] => Johnson ) [3] => Array ( [stype] => Author [iorder] => 3 [sfirst] => J. [slast] => Doe ) ) ) ) ``` I am using a nested foreach() to walk through the elements in the outer array but when it comes to spitting out the list of authors I am running into problems. Namely the problem of outputting each one multiple (multiple) times because of the crazy foreach() nesting. What would be a better approach than nesting foreach() loops in this example? **UPDATE (With solution)** Here is the loop I settled on, a bit messy (IMHO) but it works: ``` $sauthors = NULL; $stitle = NULL; foreach($apubs as $apub) { $stitle = $apub['sarticle']; foreach($apub as $svar=>$sval) { if($svar === "authors") { foreach($sval as $apeople) { $sauthors .= $apeople['slast'].", ".$apeople['sfirst']."; "; } } } echo "$sauthors<br />\n$stitle<br />\n"; } ```
Why don't you do ``` foreach($apubs as $apub) { $sauthors = ''; $stitle = $apub['sarticle']; foreach($apub['authors'] as $author) { $sauthors .= $author['slast'].", ".$author['sfirst']."; "; } echo "$sauthors<br />\n$stitle<br />\n"; } ```
Just for fun. If you *really* want to avoid loops, try this: ``` // Pre PHP 5.3: function cb2($e) { return $e['slast'] . ', ' . $e['sfirst']; } function cb1($e) { $authors = array_map('cb2', $e['authors']); echo implode('; ', $authors) . ":<br />\n" . $e['sarticle'] . "<br />\n"; } array_walk($data, 'cb1'); // PHP 5.3 (untested): array_walk($data, function($e) { $authors = array_map(function($e) { return $e['slast'] . ', ' . $e['sfirst']; }, $e['authors']); echo implode('; ', $authors) . ":<br />\n" . $e['sarticle'] . "<br />\n"; }); ```
Nested foreach()
[ "", "php", "arrays", "loops", "foreach", "" ]
I have a string which contains words in a mixture of upper and lower case characters. For example: `string myData = "a Simple string";` I need to convert the first character of each word (separated by spaces) into upper case. So I want the result as: `string myData ="A Simple String";` Is there any easy way to do this? I don't want to split the string and do the conversion (that will be my last resort). Also, it is guaranteed that the strings are in English.
MSDN : [TextInfo.ToTitleCase](https://learn.microsoft.com/en-us/dotnet/api/system.globalization.textinfo.totitlecase) Make sure that you include: `using System.Globalization` ``` string title = "war and peace"; TextInfo textInfo = new CultureInfo("en-US", false).TextInfo; title = textInfo.ToTitleCase(title); Console.WriteLine(title) ; //War And Peace //When text is ALL UPPERCASE... title = "WAR AND PEACE" ; title = textInfo.ToTitleCase(title); Console.WriteLine(title) ; //WAR AND PEACE //You need to call ToLower to make it work title = textInfo.ToTitleCase(title.ToLower()); Console.WriteLine(title) ; //War And Peace ```
Try this: ``` string myText = "a Simple string"; string asTitleCase = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo. ToTitleCase(myText.ToLower()); ``` As has already been pointed out, using TextInfo.ToTitleCase might not give you the exact results you want. If you need more control over the output, you could do something like this: ``` IEnumerable<char> CharsToTitleCase(string s) { bool newWord = true; foreach(char c in s) { if(newWord) { yield return Char.ToUpper(c); newWord = false; } else yield return Char.ToLower(c); if(c==' ') newWord = true; } } ``` And then use it like so: ``` var asTitleCase = new string( CharsToTitleCase(myText).ToArray() ); ```
Converting string to title case
[ "", "c#", "string", "" ]
I've a some type (object of `Type`). Need to check that this type has interface IList. How I can do this?
Assuming you have an object `type` with the type `System.Type` (what I gathered from the OP), ``` Type type = ...; typeof(IList).IsAssignableFrom(type) ```
You can use the [Type.GetInterface](http://msdn.microsoft.com/en-us/library/system.type.getinterface.aspx) method. ``` if (object.GetType().GetInterface("IList") != null) { // object implements IList } ```
How to check that current type (object of Type) has needed interface (or parent type)
[ "", "c#", ".net", "types", "" ]
I have a list of strings - something like ``` mytext = ['This is some text','this is yet more text','This is text that contains the substring foobar123','yet more text'] ``` I want to find the first occurrence of anything that starts with foobar. If I was grepping then I would do search for foobar\*. My current solution looks like this ``` for i in mytext: index = i.find("foobar") if(index!=-1): print i ``` Which works just fine but I am wondering if there is a 'better' (i.e more pythonic) way of doing this? Cheers, Mike
You can also use a list comprehension : ``` matches = [s for s in mytext if 'foobar' in s] ``` (and if you were really looking for strings *starting* with 'foobar' as THC4k noticed, consider the following : ``` matches = [s for s in mytext if s.startswith('foobar')] ```
If you really want the FIRST occurrence of a string that STARTS WITH foobar (which is what your words say, though very different from your code, all answers provided, your mention of grep -- how contradictory can you get?-), try: ``` found = next((s for s in mylist if s.startswith('foobar')), '') ``` this gives an empty string as the `found` result if no item of mylist meets the condition. You could also use itertools, etc, in lieu of the simple genexp, but the key trick is this way of using the `next` builtin with a default (Python 2.6 and better only).
Pythonic way of searching for a substring in a list
[ "", "string", "list", "python", "substring", "" ]
I want to write an email transfer service and need a MTU replacement of sendmail/postfix. I'm not looking how to deliver to a transmitting SMTP server (like a postfix listing on a SMTP port). I also don't need the receiving part of the server, bounces etc. would go to a different existing postfix. All of it in pure PHP. SMTP is a pretty easy protocol but this would require access to the MX DNS record and other lot of details that need to be taken care of. Why do i need this? Because most shared internet providers have insane low limits for sending out emails like 500 per day. Thats almost nothing if you want to setup even the lowest traffic email list. EDIT: Please Note: **The code needs to connect to the receivers SMTP server and deliver the message with an adapted header set (removed BCC list, added Path route).** If you see a SMTP class less then 5000 lines or requires you to configure a SMTP hostip and port then this is not the stuff i'm looking for. It needs to do all the stuff sendmail is doing just as a PHP library.
I use [Pear's Mail](http://pear.php.net/package/Mail) class. **EDIT** After re-reading this, I see there's more to it than just a library. You are asking to send direct to the remote MX. Why reinvent the wheel? Set up an instance of postfix on the server, which only listens to connections from the web server... and let an MTA do what it does best. Hand off the messages from php to a real mail server and move on. In the case of ISP's that block outbound port 25 and force the use of a smarthost, this also allows you to restrict the rate of messages sent to the smarthost. Lastly, sending straight to the end MX from your php script is a bad idea, because if you send to me, I'll never get it. I and many other sites use "greylisting" to reduce spam, which denies all initial requests with a 450 temporary error. Real MTA's will try again, but unless you implemented a delay queue and try again, your message will never go through.
We use <http://sourceforge.net/projects/phpmailer/> to do SMTP email from PHP
Is there a SMTP mail transfer library in PHP
[ "", "php", "smtp", "" ]
I'm working on an application that I will soon be publicly distributing. I would like to do anything in my power to make sure those who download my program do not reverse engineer it. I understand that distributing a .jar file is highly insecure. Can anyone recommend a platform independent way to distribute my Java application? Also, I would like to install it as a service on any platform (Windows, Linux, Mac OSX). Thanks!
You can scramble / obfuscate your bytecode with [yGuard](http://www.yworks.com/en/products_yguard_about.htm) or other java-bytecode-obfuscators. Operating System independent distribution can be difficult. IMHO the best solution is a normal archive containing several scripts (.bat/.cmd for windows, .sh for linux / OSX)for the program-start under the Operating Systems the program supports. Running a java-program as service can be even more difficult: It's easy under Linux, where you just have to write a proper startup-script to run it in the background. I know that FireDaemon has problems running java-programs as service, so it might be difficult (or impossible) to run it as service on Windows. Sorry, but I've no idea about MacOS X. Could be as easy as Linux, could be as impossible as Windows.
As others have said, you can obfuscate your code. That will make reverse engineering non-trivial. You could also compile your Java to native code using (for example) GCJ. That will make reverse engineering harder, but it will also mean that you have to create different distribution bundles for each supported hardware/OS platform. > I understand that distributing a .jar file is highly insecure. You have to understand that if you distribute software *in any form* to run on a platform that you don't fully control, then there is nothing technical that you can do to prevent reverse engineering. Nothing. Ultimately, you have to trade off the benefits of distributing your software versus the risks of someone reverse engineering it. One approach people take is to figure out if the benefits outweigh the risks \* costs, and use legal safeguards (e.g. appropriate software licenses) to deter reverse engineering. The other approach is to say "good luck to you" to potential reverse engineers and make your money by offering services rather than software licenses.
Protecting Java jar Files for Distribution
[ "", "java", "security", "installation", "" ]
I would like to get property name when I'm in it via reflection. Is it possible? I have code like this: ``` public CarType Car { get { return (Wheel) this["Wheel"];} set { this["Wheel"] = value; } } ``` And because I need more properties like this I would like to do something like this: ``` public CarType Car { get { return (Wheel) this[GetThisPropertyName()];} set { this[GetThisPropertyName()] = value; } } ```
Since properties are really just methods you can do this and clean up the get\_ returned: ``` class Program { static void Main(string[] args) { Program p = new Program(); var x = p.Something; Console.ReadLine(); } public string Something { get { return MethodBase.GetCurrentMethod().Name; } } } ``` If you profile the performance you should find MethodBase.GetCurrentMethod() is miles faster than StackFrame. In .NET 1.1 you will also have issues with StackFrame in release mode (from memory I think I found it was 3x faster). That said I'm sure the performance issue won't cause too much of a problem- though an interesting discussion on StackFrame slowness can be [found here](http://osdir.com/ml/log.log4net.user/2005-06/msg00049.html). I guess another option if you were concerned about performance would be to create a Visual Studio Intellisense Code Snippet that creates the property for you and also creates a string that corresponds to the property name.
Slightly confusing example you presented, unless I just don't get it. From C# 6.0 you can use the `nameof` operator. ``` public CarType MyProperty { get { return (CarType)this[nameof(MyProperty)]}; set { this[nameof(MyProperty)] = value]}; } ``` If you have a method that handles your getter/setter anyway, you can use the C# 4.5 `CallerMemberName` attribute, in this case you don't even need to repeat the name. ``` public CarType MyProperty { get { return Get<CarType>(); } set { Set(value); } } public T Get<T>([CallerMemberName]string name = null) { return (T)this[name]; } public void Set<T>(T value, [CallerMemberName]string name = null) { this[name] = value; } ```
How to get current property name via reflection?
[ "", "c#", "reflection", "properties", "" ]
I have already created a table to the database. Table is something like following (I am using sqlite on mac for iPhone dev) ``` create table ( attendanceDate varchar, studentNo integer, absentDetail varchar ); ``` Now I have already committed this statements. What I need is the following: * Add a composite primary key (attandanceDate,studentNo) * add a foreign key studentNo I don't know the alter table syntax in sqlite3. So, I need help. Thanks in advance.
SQLITE3 does not have syntax to do what you want. From the SQLITE documentation at <http://www.sqlite.org/lang_altertable.html> > SQLite supports a limited subset of > ALTER TABLE. The ALTER TABLE command > in SQLite allows the user to rename a > table or to add a new column to an > existing table. It is not possible to > rename a colum, remove a column, or > add or remove constraints from a > table. You will need to recreate the table with the composite primary key and foreign key defined.
When you create the table you need to create the primary key then. SQLLite3 doesn't support foreign key constraints as far as I know. Check out [this link](http://www.sqlite.org/omitted.html) for more information. I hope this helps.
SQL adding composite primary key through alter table option
[ "", "sql", "sqlite", "" ]
What is a global interpreter lock and why is it an issue? A lot of noise has been made around removing the GIL from Python, and I'd like to understand why that is so important. I have never written a compiler nor an interpreter myself, so don't be frugal with details, I'll probably need them to understand.
Python's GIL is intended to serialize access to interpreter internals from different threads. On multi-core systems, it means that multiple threads can't effectively make use of multiple cores. (If the GIL didn't lead to this problem, most people wouldn't care about the GIL - it's only being raised as an issue because of the increasing prevalence of multi-core systems.) If you want to understand it in detail, you can view [this video](https://www.youtube.com/watch?v=ph374fJqFPE) or look at [this set of slides](http://www.dabeaz.com/python/GIL.pdf). It might be too much information, but then you did ask for details :-) Note that Python's GIL is only really an issue for CPython, the reference implementation. Jython and IronPython don't have a GIL. As a Python developer, you don't generally come across the GIL unless you're writing a C extension. C extension writers need to release the GIL when their extensions do blocking I/O, so that other threads in the Python process get a chance to run.
Suppose you have multiple threads which don't *really* touch each other's data. Those should execute as independently as possible. If you have a "global lock" which you need to acquire in order to (say) call a function, that can end up as a bottleneck. You can wind up not getting much benefit from having multiple threads in the first place. To put it into a real world analogy: imagine 100 developers working at a company with only a single coffee mug. Most of the developers would spend their time waiting for coffee instead of coding. None of this is Python-specific - I don't know the details of what Python needed a GIL for in the first place. However, hopefully it's given you a better idea of the general concept.
What is the global interpreter lock (GIL) in CPython?
[ "", "python", "python-internals", "gil", "" ]
I'm busy with a simple application. It reads xml and puts the information in a treeview. I do this by creating TreeNodes and nest them, and finaly, return the root treenode. Because I want to show some extra information when a treenode is selected, I put the information in the tag property of the TreeNode. In this way, I should be able to retrieve the information when the node is selected. But when I try to retrieve the information in the Tag property, it says the value = null. Here is the code where I fill the tag. This is in a function which is recursively used to read the XML dom. treeNode is a paramater given to this function. ``` if (treeNode.Tag == null) { treeNode.Tag = new List<AttributePair>(); } (treeNode.Tag as List<AttributePair>).Add(new AttributePair(currentNode.Name, currentNode.Value)); ``` This is the event where a treenode is selected ``` private void tvXML_AfterSelect(object sender, TreeViewEventArgs e) { if (tvXML.SelectedNode.Tag != null) { } if (e.Node.Tag != null) { } } ``` Both values evaluate to null. How can I solve this problem?
The code you posted should work as-is. Something else in your code, code that you didn't post here, is causing this to break. It could be clearing the Tag, it could be a data binding set on the tag, etc. Without seeing all your code, the best I can do is guess and help you isolate the problem. Here's what I'd do: [setup Visual Studio to allow stepping into the .NET framework source code with the debugger](http://weblogs.asp.net/scottgu/archive/2008/01/16/net-framework-library-source-code-now-available.aspx). Then, set a breakpoint on the setter for the TreeNode.Tag property. After you set the tag in your code to your AttributePair List, see when it gets set again. The breakpoint will hit, you'll look at the stack trace and see what exactly is clearing your Tag property.
If using Tag property isn't in principle, I'm recommend inherit TreeItem: ``` public class MyTreeNode : TreeNode { public List<AttributePair> list; public MyTreeNode (string text,List<AttributePair> list) : base(text) { this.list = list; } //or public MyTreeNode (string text) : base(text) { this.list = new List<AttributePair>(); } } ``` And use it: ``` private void tvXML_AfterSelect(object sender, TreeViewEventArgs e) { if (tvXML.SelectedNode is MyTreeNode) { MyTreeNode selectedNode = tvXML.SelectedNode as MyTreeNode; selectedNode.list.Add(.., ..); } if (e.Node is MyTreeNode) { MyTreeNode node = e.Node as MyTreeNode; node.list.Add(.., ..); } } ```
Value of tag property disappears
[ "", "c#", "winforms", "" ]
What is the best way to store data between program runs in Java? I already know that you can use a text file and store the information that way, but I was wondering if there is a better way to store the information that is generated by the program between runs of the program. Also, is there any way to do it so as to keep the information secure? Specifically, I want to keep the end user from being able to access it.
> I was wondering if there was any way > other placing the information that is > genereated by the program between runs > of the program? Simply use an `ObjectOutputStream` to serialize it into a file and an `ObjectInputStream` to get it back. > Also is there any way to do it so as > to keep the information secure? from > the end user being able to access it? If the code runs on the end user's system then no, there is no way to prevent them from getting the data - it's not even worth your time trying to encode it somehow, since it's easy to attach a debugger and inspect the program's state while it's running. As a binary format, Java serialization will prevent non-technical users from deciphering it, and that's pretty much the best you can hope for.
I've never used it myself, but I think that's what the JDK's [java.util.prefs.Preferences](http://java.sun.com/j2se/1.5.0/docs/api/java/util/prefs/Preferences.html) was originally designed for.
Best way to store data between program runs in java?
[ "", "java", "storage", "information-hiding", "" ]
I try to make my evoque templates color-code a bit, but the html I get is already escaped with lt-gt's I read there should be something like a quoted-no-more class but I haven't been able to find the evoque.quoted package My aim is to not have escaped html coming out of the template, but 'real'. ``` from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import HtmlFormatter from evoque.domain import Domain import os tmpl=""" $begin{code} ${codyfy(evoque(name=label), lang=label.split()[0][1:])} $end{code} $begin{c 0} int main(void){printf("hello world");return 0;} $end{c 0} $begin{python 0} print "hello world" $end{python 0} $evoque{#code, label="#c 0"} $evoque{#code, label="#python 0"} """ td = Domain(os.path.abspath(".")) def codyfy(src,lang="python"): return highlight(src,get_lexer_by_name(lang, stripall=True),HtmlFormatter()) td.set_on_globals('codyfy',codyfy) td.set_template("testtmpl", src=tmpl, from_string=True) t = td.get_template("testtmpl") print t.evoque() ```
Have you tried it with `raw=True`? See: * <http://evoque.gizmojo.org/howto/source/> I haven't used Qpy before, but perhaps this note will help: > [Defining custom quoted-no-more classes](http://evoque.gizmojo.org/howto/quoted-no-more/) > > [...] It is also highly recommended to download and install the Qpy unicode templating utility that provides the qpy.xml Quoted-No-More class for automatic input escaping. [...]
Yeps - we got in parallel, ars and I. The answer is here - snip it into above: ``` from qpy import xml def codyfy(src,lang="python"): return xml(highlight(src,get_lexer_by_name(lang, stripall=True),HtmlFormatter())) ``` xml() is apparently sort of a payload making subsequent escapers lay off.
How to avoid html-escaping in evoque
[ "", "python", "" ]
I wanted to ask about the pros cons of my the following OOP style. I write my JS classes in the following manner. ``` var MyClass = function() { // private vars var self = this, _foo = 1, _bar = "test"; // public vars this.cool = true; // private methods var initialize = function(a, b) { // initialize everything }; var doSomething = function() { var test = 34; _foo = cool; }; // public methods this.startRequest = function() { }; // call the constructor initialize.apply(this, arguments); }; var instance_1 = new MyClass(); var instance_2 = new MyClass("just", "testing"); ``` Is this a good approach? Is there any drawback? I don't use inheritance, but would it work this way to achieve inheritance? Thanks in advance.
I think it's a very good approach. Don't be ashamed of the 'no inheritance' issue. Most OOP isn't about inheritance. The most important aspects are the encapsulation and polymorphism, and you've got them. It can be argued (well, i usually argue) that inheritance is only needed for static languages, where you have to somehow tell the compiler that these two types (classes) are related, that they have something in common (the common ancestor) so that it can allow polymorphism. With dynamic languages, OTOH, the compiler won't care, and the runtime environment will find the commonalities without any inheritance. Another point: if you need some inheritance in some places (and it's *great* in some cases, like GUIs, for example), often you'll find that you can easily interoperate between your 'simple' objects/classes, and other more complex and heavier. IOW: don't try to find a framework that fills all your needs and use it for everything; instead use the one that you're more comfortable with at each moment, as long as it helps with the specific problem.
I found those articles by Douglas Crockford very informative: * [The World's Most Misunderstood Programming Language](http://www.crockford.com/javascript/javascript.html) * [Private Members in JavaScript](http://www.crockford.com/javascript/private.html) * [Classical Inheritance in JavaScript](http://www.crockford.com/javascript/inheritance.html)
Is this a good way to do JS OOP?
[ "", "javascript", "oop", "" ]
If I call a virtual function 1000 times in a loop, will I suffer from the vtable lookup overhead 1000 times or only once?
The Visual C++ compiler (at least through VS 2008) does not cache vtable lookups. Even more interestingly, it doesn't direct-dispatch calls to virtual methods where the static type of the object is [sealed](http://msdn.microsoft.com/en-us/library/0w2w91tf.aspx). However, the actual overhead of the virtual dispatch lookup is almost always negligible. The place where you sometimes do see a hit is in the fact that virtual calls in C++ cannot be replaced by direct calls like they can in a managed VM. This also means no inlining for virtual calls. The only true way to establish the impact for your application is using a profiler. Regarding the specifics of your original question: if the virtual method you are calling is trivial enough that the virtual dispatch itself is incurring a measurable performance impact, then that method is sufficiently small that the vtable will remain in the processor's cache throughout the loop. Even though the assembly instructions to pull the function pointer from the vtable are executed 1000 times, the performance impact will be much less than `(1000 * time to load vtable from system memory)`.
The compiler may be able to optimise it - for example, the following is (at least conceptually) easliy optimised: ``` Foo * f = new Foo; for ( int i = 0; i < 1000; i++ ) { f->func(); } ``` However, other cases are more difficult: ``` vector <Foo *> v; // populate v with 1000 Foo (not derived) objects for ( int i = 0; i < v.size(); i++ ) { v[i]->func(); } ``` the same conceptual optimisation is applicable, but much harder for the compiler to see. Bottom line - if you really care about it, compile your code with all optimisations enabled and examine the compiler's assembler output.
about the cost of virtual function
[ "", "c++", "virtual", "" ]
In PHP, how can I get the URL of the current page? Preferably just the parts after `http://domain.example`.
``` $_SERVER['REQUEST_URI'] ``` For more details on what info is available in the $\_SERVER array, see [the PHP manual page for it](https://www.php.net/manual/en/reserved.variables.server.php). If you also need the query string (the bit after the `?` in a URL), that part is in this variable: ``` $_SERVER['QUERY_STRING'] ```
If you want just the parts of URL after `http://domain.example`, try this: ``` <?php echo $_SERVER['REQUEST_URI']; ?> ``` If the current URL was `http://domain.example/some-slug/some-id`, echo will return only `/some-slug/some-id`. --- If you want the full URL, try this: ``` <?php echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?> ```
How to get URL of current page in PHP
[ "", "php", "url", "" ]
I've a big XML data returned by SAP. Of this, I need only few nodes, may be 30% of the returned data. After googling, I got to know that I can filter the nodes in either of the ways: 1. Apply XSLT templates - Have seen some nice solutions, which i want, in this site only. 2. Using a parser - use JDOM or SAX parser. which is the efficient way to "filter XML nodes"? thanks
SAX parser will be the fastest and most efficient (in that you don't need to read the entire document into memory and process it). XSLT will be probably a terser solution since all you need is an [identity transform](http://en.wikipedia.org/wiki/Identity_transform) (to copy the input document) with a few templates to copy out the bits you want. Personally I'd go with the SAX parser.
The [StAX API](http://java.sun.com/javaee/5/docs/tutorial/doc/bnbdv.html) may suit your needs - have a look at [StreamFilter](http://java.sun.com/javase/6/docs/api/javax/xml/stream/StreamFilter.html) or [EventFilter](http://java.sun.com/javase/6/docs/api/javax/xml/stream/EventFilter.html). It has an advantage over SAX in that its pull model makes it is easier to quit processing when you've parsed all the data you want without resorting to artificial mechanisms like throwing an exception.
Filtering XML nodes in Java | XSLT or Parser
[ "", "java", "xml", "filtering", "" ]
I have a situation where I have an interface that defines how a certain class behaves in order to fill a certain role in my program, but at this point in time I'm not 100% sure how many classes I will write to fill that role. However, at the same time, I know that I want the user to be able to select, from a GUI combo/list box, which concrete class implementing the interface that they want to use to fill a certain role. I want the GUI to be able to enumerate all available classes, but I would prefer not to have to go back and change old code whenever I decide to implement a new class to fill that role (which may be months from now) Some things I've considered: 1. using an enumeration * Pros: 1. I know how to do it * Cons 1. I will have to update update the enumeration when I add a new class 2. ugly to iterate through 2. using some kind of `static` list object in the interface, and adding a new element from within the definition file of the implementing class * Pros: 1. Wont have to change old code * Cons: 1. Not even sure if this is possible 2. Not sure what kind of information to store so that a factory method can choose the proper constructor ( maybe a map between a string and a function pointer that returns a pointer to an object of the interface ) I'm guessing this is a problem (or similar to a problem) that more experienced programmers have probably come across before (and often), and there is probably a common solution to this kind of problem, which is almost certainly better than anything I'm capable of coming up with. So, how do I do it? (P.S. I searched, but all I found was this, and it's not the same: [How do I enumerate all items that implement a generic interface?](https://stackoverflow.com/questions/976208/how-do-i-enumerate-all-items-that-implement-a-generic-interface). It appears he already knows how to solve the problem I'm trying to figure out.) Edit: I renamed the title to "How can I keep track of... " rather than just "How can I enumerate..." because the original question sounded like I was more interested in examining the runtime environment, where as what I'm really interested in is compile-time book-keeping.
Create a singleton where you can register your classes with a pointer to a creator function. In the cpp files of the concrete classes you register each class. Something like this: ``` class Interface; typedef boost::function<Interface* ()> Creator; class InterfaceRegistration { typedef map<string, Creator> CreatorMap; public: InterfaceRegistration& instance() { static InterfaceRegistration interfaceRegistration; return interfaceRegistration; } bool registerInterface( const string& name, Creator creator ) { return (m_interfaces[name] = creator); } list<string> names() const { list<string> nameList; transform( m_interfaces.begin(), m_interfaces.end(), back_inserter(nameList) select1st<CreatorMap>::value_type>() ); } Interface* create(cosnt string& name ) const { const CreatorMap::const_iterator it = m_interfaces.find(name); if( it!=m_interfaces.end() && (*it) ) { return (*it)(); } // throw exception ... return 0; } private: CreatorMap m_interfaces; }; // in your concrete classes cpp files namespace { bool registerClassX = InterfaceRegistration::instance("ClassX", boost::lambda::new_ptr<ClassX>() ); } ClassX::ClassX() : Interface() { //.... } // in your concrete class Y cpp files namespace { bool registerClassY = InterfaceRegistration::instance("ClassY", boost::lambda::new_ptr<ClassY>() ); } ClassY::ClassY() : Interface() { //.... } ```
I vaguely remember doing something similar to this many years ago. Your option (2) is pretty much what I did. In that case it was a `std::map` of `std::string` to `std::typeinfo`. In each, .cpp file I registered the class like this: ``` static dummy = registerClass (typeid (MyNewClass)); ``` `registerClass` takes a `type_info` object and simply returns `true`. You have to initialize a variable to ensure that `registerClass` is called during startup time. Simply calling `registerClass` in the global namespace is an error. And making `dummy` static allow you to reuse the name across compilation units without a name collision.
How can I keep track of (enumerate) all classes that implement an interface
[ "", "c++", "class", "enumerate", "" ]
I have the following code used to get xml from a DataSet into a byte array using UTF-8 encoding: ``` private static byte[] fGetXmlBytes(DataTable lvDataTable) { XmlWriterSettings lvSettings = new XmlWriterSettings(); lvSettings.Encoding = Encoding.UTF8; lvSettings.NewLineHandling = NewLineHandling.Replace; lvSettings.NewLineChars = String.Empty; using(MemoryStream lvMemoryStream = new MemoryStream()) using (XmlWriter lvWriter = XmlWriter.Create(lvMemoryStream, lvSettings)) { lvDataTable.WriteXml(lvWriter, XmlWriteMode.IgnoreSchema); //Lines used during debugging //byte[] lvXmlBytes = lvMemoryStream.GetBuffer(); //String lsXml = Encoding.UTF8.GetString(lvXmlBytes, 0, lvXmlBytes.Length); return lvMemoryStream.GetBuffer(); } } ``` I want a byte array because I subsequently pass the data to compression and encryption routines that work on byte arrays. Problem is I end up with an extra character at the start of the xml. Instead of: ``` <?xml version="1.0" encoding="utf-8"?><etc.... ``` I get ``` .<?xml version="1.0" encoding="utf-8"?><etc.... ``` Does anyone know why the character is there? Is there a way to prevent the character being added? Or to easily strip it out? Colin
You will have to use an `Encoding` class that doesn't emit a preamble. The object returned by `Encoding.UTF8` will emit a preamble, but you can create your own `UTF8Encoding` that doesn't emit a preamble like this: ``` lvSettings.Encoding = new UTF8Encoding(false); ``` --- The UTF-8 preamble is the [UNICODE byte order mark](http://en.wikipedia.org/wiki/Byte_order_mark) (U+FEFF) encoded using UTF-8. The purpose of the UNICODE byte order mark is to indicate the endianness (byte order) of the 16-bit code units of the stream. If the initial bytes in the stream are `0xEF 0xFF` the stream is big endian; otherwise, if the initial bytes are `0xFF 0xEF` the stream is little endian. U+FEFF encoded using UTF-8 results in the bytes `0xEF 0xBB 0xBF` and somewhat ironically, because UTF-8 encodes into a sequence of 8-bit bytes, the byte order does no longer matter.
Preamble perhaps? Info here: <http://www.firstobject.com/dn_markutf8preamble.htm>
Why am I getting an extra character (a dot or bullet point) at the beginning of my byte array?
[ "", "c#", "xml", "" ]
I have a product definition that includes one feature I wrote and the org.eclipse.feature. When I build this product from eclipse, it completes successfully. However, when I try to use the Headless build, the compilation process fails as it complains that it cannot find classes included in org.eclipse.ui. One of these classes, for example, is PlatformUI. The build process thus fails. I've checked and the org.eclipse.ui is included in the org.eclipse.ui plugin. I've also tried to include this plugin explicitly in my custom feature, but to no avail. I've also tried removing one of these plugins with problems, but the next that used org.eclipse.ui failed. So it seems to be definitively a classpath issue of some sowrt. I've tried this headless build using version 3.3.2 of Eclipse.
The `org.eclipse.ui.PlatformUI` class is in the `org.eclipse.ui.workbench` plug-in. org.eclipse.ui.workbench is required and re-exported by org.eclipse.ui. The "`org.eclipse.ui`" package is a [split package](http://eclipsesource.com/blogs/2008/08/22/tip-split-packages-and-visibility/). If you are using Import-Package for this dependency, then you are only getting wired to one of the providers of the package. If you only need the classes from the ui.workbench, then you can add an attribute to your Import-Package statement: ``` Import-Package:org.eclipse.ui;ui.workbench=split ``` Or, you could just change to `Require-Bundle`
Did you check your `build.properties` file? Specifically the [`archivesFormat` section](http://help.eclipse.org/help33/topic/org.eclipse.pde.doc.user/guide/tasks/pde_controlling_output.htm) > The `archivesFormat` property allows specifying the output format (zip, tar, and folder) of the build on a configuration basis. > The format of the property is `<configuration> - <format>`, where configuration is the same value than the one specified in the configs property. if it specifies `linux,gtk,x86-folder` while you are trying to build with a `win32` installation, it will not work.
Why an Eclipse RCP product build can not find classes in org.eclipse.ui during headless build?
[ "", "java", "eclipse", "build", "rcp", "" ]
Does anybody know of any good libraries to convert a flat file to Java objects? I found [flatworm](http://javaconfessions.com/2009/04/writing-flat-files-in-java-with.html) but I am looking for alternatives.
**FFP - Flat file parsing library** <http://jffp.sourceforge.net/>
Quick update: flatworm has not been active for quite a while, there is a fork named BeanIO: <http://www.beanio.org/>
Converting Flat File to Java Objects
[ "", "java", "flat-file", "" ]
I am making a profile form in Django. There are a lot of optional extra profile fields but I would only like to show two at a time. How do I hide or remove the fields I do not want to show dynamically? Here is what I have so far: ``` class UserProfileForm(forms.ModelForm): extra_fields = ('field1', 'field2', 'field3') extra_field_total = 2 class Meta: model = UserProfile def __init__(self, *args, **kwargs): extra_field_count = 0 for key, field in self.base_fields.iteritems(): if key in self.extra_fields: if extra_field_count < self.extra_field_total: extra_field_count += 1 else: # do something here to hide or remove field super(UserProfileForm, self).__init__(*args, **kwargs) ```
I think I found my answer. First I tried: ``` field.widget = field.hidden_widget ``` which didn't work. The correct way happens to be: ``` field.widget = field.hidden_widget() ```
Can also use ``` def __init__(self, instance, *args, **kwargs): super(FormClass, self).__init__(instance=instance, *args, **kwargs) if instance and instance.item: del self.fields['field_for_item'] ```
How do you dynamically hide form fields in Django?
[ "", "python", "django", "django-forms", "" ]
I am developing a 2D grid based sim game. Progress is good. Been cracking out code for the last few days really well, and I've been having some issues today. I build two rooms, set the door position, and spawn a person. The person has the 2 room types that they must visit in order to be cured (It's a remake of Theme Hospital). I click the spawn button, Person moves onto the grid from off screen, and then when the spawn is finished, they get their first path to the first room, then second, and then back to the ending spawn point. When I say the spawn point, I mean the point off screen / off grid, when I say the ending spawn point, I mean the point where the person is when the spawn cycle is finished, and they are fully on screen / grid. The problem now comes, what to do with the "person" (which is an object in its own right), is finished with? Should I simple set a boolean so they are no longer "active" but data on them remains? I wasn't sure, so I tried to just remove them from the ArrayList of people objects they were being held in. I did this by assigning a number value to each person on creation which was the same as their new position in the ArrayList, and then when removing them, using that number. I know that in itself is floored, but I'm only testing with 1 person right now. If anyone can give me some help on that, fantastic! But I suppose that is more a sub question. When the person is to be removed, they are, and I check the size of the arraylist, and then I get the following error... "Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException" I did some researching and I understand this is to do with synchronisation of objects in different threads, but I'm not sure that I have more than one thread. I do have a single timer, and I don't think the people ArrayList is accessed elsewhere. Any Thoughts? Ideas? Suggestions? Comments on this? Thanks in advance! (I will soon post a video and update this question with a link to it)
Typically I give every person or entity or whatever a boolean field called isMarkedForDeletion. Then during the main loop, they will either be told to update(), or if they are marked for deletion their index will be **added to a deletion list**. Once you have the deletion list all populated, you can iterate through the deletion list and remove those objects from the main list. Alternatively you can just iterate backwards and pull from the tail end of the list. This may or may not explain your ConcurrentModificationException - I've never gotten them when working with ArrayList's before. However, I've gotten them from LinkedList's and it was precisely for the reason you described and had nothing to do with threads. The actual cause was using an Iterator. **The following will cause a ConcurrentModificationException:** ``` for (Iterator i = list.iterator(); i.hasNext();) { Person o = i.next(); o.update(); if (list.isMarkedForDeletion()) { list.remove(o); } } ``` This **will not cause an Exception:** ``` ArrayList deletedObjects = new ArrayList(); for (Iterator i = list.iterator(); i.hasNext();) { Person o = i.next(); o.update(); if (list.isMarkedForDeletion()) { deletedObjects.add(o); } } for (int i = 0; i < deletedObjects.size(); i++) { list.remove(deletedObjects.get(i)); } ``` Perhaps the simplest way to do it, **will not cause an Exception**: ``` for (int i = list.size()-1; i >= 0; i--) { Person o = list.get(i); if (o.isMarkedForDeletion()) { list.remove(i); } else { o.update(); } } ```
Just a wild guess due to the lack of any code excerpts, but most probably your rendering is iterating through the ArrayList on Swing's thread, while you another thread (the timer I guess?) tries to remove the person from the list. If that's the case, one way to go is to have Swing remove the person from the list (between two renderings) as: ``` // peopleArray and personInstance should be final Runnable removePersonTask = new Runnable() { public void run() { peopleArray.remove(personInstance). } }; SwingUtilities.invokeLater(removePersonTask). ```
Spawning and terminating a person in a sim game (in Java)
[ "", "java", "spawning", "" ]
How can I retrieve a hard disk's unique ID using Java+JNI on Linux, Windows and Mac?
You could use Java+JNA (<https://github.com/twall/jna/>), but then you'd have to figure out how to gather that information by using native libraries on each of the platforms you'd like to support. The benefit is that you wouldn't have to compile any C/C++ code for each of the platforms. If you decide to go with that option someone else might be able to tell you how to figure out the harddisk IDs on the different platforms using C/C++ code/libraries. AFAIK, on Linux you need to read something from /proc or /sys, on Windows I would look through MSDN and see what you could find that is usable in Visual Studio (C++) and for Mac someone else would have to fill in. Solaris/BSD should probably be supported too if you do it right. In fact, for most of the POSIX-compatible OSes out there I think you should be able to do it somewhat uniformly.
To sum it up: you can't do this with just Java
How can I retrieve a hard disk's unique ID using Java+JNI on Linux, Windows and Mac
[ "", "java", "hardware", "" ]
How can you iterate in the rows and columns of a **WPF DataGrid** like with a **Forms DataGridView in C#**? For example, if you have Forms DataGridView you can do something like this: ``` for(int i = 0; i < formsDataGrid1.Rows.Count; i++) { MessageBox.Show(formsDataGrid1.Rows[i].ToString()); for(int j = 0; j < formsDataGrid1.Columns.Count; j++) MessageBox.Show(formsDataGrid1.Rows[i].Cells[j].ToString()); } ``` Thank you for any help! ## \*\*Edit: The reason I want to do this is that the DataGrid will be used by a user to enter certain informations in the second column of the DataGrid. Also, this DataGrid has multiple rows and I want to able to get that data and update a database with it.
Typically, you don't do that : you access the underlying data source instead of the DataGrid itself. For instance, assuming the data source is an `IEnumerable<Foo>` : ``` foreach(Foo f in foos) { MessageBox.Show(f.Name); } ``` --- EDIT: You don't need to access explicitly a specific cell of the grid : if the grid is bound to a list of objects, the object's property will be automatically updated when the user edits the corresponding cell in the grid. Simple example with a list of contacts : ``` public class Contact { public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } } ... ObservableCollection<Contact> contacts = new ObservableCollection<Contact>(); dataGrid.ItemsSource = contacts; ... ```
dg is your XAML DataGrid x:Name ``` for (int i = 0; i < dg.Items.Count; i++) { DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(i); for (int j = 0; j < dg.Columns.Count; j++) { TextBlock cellContent = dg.Columns[j].GetCellContent(row) as TextBlock; Console.WriteLine(cellContent.Text); } } ```
WPF DataGrid: How do you iterate in a DataGrid to get rows and columns?
[ "", "c#", "wpf", "datagrid", "iteration", "wpftoolkit", "" ]
I have a textBox control that lets the user their email address/addresses. The use may enter email by supplying comma or in next line (new line). The task is to check whether the textBox contains **new line (\n)** character or **commas** then split the email addresses accordingly. I applied: **string[] emails = txtemailAddress.Text.Split('\n');** it splits the email addresses. **I need a single routine that should check whether the textBox contains ",' {or} '\n' and split the string based on the split character.If the *email address is invalid in format* it should throw exception as well.** Thanks in advance.
The string.Split method accepts an array of characters to split on: ``` // split on newline or comma txtemailAddress.Text.Split(new[]{'\n', ','}); ``` Regarding validating email addresses, this is one of those tasks that may seem simple at first glance, but that proves to be more of a challange than expected. [This has been dicussed here at SO before](https://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses).
it's not easy to write a parser to check if email is correct or not. for splitting you can pass array of chars to split by using it like ``` char[] delimiters = new char[] { ',', '\n' }; string[] emails = txtemailAddress.Text.Split(delimiters ); ```
C# -Windows App - Regular Expression Help
[ "", "c#", "" ]
Does anybody know how to click on a link in the WebBrowser control in a WinForms application and then have that link open in a new tab inside my TabControl? I've been searching for months, seen many tutorials/articles/code samples but it seems as though nobody has ever tried this in C# before. Any advice/samples are greatly appreciated. Thank you.
Based on your comments, I understand that you want to trap the "Open In New Window" action for the WebBrowser control, and override the default behavior to open in a new tab inside your application instead. To accomplish this reliably, you need to get at the NewWindow2 event, which exposes ppDisp (a settable pointer to the WebBrowser control that should open the new window). All of the other potential hacked together solutions (such as obtaining the last link selected by the user before the OpenWindow event) are not optimal and are bound to fail in corner cases. Luckily, there is a (relatively) simple way of accomplishing this while still using the System.Windows.Forms.WebBrowser control as a base. All you need to do is extend the WebBrowser and intercept the NewWindow2 event while providing public access to the ActiveX Instance (for passing into ppDisp in new tabs). This has been done before, and Mauricio Rojas has an excellent example with a complete working class "ExtendedWebBrowser": <http://blogs.artinsoft.net/mrojas/archive/2008/09/18/newwindow2-events-in-the-c-webbrowsercontrol.aspx> Once you have the ExtendedWebBrowser class, all you need to do is setup handlers for NewWindow2 and point ppDisp to a browser in a new tab. Here's an example that I put together: ``` private void InitializeBrowserEvents(ExtendedWebBrowser SourceBrowser) { SourceBrowser.NewWindow2 += new EventHandler<NewWindow2EventArgs>(SourceBrowser_NewWindow2); } void SourceBrowser_NewWindow2(object sender, NewWindow2EventArgs e) { TabPage NewTabPage = new TabPage() { Text = "Loading..." }; ExtendedWebBrowser NewTabBrowser = new ExtendedWebBrowser() { Parent = NewTabPage, Dock = DockStyle.Fill, Tag = NewTabPage }; e.PPDisp = NewTabBrowser.Application; InitializeBrowserEvents(NewTabBrowser); Tabs.TabPages.Add(NewTabPage); Tabs.SelectedTab = NewTabPage; } private void Form1_Load(object sender, EventArgs e) { InitializeBrowserEvents(InitialTabBrowser); } ``` (Assumes TabControl named "Tabs" and initial tab containing child control docked ExtendedWebBrowser named "InitialWebBrowser") Don't forget to unregister the events when the tabs are closed!
``` private Uri _MyUrl; System.Windows.Forms.WebBrowser browser = new System.Windows.Forms.WebBrowser(); browser.Navigating += new System.Windows.Forms.WebBrowserNavigatingEventHandler(browser_Navigating); void browser_Navigating(object sender, System.Windows.Forms.WebBrowserNavigatingEventArgs e) { _MyUrl = e.Url; e.Cancel; } ```
Open link in new TAB (WebBrowser Control)
[ "", "c#", ".net", "winforms", "webbrowser-control", "tabcontrol", "" ]
I need to able to block any and all connections to my pc from a specific IP address , i know this is possible with a firewall but i need to do this in c#. Any idea how (need code). Update : Its a generic C# app not asp.net , target platform is WinXp till Win7
Need more information... if you're talking socket communication, you can simply close the connection to a client as soon as it connects if the IP address is blocked, or process the Connection Request and evaluate there. **Edit:** Simplest way for you would probably just be to interact with Windows Firewall API... here's how: <http://www.shafqatahmed.com/2008/01/controlling-win.html>
Your question is unclear but I'll try to answer the best I can, within my understanding. 1. Do you want to control machines from connecting to any port on your machine? if so, you need to control the built-in windows firewall or find yourself a filter driver you can control. In order to write your own filter driver, you must leave the land of managed code, so I am guessing that's not an option. To learn how to control the firewall, here's a link: <http://www.shafqatahmed.com/2008/01/controlling-win.html> more on google. 2. Do you want to control remote machines from connection to a port on your machines that your application owns? You cannot do that either (see #1 above). However you can take action after the connection, and close the connection if you don't like the remote IP (check the remote endpoint's IP). two caveats with this approach: It doesn't save you from a DoS attack. You will need to be careful if you need ipv6 support (you can't just check the IPV4 address in that case) HTH
Blocking Connections By IP
[ "", "c#", ".net", "" ]
What [OSS](http://en.wikipedia.org/wiki/Open_source_software) (or free) tools are available for drafting a single source for documentation that can be used to generate manuals? Specifically, in the following formats: * HTML website * PDF document * Embedded (within an application; possibly HTML)1 * Text (optional) * Man pages (optional) Additional requirements: * Tool is suitable for technical writers (need not be WYSIWYG). * XML/SGML source * High quality PDF output (comparable to TeX) * Multi-platform **Expanded Requirement**1 The same command-line application is written in two languages (C and Java). Using XML to describe the command-line options (some of which are specific to one language or the other), it is straightforward to transform the XML into a Java class, or a C function, which writes help to standard output. This ensures that the help can be embedded into the binary without having to depend on external files. It appears AsciiDoc does not have this ability. Is there another option?
One that satisfies most of your requirements, that I've used before, is [AsciiDoc](http://www.methods.co.nz/asciidoc/). AsciiDoc isn't an XML source format though, instead it opts for a simple text format. It can output HTML and Docbook, which can be rendered into PDF or other formats. The source text is nearly good enough for plain text presentation, too. Another popular choice along the same lines is [reStructuredText](http://docutils.sourceforge.net/rst.html).
I've been considering evangelizing [DocBook](http://www.docbook.org/) as a replacement for Word in our engineering group. There are a number of toolchains available. The easiest for engineers is probably [DocBook XSL](http://docbook.sourceforge.net/release/xsl/current/doc/), [Apache FOP](http://xmlgraphics.apache.org/fop/), and either [Ant](http://ant.apache.org/) or [Make](http://www.gnu.org/software/make/). This is how I have been doing my DocBook stuff. If you are really into LaTeX, then you might want to check out [DBLaTeX](http://dblatex.sourceforge.net/) for a DocBook to LaTeX publishing environment. If you don't mind stepping outside of the free environments, then the [`<oXygen/>` XML Editor](http://www.oxygenxml.com/docbook_editor.html) offers a pretty nice WYSIWYG DocBook editor. I haven't used it that much, but it does look pretty promising.
Single source documentation tool
[ "", "java", "pdf-generation", "documentation-generation", "" ]
I am currently working on a pretty large application which contains a lot of forms. Up to this moment, I have always been writing my forms by hand and writing my own validation logic, but I have decided it was about time I started using Zend\_Form and it's built-in validation routines. However, I keep stumbling upon more and more problems concerning the (lack of) flexibility caused [`Zend_Form_Decorator`](http://framework.zend.com/manual/en/zend.form.decorators.html). Simple tasks like adding an extra button to a single input-element become incredibly difficult tasks. I have now reached a point where I am seriously considering dropping the [`Zend_Form_Element`](http://framework.zend.com/manual/en/zend.form.elements.html) + [`Zend_Form_Decorator`](http://framework.zend.com/manual/en/zend.form.decorators) approach entirely, but I do not want to lose the excellent validation options. **Basically, I want the best of both worlds:** * **Write forms the way the end-user sees them: *in plain HTML*** * **Easily add server-side validations to form fields without breaking too much of the ZF standard behaviour** A possible solution I am considering is writing the forms both on the server side as in the views. This would allow me to easily validate my own forms, but the (in my eyes quite big) downside is that each form should be defined twice, which just feels plain wrong. Are there any guidelines to do this? Have any of you experienced the same, and if so, how have you solved these issues? I'd very much like to hear your points of view.
I too find the default decorators to be a massive pain. I understand *why* they are the way they are, but I think the 'inconvenience factor' has been grossly underestimated. Anyway, I would recommend using [ViewScripts](http://framework.zend.com/manual/en/zend.form.standardDecorators.html#zend.form.standardDecorators.viewScript) for your forms. Note that these are not the same as Views -- instead, ViewScripts are referenced explicitly in your Form class, act as a "sub-view" of sorts and allow you to control the layout of each and every element. Examples how to use ViewScripts have been somewhat hard to find in the past, but I'll try to take a stab at providing something useful. First, override loadDefaultDecorators in your form class: ``` public function loadDefaultDecorators() { $this->setDecorators( array( array('ViewScript', array('viewScript' => 'foo/bar.phtml') ) ) ); } ``` This will reference a ViewScript named *bar.phtml* located in */views/scripts/foo*. Note the case-sensitive differences in "ViewScript" and "viewScript" above. Next, you'll have to tweak the decorators applied to each element to ensure it displays but without the annoying dt/dd wrappers. For instance: ``` $baz = new Zend_Form_Element_Text('bazInput'); $baz->setDecorators(array('ViewHelper','Errors')); ``` Finally, you'll need to build your ViewScript, such as: ``` <form method="post" action="<?php echo $this-element->getAction() ?>"> <table> <tr> <td><label for="bazInput">Baz:</label></td> <td><?php echo $this->element->bazInput ?></td> </tr> </table> <input type="submit" value="Submit Form" /> </form> ``` Obviously this is a very simple example, but it illustrates how to reference the form elements and form action. Then in your View, simply reference and output your form as usual. This way you can have much finer control over your form layouts -- to include easily adding Javascript. I believe this approach resolves both your requirements: you can build forms in plain HTML and still take advantage of the Zend Form validation mechanism.
I have been using as many Zend components as possible over the past 10 months, on a large project, and Zend\_Form has been the biggest pain in the \*\*\*. The forms are slow to render, and hard to make pretty. Don't even get me started on Sub-Forms. I saw an interesting article called "[scaling zend\_form](http://ishouldbecoding.com/2008/11/05/scaling-zend_form)" but it didn't seem to help much with render speed :( I am thinking about making all my forms using straight HTML in the view, and only using Zend\_Form to do the validation and filtering (not rendering). Either that, OR I will just use Zend\_Validate and Zend\_Filter, without the Form aspect at all. A tool is only a tool if it helps you. Otherwise, it's just a hindrance.
Zend Framework forms, decorators and validation: should I go back to plain HTML?
[ "", "php", "zend-framework", "zend-form", "decorator", "" ]
There is a table with Columns as below: ``` Id : long autoincrement; timestamp:long; price:long ``` Timestamp is given as a unix\_time in ms. Question: what is the average time difference between the records ?
In SQL Server, you could write something like that to get that information: ``` SELECT t1.ID, t2.ID, DATEDIFF(MILLISECOND, t2.PriceTime, test2.PriceTime) FROM table t1 INNER JOIN table t2 ON t2.ID = t1.ID-1 WHERE t1.ID > (SELECT MIN(ID) FROM table) ``` and if you're only interested in the AVG across all entries, you could use: ``` SELECT AVG(DATEDIFF(MILLISECOND, t2.PriceTime, test2.PriceTime)) FROM table t1 INNER JOIN table t2 ON t2.ID = t1.ID-1 WHERE t1.ID > (SELECT MIN(ID) FROM table) ``` Basically, you need to join the table with itself, and use "t1.ID = t2.ID-1" to associate item no. 2 in one table with item no. 1 in the other table and then calculate the time difference between the two. In order to avoid accessing item no. 0 which doesn't exist, use the "T1.ID > (SELECT MIN(ID) FROM table)" clause to start from the second item. Marc
First thought is a sub-query grabbing the record immediately previous: ``` SELECT timestamp - (select top 1 timestamp from Table T1 where T1.Id < Table.Id order by Id desc) FROM Table ``` Then you can take the average of that: ``` SELECT AVG(delta) from (SELECT timestamp - (select top 1 timestamp from Table T1 where T1.Id < Table.Id order by Id desc) as delta FROM Table) T ``` There will probably need to be some handling of the null that results for the first row, but I haven't tested to be sure.
SQL - Query to return result
[ "", "sql", "oracle", "" ]
I have a key/value pairs mapped by hash (ID) in `Dictionary<string, Dictionary<string, string>>` called id2key\_value. You can think of this as a way to represent database-like table with rows. I added some helper functions to ease the use of some basic datatypes by doing a cast, like ``` public int GetInt(string id, string key) { int value = 0; bool success = int.TryParse(map[id][key], out value); if (success) return value; else throw new InvalidOperationException( "Trying to obtain a non-integer value with GetInt()."); } ``` Well, I thought I was being clever when I came up with an idea of a "cast-cache", which basically holds already parsed objects, so I could skip the parsing of the string for int, bool, DateTime, etc., and simply cast them to appropriate datatype from the cache. Like, ``` public int GetInt(string id, string key) { if (cast_cache.ContainsKey(id) && cast_cache[id].ContainsKey(key)) return (int) cast_cache[id][key]; int value = 0; bool success = int.TryParse(map[id][key], out value); if (success) { this.AddToCache(id, key, value); return value; } else throw new InvalidOperationException( "Trying to obtain a non-integer value with GetInt()."); } ``` The "cast-cache" is simply `Dictionary<string, Dictionary<string, object>>`. So, I did some performance testing with 10000 ints added to the map. Then I did one million random retrieves, with and without "cast-caching". It took 495(ms) without caching and 490(ms) with caching. I also ran a test with DateTime, there the difference was more significant, but less than I expect (~750(ms) non-cached vs ~500(ms) cached). Not (obviously) understanding the principle of a cast, how costly this operation is and why the performance is so close to the one that "deserializes" from string?
Casting is much faster that most people seem to think since you are not touching the object itself (you are simply changing the reference that points to that object). One of the main reasons that you ought to avoid casting is that when you cast you are eschewing type-safety and introducing potential execution-time errors into your application. I would rarely consider casting to be a performance concern. As a side note I would make sure that you test both reference types and value types in your cache to make sure that you are not incurring a performance penalty due to the boxing and unboxing of any value types. The performance penalty of boxing comes from the fact that casting a value type to an object *does* involve more than changing a reference as the value type must be copied to the heap. Also the use of a boxed value type will unbox the reference type and subsequently copy those values from the heap to the stack again.
Hang on, what you're calling a "cast" in your code is not a cast. If you're doing this: ``` bool success = int.TryParse(map[id][key], out value); ``` That's a **conversion**, not a cast. A **cast** would be: ``` value = (int) map[id][key]; ``` or ``` value = map[id][key] as int; ``` Which would fail in this case because the object really is a string, not an int. If you have a `Dictionary<string, string>` but you are really interested in storing arbitrary objects in it, I would make it a `Dictionary<string, object>`. As a result you'll be able to use casts instead of conversions, which as Andrew Hare points out is going to be a lot faster.
The cost of casting?
[ "", "c#", "caching", "casting", "" ]
In order to save space and the complexity of having to maintain the consistency of data between different sources, I'm considering storing start/end indices for some substrings instead of storing the substrings themselves. The trick is that if I do so, it's possible I'll be creating slices ALL the time. Is this something to be avoided? Is the slice operator fast enough I don't need to worry? How about the new object creation/destruction overhead? --- Okay, I learned my lesson. Don't optimize unless there's a real problem you're trying to fix. (Of course this doesn't mean to right needlessly bad code, but that's beside the point...) Also, test and profile before coming to stack overflow. =D Thanks everyone!
1. Fast enough as opposed to what? How do you do it right now? What exactly are you storing, what exactly are you retrieving? The answer probably highly depends on this. Which brings us to ... 2. Measure! Don't discuss and analyze theoretically; try and measure what is the more performant way. Then decide whether the possible performance gain justifies refactoring your database. **Edit:** I just ran a test measuring string slicing versus lookup in a dict keyed on `(start, end)` tuples. It suggests that there's not much of a difference. It's a pretty naive test, though, so take it with a pinch of salt.
In a comment the OP mentions bloat "in the database" -- but no information regarding what database he's talking about; from the scant information in that comment it would seem that Python string slices aren't necessarily what's involved, rather, the "slicing" would be done by the DB engine upon retrieval. If that's the actual situation then I would recommend on general principles against storing redundant information in the DB -- a "normal form" (maybe in a lax sense of the expression;-) whereby information is stored just once and derived information is recomputed (or cached charge of the DB engine, etc;-) should be the norm, and "denormalization" by deliberately storing derived information very much the exception and only when justified by specific, well measured retrieval-performance needs. If the reference to "database" was a misdirection;-), or rather used in a lax sense as I did for "normal form" above;-), then another consideration may apply: since Python strings are immutable, it would seem to be natural to not have to do slices by copying, but rather have each slice reuse part of the memory space of the parent it's being sliced from (much as is done for numpy arrays' slices). However that's not currently part of the Python core. I did once try a patch to that purpose, but the problem of adding a reference to the big string and thus making it stay in memory just because a tiny substring thereof is still referenced loomed large for general-purpose adaptation. Still it would be possible to make a special purpose subclass of string (and one of unicode) for the case in which the big "parent" string needs to stay in memory anyway. Currently `buffer` does a tiny bit of that, but you can't call string methods on a buffer object (without explicitly copying it to a string object first), so it's only really useful for output and a few special cases... but there's no real conceptual block against adding string method (I doubt that would be adopted in the core, but it should be decently easy to maintain as a third party module anyway;-). The worth of such an approach can hardly be solidly proven by measurement, one way or another -- speed would be very similar to the current implicitly-copying approach; the advantage would come entirely in terms of reducing memory footprint, which wouldn't so much make any given Python code faster, but rather allow a certain program to execute on a machine with a bit less RAM, or multi-task better when several instances are being used at the same time in separate processes. See [rope](http://www.sgi.com/tech/stl/Rope.html) for a similar but richer approach once experimented with in the context of C++ (but note it didn't make it into the standard;-).
how fast is python's slice
[ "", "python", "optimization", "" ]
I'm looking to create a very -tiny- application(s) in Windows 7. I'm looking for a programming language like C# and a simple framework that * Makes the application very light weight * Doesn't require any libraries or modules (only the \*.exe and works on a newly installed Win7) * The IDE (Or the compiler) let me easily implement windows 7 features (like the menu, the graphics...) **The point**: I want to create a small application (light weight so it can be easily transported), that focus mainly on Windows 7 graphic design and features. I don't know if such IDE exists but also asking how will you solve it, mean if you have to create a tiny application (gadget like) how will you proceed?
* Lightweight and regarding dependencies: Well, since you want kind of C#, you have the .NET Framework. That's not exactly lightweight, unless you're sure that the target system has it available. Be sure to check which .NET version comes preinstalled with Seven. *Addendum: Now that 7 is out, it seems it comes preinstalled with .NET 3.5 SP1 (full framework, not client profile). That's a good thing.* * Have a look at the [Windows API Code Pack](http://code.msdn.microsoft.com/WindowsAPICodePack) for Windows 7 for access to Windows 7 features. Like tvanfosson, I'd also stick with Visual Studio and .NET.
Personally, I'd stick with Visual Studio. You might want to get a utility like [NuGenUnify](http://www.genetibase.com/cforce/nugenunify.php), which makes it easy to use ILMerge to combine any extra libraries into the main exe if you want to distribute as a single file.
Develop smart applications for Windows 7
[ "", "c#", "windows-7", "" ]
I feel a little silly for asking this since I seem to be the only person in the world who doesn't get it, but here goes anyway. I'm going to use Python as an example. When I use raw SQL queries (I usually use ORMs) I use parameterisation, like this example using SQLite: **Method A:** ``` username = "wayne" query_params = (username) cursor.execute("SELECT * FROM mytable WHERE user=?", query_params) ``` I know this works and I know this is the generally recommended way to do it. A SQL injection-vulnerable way to do the same thing would be something like this: **Method B:** ``` username = "wayne" cursor.execute("SELECT * FROM mytable WHERE user='%s'" % username) ``` As far I can tell I understand SQL injection, as explained in [this Wikipedia article](http://en.wikipedia.org/wiki/Sql_injection). My question is simply: How is method A really different to method B? Why is the end result of method A not the same as method B? I assume that the `cursor.execute()` method (part of Python's DB-API specification) takes care of correctly escaping and type-checking the input, but this is never explicitly stated anywhere. Is that all that parameterisation in this context is? To me, when we say "parameterisation", all that means is "string substitution", like %-formatting. Is that incorrect?
A parameterized query doesn't actually do string replacement. If you use string substitution, then the SQL engine actually sees a query that looks like ``` SELECT * FROM mytable WHERE user='wayne' ``` If you use a `?` parameter, then the SQL engine sees a query that looks like ``` SELECT * FROM mytable WHERE user=<some value> ``` Which means that before it even sees the string "wayne", it can fully parse the query and understand, generally, what the query does. It sticks "wayne" into its own representation of the query, not the SQL string that describes the query. Thus, SQL injection is impossible, since we've already passed the SQL stage of the process. (The above is generalized, but it more or less conveys the idea.)
When you do text replacement (like your method B), you have to be wary of quotes and such, because the server will get a single piece of text, and it have to determine where the value ends. With parameterized statements, OTOH, the DB server gets the statement as is, without the parameter. The value is sent to the server as a different piece of data, using a simple binary safe protocol. Therefore, your program doesn't have to put quotes around the value, and of course it doesn't matter if there were already quotes in the value itself. An analogy is about source and compiled code: in your method B, you're building the source code of a procedure, so you have to be sure to strictly follow the language syntax. With Method A, you first build and compile a procedure, then (immediately after, in your example), you call that procedure with your value as a parameter. And of course, in-memory values aren't subject to syntax limitations. Umm... that wasn't really an analogy, it's really what is happening under the hood (roughly).
How does SQL query parameterisation work?
[ "", "sql", "security", "sql-injection", "" ]
As far as I understand, there is no way to find out which exceptions a method throws without looking up the API docs one-by-one. Since that is no option, I'd like to reverse the research and ask you which are the most common Exceptions and RuntimeExceptions you've come across when dealing with: * Casting * Arrays * Vector, ArrayList, HashMap, etc. * IO (File class, streams, filters, ...) * Object Serialization * Threads (wait(), sleep(), etc.) * or anything else that is considered "basic Java" I realize that this might be subjective and boring but it is for a class test and I really don't know better.
Assume the below are `java.lang` unless I specify otherwise: * **Casting**: ClassCastException * **Arrays**: ArrayIndexOutOfBoundsException, NullPointerException * **Collections**: NullPointerException, ClassCastException (if you're not using autoboxing and you screw it up) * **IO**: java.io.IOException, java.io.FileNotFoundException, java.io.EOFException * **Serialization**: java.io.ObjectStreamException (AND ITS SUBCLASSES, which I'm too lazy to enumerate) * **Threads**: InterruptedException, SecurityException, IllegalThreadStateException * **Potentially common to all situations**: NullPointerException, IllegalArgumentException **You would do well to look at Java site's Package Summary pages.** Here's one: <https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/io/package-summary.html>
**Unchecked Exception List** ArrayIndexOutOfBoundsException ClassCastException IllegalArgumentException IllegalStateException NullPointerException NumberFormatException AssertionError ExceptionInInitializerError StackOverflowError NoClassDefFoundError **Checked Exception List** Exception IOException FileNotFoundException ParseException ClassNotFoundException CloneNotSupportedException InstantiationException InterruptedException NoSuchMethodException NoSuchFieldException
Most common checked and unchecked Java Exceptions?
[ "", "java", "exception", "" ]
In Java, updating double and long variable may not be atomic, as double/long are being treated as two separate 32 bits variables. <http://java.sun.com/docs/books/jls/second_edition/html/memory.doc.html#28733> In C++, if I am using 32 bit Intel Processor + Microsoft Visual C++ compiler, is updating double (8 byte) operation atomic? I cannot find much specification mention on this behavior. When I say "atomic variable", here is what I mean : Thread A trying to write 1 to variable x. Thread B trying to write 2 to variable x. We shall get value 1 or 2 out from variable x, but not an undefined value.
This is hardware specific and depends an the architecture. For x86 and x86\_64 8 byte writes or reads are guaranteed to be atomic, if they are aligned. Quoting from the Intel Architecture Memory Ordering White Paper: > Intel 64 memory ordering guarantees > that for each of the following > memory-access instructions, the > constituent memory operation appears > to execute as a single memory access > regardless of memory type: > > 1. Instructions that read or write a single byte. > 2. Instructions that read or write a word (2 bytes) whose address is > aligned on a 2 byte boundary. > 3. Instructions that read or write a doubleword (4 bytes) whose address is > aligned on a 4 byte boundary. > 4. Instructions that read or write a quadword (8 bytes) whose address is > aligned on an 8 byte boundary. > > All locked instructions (the implicitly > locked xchg instruction and other > read-modify-write instructions with a > lock prefix) are an indivisible and > uninterruptible sequence of load(s) > followed by store(s) regardless of > memory type and alignment.
It's safe to assume that updating a double is never atomic, even if it's size is the same as an int with atomic guarantee. The reason is that if has different processing path since it's a non-critical and expensive data type. For example even data barriers usually mention that they don't apply to floating point data/operations in general. Visual C++ will allign primitive types (see [article](http://msdn.microsoft.com/en-us/library/aa290049%28VS.71%29.aspx)) and while that should guarantee that it's bits won't get garbled while writing to memory (8 byte allignment is always in one 64 or 128 bit cache line) the rest depends on how CPU handles non-atomic data in it's cache and whether reading/flushing a cache line is interruptable. So if you dig through Intel docs for the kind of core you are using and it gives you that guarantee then you are safe to go. The reason why Java spec is so conservative is that it's supposed to run the same way on an old 386 and on Corei7. Which is of course delusional but a promise is a promise, therefore it promisses less :-) The reason I'm saying that you have to look up CPU doc is that your CPU might be an old 386, or alike :-)) Don't forget that on a 32-bit CPU your 8-byte block takes 2 "rounds" to access so you are down to the mercy of the mechanics of the cache access. Cache line flushing giving much higher data consistency guarantee applies only to a reasonably recent CPU with Intel-ian guarantee (automatic cache consistency).
Is Updating double operation atomic
[ "", "c++", "visual-c++", "" ]
I have a custom attribute that is being filled from a database. This attribute can contain an embedded single quote like this, ``` MYATT='Tony\'s Test' ``` At some pont in my code I use jquery to copy this attribute to a field like this, ``` $('#MY_DESC').val($(recdata).attr('MYATT')); ``` MY\_DESC is a text field in a dialog box. When I display the dialog box all I see in the field is **Tony\** What I need to see is, **Tony's Test** How can I fix this so I can see the entire string?
Try: ``` MYATT='Tony&#x27s Test' ``` I didn't bother verifying this with the HTML spec, but the [wikipedia](http://en.wikipedia.org/wiki/HTML) entry says: > `The ability to "escape" characters in this way allows for the characters < and & (when written as &lt; and &amp;, respectively) to be interpreted as character data, rather than markup. For example, a literal < normally indicates the start of a tag, and & normally indicates the start of a character entity reference or numeric character reference; writing it as &amp; or &#x26; or &#38; allows & to be included in the content of elements or the values of attributes. The double-quote character ("), when used to quote an attribute value, must also be escaped as &quot; or &#x22; or &#34; when it appears within the attribute value itself. The single-quote character ('), when used to quote an attribute value, must also be escaped as &#x27; or &#39; (should NOT be escaped as &apos; except in XHTML documents) when it appears within the attribute value itself. However, since document authors often overlook the need to escape these characters, browsers tend to be very forgiving, treating them as markup only when subsequent text appears to confirm that intent.`
In case you won't use double-quotes, put your custom attribute into them :) If not, I suggest escape the value.
Jquery embedded quote in attribute
[ "", "javascript", "jquery", "" ]
``` <ul class="bullets"> <li><a href="#">item 1</a></li> <li><a href="#">item 2</a></li> <li><a href="#">item 3</a></li> <li><a href="#">item 4</a></li> <li><a href="#">item 5</a></li> </ul> ``` When I click on the `<a>` element, i'd like to get it's parent `<li>`'s index number. I'm trying to create a carrousel type function that doesn't need item-n classes on the list items. ``` $(".bullets li a").click(function(){ var myIndex = $(this).parent().index(this); showPic(myIndex); }); ``` Thanks for any help. TD.
``` $(".bullets li a").click(function(){ var myIndex = $(this).parent().prevAll().length; showPic(myIndex); }); ``` --- Note: **`prevAll().length`** will give you a zero-based index; the first item will be 0 (zero).
`$(this).parent().index();` short and sweet Correction : this is not short and sweet from where this comes it should be like: ``` $(".bullets li a").click(function(){ var myIndex = $(this).parent().index(); console.log(myIndex); showPic(myIndex); }); ```
Get parent index with jQuery
[ "", "javascript", "jquery", "xhtml", "" ]
**what can I do on the reporting side, not the sql, or the c# part of the problem?** my query returns four rows, grouped by the field payment\_type, then puts the results into a datatable that's connected to my report in c#. What can I do on the report side to pull a specific row out of the datatable where payment\_type="Cash" without modifying any existing sql queries or creating any new datatables? the solution should be limited to working with the report editor only. modifying the sql query itself or creating a new datatable with the a subset of the data in my controller class cannot be part of the solution.
There happens to be a bunch of functions available in the reporting services related to aggregating, limiting and/or rendering results from the dataset in a report. Here's a good list of examples: <http://msdn.microsoft.com/en-us/library/ms157328.aspx#ReportFunctions> Here's my solution to the situation as well. ``` =FormatCurrency(Sum(IIF(Fields!pay_type.Value = "Cash", Fields!empCurBal.Value, 0.0))) ```
[DataTable.Select](http://msdn.microsoft.com/en-us/library/det4aw50.aspx) can take simple expressions like "columnname operator value": ``` DataRow[] rows = MyDataTable.Select("payment_type = 'Cash'"); if(rows.Length > 0) { DataRow rowYouWant = rows[0]; } ```
c# datatable is populated, need help printing particular data to a report
[ "", "c#", "reporting-services", "datatable", "" ]
Ok I have a generic interface ``` public IConfigurationValidator<T> { void Validate(); } ``` a class that implements it: ``` public class SMTPServerValidator : IConfigurationValidator<string> { public void Validate(string value) { if (string.IsNullOrEmpty(value)) { throw new Exception("Value cannot be null or empty"); } } } ``` I now want to use reflection to create an instance of SMTPServerValidator, because I know the AssemblyQualifiedName of the type. I was thinking to use Activator.CreateInstance and cast that to the interface... like this: ``` IConfigurationValidator<T> validator = (IConfigurationValidator<T>)Activator.CreateInstance(typeof(SMTPServerValidator)); ``` I dont know what T is....how do I use reflection to create an instance of this class? There is another class that has that I am dealing with that I left out: ``` public class ConfigurationSetting<T> { IConfigurationValidator<T> m_Validator; public ConfigurationSetting(IConfigurationValidator<T> validator) { m_Validator = validator; } public void Validate(T value) { m_Validator.Validate(value); } } ``` In the end I am trying to create ConfigurationSettings and need to pass in the appropriate validator based on the parameter.
Creating the instance of the class is easy - you've done that already with `Activator.CreateInstance`. If you don't know what `T` is, how are you hoping to *use* this as an implementation of the interface? I assume that in reality, the interface actually refers to `T` in the members. If it doesn't - or if you don't need those bits - then make it non-generic, or create a non-generic base interface which the base interface extends.
How about ``` Type lConfigValidatorType = typeof(IConfigurationValidator<>) Type lSomeOtherType = typeof(T) Type lConstructedType = lConfigValidatorType.MakeGenericType(lSomeOtherType); var lObject = Activator.CreateInstance(lConstructedType) ```
Creating an instance of a class that implements generic interface
[ "", "c#", ".net", "generics", "reflection", "" ]
Is there any code for a nice notice box (Even a dll would be fine) Like the one kaspersky antivirus shows? Because in my script I use a lot of message box and the end-user start to complain that they need to click okay every time.
You can look at this [exemple](http://www.codeproject.com/KB/miscctrl/taskbarnotifier.aspx) on CodeProject.
I suggest you create a custom control, which inherits from the message box and then you design it as per your liking.
c# a nice notice box
[ "", "c#", "messagebox", "notice", "" ]
let's say I have a matrix (array) like this example, but much larger: ``` 0 0 5 0 3 6 6 4 0 3 0 8 0 1 1 9 4 0 6 0 0 0 4 1 0 6 0 7 0 0 3 1 6 1 5 0 8 0 8 0 3 2 6 4 8 1 0 2 2 8 5 8 1 8 7 4 1 0 3 0 6 3 8 1 0 0 4 0 0 3 1 5 2 0 0 0 0 5 0 3 6 6 4 0 3 0 8 0 1 1 9 4 0 6 0 0 0 4 1 0 6 0 7 0 0 3 1 6 1 5 0 8 0 8 0 3 2 6 4 8 1 0 2 2 8 5 8 1 8 7 4 1 0 3 0 6 3 8 1 0 0 4 0 9 4 1 5 2 0 0 ``` I'm trying to determine the position of two equal numbers with greatest distance between them in the array in a diagonal, horizontal or vertical straight line, with the distance calculated as the count of numbers between them (distance d >= 0). Other Constraints: * The straight line as described above may not contain the same number that is marking its beginning and end, so you can't have **6** 0 4 5 **6** 1 7 3 5 **6** and say distance 6..6 is 8 as there is a 6 in the sequence. * The numbers to look for are not given but must be determined dynamically. In the example the result (considering the array as a regular X|Y coord system with 0, 0 in the lower left) it should determine P1(0, 8), P2(8, 0) with d = 7 (number: 9). Any good ideas on how to do this efficiently? I'm using C# but examples/ideas in other languages are appreciated too. In case you wonder where this question comes from, I've been thinking about various math related challenges that I believe are tough to solve (for myself) and hope to get a better handle on such problems by seeing how others solve such issues. Thank you!
**Algorithm:** Simplify the problem. It is equivalent to solving the 1-dimensional version (find largest gap between equal values in a list) once per row, column and diagonal then returning the maximum. Simplify more. The 1-dimensional version is pretty easy. You just build a Dictionary which maps values to a list of their positions, solve the trivial problem of 'what is the largest delta in this list of positions' for each value, and return the maximum. **Analysis:** The trivial problem takes linear time in the size of the position list (because the list is sorted [by the natural insertion order]). Therefore the 1-dim gap problem takes linear time in the size of the value list (because there is one position per value). Therefore the 2-dim gap problem takes linear time in the size of the matrix (because each value is included in exactly four 1-dim sub-problems). So if the matrix is n*m, the solution will take O(n*m) time. It requires O(n+m) space (to store the value->positions dictionary during each 1-dim phase). I really doubt you'll do better (the time is clearly optimal, not so sure about the size).
I don't see how you can do this really any faster besides just iterating through each row, each column, and each diagonal (you can tell if something's on the same diagonal by taking the absolute value of the difference of its X and Y coordinates, of course) and keeping track of the most recent coordinates of each number you see, and the greatest observed separation.
Greatest Distance between Equal Numbers in Array
[ "", "c#", "algorithm", "" ]
suppose, I need to perform a set of procedure on a particular website say, fill some forms, click submit button, send the data back to server, receive the response, again do something based on the response and send the data back to the server of the website. I know there is a webbrowser module in python, but I want to do this without invoking any web browser. It hast to be a pure script. Is there a module available in python, which can help me do that? thanks
You can also take a look at [mechanize](https://github.com/python-mechanize/mechanize). Its meant to handle *"stateful programmatic web browsing"* (as per their site).
selenium will do exactly what you want and it handles javascript
How to automate browsing using python?
[ "", "python", "browser-automation", "" ]