Search Results

Search found 676 results on 28 pages for 'dt'.

Page 5/28 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • GridView in ASP.NET 2.0

    - by Subho
    How can I populate an editable Grid with data from different tables from MSSQL Server'05 writing a code behind function??? I have used: Dim conn As New SqlConnection(conn_web) Dim objCmd As New SqlDataAdapter(sql, conn) Dim oDS As New DataSet objCmd.Fill(oDS, "TAB") Dim dt As DataTable = oDS.Tables(0) Dim rowCount As Integer = dt.Rows.Count Dim dr As DataRow = dt.NewRow() If rowCount = 0 Then e.DataSource = Nothing e.DataBind() e.Focus() Else e.DataSource = dt e.DataBind() End If

    Read the article

  • Python/Biomolecular Physics- Trying to code a simple stochastic simulation of a system exhibiting co

    - by user359597
    *edited 6/17/10 I'm trying to understand how to improve my code (make it more pythonic). Also, I'm interested in writing more intuitive 'conditionals' that would describe scenarios that are commonplace in biochemistry. The conditional criteria in the below program is explained in Answer #2, but I am not satisfied with it- it is correct, but isn't obvious and isn't easy to implement for more complicated conditional scenarios. Ideas welcome. Comments/criticisms welcome. First posting experience @ stackoverflow- please comment on etiquette if needed. The code generates a list of values that are the solution to the following exercise: "In a programming language of your choice, implement Gillespie’s First Reaction Algorithm to study the temporal behaviour of the reaction A---B in which the transition from A to B can only take place if another compound, C, is present, and where C dynamically interconverts with D, as modelled in the Petri-net below. Assume that there are 100 molecules of A, 1 of C, and no B or D present at the start of the reaction. Set kAB to 0.1 s-1 and both kCD and kDC to 1.0 s-1. Simulate the behaviour of the system over 100 s." def sim(): # Set the rate constants for all transitions kAB = 0.1 kCD = 1.0 kDC = 1.0 # Set up the initial state A = 100 B = 0 C = 1 D = 0 # Set the start and end times t = 0.0 tEnd = 100.0 print "Time\t", "Transition\t", "A\t", "B\t", "C\t", "D" # Compute the first interval transition, interval = transitionData(A, B, C, D, kAB, kCD, kDC) # Loop until the end time is exceded or no transition can fire any more while t <= tEnd and transition >= 0: print t, '\t', transition, '\t', A, '\t', B, '\t', C, '\t', D t += interval if transition == 0: A -= 1 B += 1 if transition == 1: C -= 1 D += 1 if transition == 2: C += 1 D -= 1 transition, interval = transitionData(A, B, C, D, kAB, kCD, kDC) def transitionData(A, B, C, D, kAB, kCD, kDC): """ Returns nTransition, the number of the firing transition (0: A->B, 1: C->D, 2: D->C), and interval, the interval between the time of the previous transition and that of the current one. """ RAB = kAB * A * C RCD = kCD * C RDC = kDC * D dt = [-1.0, -1.0, -1.0] if RAB > 0.0: dt[0] = -math.log(1.0 - random.random())/RAB if RCD > 0.0: dt[1] = -math.log(1.0 - random.random())/RCD if RDC > 0.0: dt[2] = -math.log(1.0 - random.random())/RDC interval = 1e36 transition = -1 for n in range(len(dt)): if dt[n] > 0.0 and dt[n] < interval: interval = dt[n] transition = n return transition, interval if __name__ == '__main__': sim()

    Read the article

  • How to add Items with value and display into comboboxes?

    - by hatem gamil
    hi all i have a combo box that have a datatable dt as datasource Code: dt = new DataTable(); dt = DAL.ExecuteProc("SP_GetCashiers"); CashierDDL.DataSource = dt; CashierDDL.DisplayMember = "Cashier_Name"; CashierDDL.ValueMember = "Id"; just like that ,,note::CashierDDL is my combobox i want to know how can add an item to my combobox with value to assign it to sqlParameter to send this parameter to another storedProc to get data based on seleted item from the combobox i am working with vs2008 ,,winforms thnx

    Read the article

  • What is the best WebControl to create this

    - by balexandre
    current output wanted output current code public partial class test : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) populateData(); } private void populateData() { List<temp> ls = new List<temp>(); ls.Add(new temp { a = "AAA", b = "aa", c = "a", dt = DateTime.Now }); ls.Add(new temp { a = "BBB", b = "bb", c = "b", dt = DateTime.Now }); ls.Add(new temp { a = "CCC", b = "cc", c = "c", dt = DateTime.Now.AddDays(1) }); ls.Add(new temp { a = "DDD", b = "dd", c = "d", dt = DateTime.Now.AddDays(1) }); ls.Add(new temp { a = "EEE", b = "ee", c = "e", dt = DateTime.Now.AddDays(2) }); ls.Add(new temp { a = "FFF", b = "ff", c = "f", dt = DateTime.Now.AddDays(2) }); TemplateField tc = (TemplateField)gv.Columns[0]; // <-- want to assign here just day gv.Columns.Add(tc); // <-- want to assign here just day + 1 gv.Columns.Add(tc); // <-- want to assign here just day + 2 gv.DataSource = ls; gv.DataBind(); } } public class temp { public temp() { } public string a { get; set; } public string b { get; set; } public string c { get; set; } public DateTime dt { get; set; } } and in HTML <asp:GridView ID="gv" runat="server" AutoGenerateColumns="false"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Eval("a") %>' Font-Bold="true" /><br /> <asp:Label ID="Label2" runat="server" Text='<%# Eval("b") %>' Font-Italic="true" /><br /> <asp:Label ID="Label3" runat="server" Text='<%# Eval("dt") %>' /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> What I'm trying to avoid is repeat code so I can only use one unique TemplateField I can accomplish this with 3 x GridView, one per each day, but I'm really trying to simplify code as the Grid will be exactly the same (as the HTML code goes), just the DataSource changes. Any help is greatly appreciated, Thank you.

    Read the article

  • How can I convert this column value to an integer?

    - by Kevin
    My C# code looks like this: myNum = dt.Columns[0]; myNum is an integer and dt is a datatable. The value in column 0 of dt is a string ("12"), but I'd like to convert it to an integer. How can I do this? I've tried: myNum = int.Parse(dt.Columns[0]); ...but that doesn't work. Any ideas?

    Read the article

  • A free standing ASP.NET Pager Web Control

    - by Rick Strahl
    Paging in ASP.NET has been relatively easy with stock controls supporting basic paging functionality. However, recently I built an MVC application and one of the things I ran into was that I HAD TO build manual paging support into a few of my pages. Dealing with list controls and rendering markup is easy enough, but doing paging is a little more involved. I ended up with a small but flexible component that can be dropped anywhere. As it turns out the task of creating a semi-generic Pager control for MVC was fairly easily. Now I’m back to working in Web Forms and thought to myself that the way I created the pager in MVC actually would also work in ASP.NET – in fact quite a bit easier since the whole thing can be conveniently wrapped up into an easily reusable control. A standalone pager would provider easier reuse in various pages and a more consistent pager display regardless of what kind of 'control’ the pager is associated with. Why a Pager Control? At first blush it might sound silly to create a new pager control – after all Web Forms has pretty decent paging support, doesn’t it? Well, sort of. Yes the GridView control has automatic paging built in and the ListView control has the related DataPager control. The built in ASP.NET paging has several issues though: Postback and JavaScript requirements If you look at paging links in ASP.NET they are always postback links with javascript:__doPostback() calls that go back to the server. While that works fine and actually has some benefit like the fact that paging saves changes to the page and post them back, it’s not very SEO friendly. Basically if you use javascript based navigation nosearch engine will follow the paging links which effectively cuts off list content on the first page. The DataPager control does support GET based links via the QueryStringParameter property, but the control is effectively tied to the ListView control (which is the only control that implements IPageableItemContainer). DataSource Controls required for Efficient Data Paging Retrieval The only way you can get paging to work efficiently where only the few records you display on the page are queried for and retrieved from the database you have to use a DataSource control - only the Linq and Entity DataSource controls  support this natively. While you can retrieve this data yourself manually, there’s no way to just assign the page number and render the pager based on this custom subset. Other than that default paging requires a full resultset for ASP.NET to filter the data and display only a subset which can be very resource intensive and wasteful if you’re dealing with largish resultsets (although I’m a firm believer in returning actually usable sets :-}). If you use your own business layer that doesn’t fit an ObjectDataSource you’re SOL. That’s a real shame too because with LINQ based querying it’s real easy to retrieve a subset of data that is just the data you want to display but the native Pager functionality doesn’t support just setting properties to display just the subset AFAIK. DataPager is not Free Standing The DataPager control is the closest thing to a decent Pager implementation that ASP.NET has, but alas it’s not a free standing component – it works off a related control and the only one that it effectively supports from the stock ASP.NET controls is the ListView control. This means you can’t use the same data pager formatting for a grid and a list view or vice versa and you’re always tied to the control. Paging Events In order to handle paging you have to deal with paging events. The events fire at specific time instances in the page pipeline and because of this you often have to handle data binding in a way to work around the paging events or else end up double binding your data sources based on paging. Yuk. Styling The GridView pager is a royal pain to beat into submission for styled rendering. The DataPager control has many more options and template layout and it renders somewhat cleaner, but it too is not exactly easy to get a decent display for. Not a Generic Solution The problem with the ASP.NET controls too is that it’s not generic. GridView, DataGrid use their own internal paging, ListView can use a DataPager and if you want to manually create data layout – well you’re on your own. IOW, depending on what you use you likely have very different looking Paging experiences. So, I figured I’ve struggled with this once too many and finally sat down and built a Pager control. The Pager Control My goal was to create a totally free standing control that has no dependencies on other controls and certainly no requirements for using DataSource controls. The idea is that you should be able to use this pager control without any sort of data requirements at all – you should just be able to set properties and be able to display a pager. The Pager control I ended up with has the following features: Completely free standing Pager control – no control or data dependencies Complete manual control – Pager can render without any data dependency Easy to use: Only need to set PageSize, ActivePage and TotalItems Supports optional filtering of IQueryable for efficient queries and Pager rendering Supports optional full set filtering of IEnumerable<T> and DataTable Page links are plain HTTP GET href Links Control automatically picks up Page links on the URL and assigns them (automatic page detection no page index changing events to hookup) Full CSS Styling support On the downside there’s no templating support for the control so the layout of the pager is relatively fixed. All elements however are stylable and there are options to control the text, and layout options such as whether to display first and last pages and the previous/next buttons and so on. To give you an idea what the pager looks like, here are two differently styled examples (all via CSS):   The markup for these two pagers looks like this: <ww:Pager runat="server" id="ItemPager" PageSize="5" PageLinkCssClass="gridpagerbutton" SelectedPageCssClass="gridpagerbutton-selected" PagesTextCssClass="gridpagertext" CssClass="gridpager" RenderContainerDiv="true" ContainerDivCssClass="gridpagercontainer" MaxPagesToDisplay="6" PagesText="Item Pages:" NextText="next" PreviousText="previous" /> <ww:Pager runat="server" id="ItemPager2" PageSize="5" RenderContainerDiv="true" MaxPagesToDisplay="6" /> The latter example uses default style settings so it there’s not much to set. The first example on the other hand explicitly assigns custom styles and overrides a few of the formatting options. Styling The styling is based on a number of CSS classes of which the the main pager, pagerbutton and pagerbutton-selected classes are the important ones. Other styles like pagerbutton-next/prev/first/last are based on the pagerbutton style. The default styling shown for the red outlined pager looks like this: .pagercontainer { margin: 20px 0; background: whitesmoke; padding: 5px; } .pager { float: right; font-size: 10pt; text-align: left; } .pagerbutton,.pagerbutton-selected,.pagertext { display: block; float: left; text-align: center; border: solid 2px maroon; min-width: 18px; margin-left: 3px; text-decoration: none; padding: 4px; } .pagerbutton-selected { font-size: 130%; font-weight: bold; color: maroon; border-width: 0px; background: khaki; } .pagerbutton-first { margin-right: 12px; } .pagerbutton-last,.pagerbutton-prev { margin-left: 12px; } .pagertext { border: none; margin-left: 30px; font-weight: bold; } .pagerbutton a { text-decoration: none; } .pagerbutton:hover { background-color: maroon; color: cornsilk; } .pagerbutton-prev { background-image: url(images/prev.png); background-position: 2px center; background-repeat: no-repeat; width: 35px; padding-left: 20px; } .pagerbutton-next { background-image: url(images/next.png); background-position: 40px center; background-repeat: no-repeat; width: 35px; padding-right: 20px; margin-right: 0px; } Yup that’s a lot of styling settings although not all of them are required. The key ones are pagerbutton, pager and pager selection. The others (which are implicitly created by the control based on the pagerbutton style) are for custom markup of the ‘special’ buttons. In my apps I tend to have two kinds of pages: Those that are associated with typical ‘grid’ displays that display purely tabular data and those that have a more looser list like layout. The two pagers shown above represent these two views and the pager and gridpager styles in my standard style sheet reflect these two styles. Configuring the Pager with Code Finally lets look at what it takes to hook up the pager. As mentioned in the highlights the Pager control is completely independent of other controls so if you just want to display a pager on its own it’s as simple as dropping the control and assigning the PageSize, ActivePage and either TotalPages or TotalItems. So for this markup: <ww:Pager runat="server" id="ItemPagerManual" PageSize="5" MaxPagesToDisplay="6" /> I can use code as simple as: ItemPagerManual.PageSize = 3; ItemPagerManual.ActivePage = 4;ItemPagerManual.TotalItems = 20; Note that ActivePage is not required - it will automatically use any Page=x query string value and assign it, although you can override it as I did above. TotalItems can be any value that you retrieve from a result set or manually assign as I did above. A more realistic scenario based on a LINQ to SQL IQueryable result is even easier. In this example, I have a UserControl that contains a ListView control that renders IQueryable data. I use a User Control here because there are different views the user can choose from with each view being a different user control. This incidentally also highlights one of the nice features of the pager: Because the pager is independent of the control I can put the pager on the host page instead of into each of the user controls. IOW, there’s only one Pager control, but there are potentially many user controls/listviews that hold the actual display data. The following code demonstrates how to use the Pager with an IQueryable that loads only the records it displays: protected voidPage_Load(objectsender, EventArgs e) {     Category = Request.Params["Category"] ?? string.Empty;     IQueryable<wws_Item> ItemList = ItemRepository.GetItemsByCategory(Category);     // Update the page and filter the list down     ItemList = ItemPager.FilterIQueryable<wws_Item>(ItemList); // Render user control with a list view Control ulItemList = LoadControl("~/usercontrols/" + App.Configuration.ItemListType + ".ascx"); ((IInventoryItemListControl)ulItemList).InventoryItemList = ItemList; phItemList.Controls.Add(ulItemList); // placeholder } The code uses a business object to retrieve Items by category as an IQueryable which means that the result is only an expression tree that hasn’t execute SQL yet and can be further filtered. I then pass this IQueryable to the FilterIQueryable() helper method of the control which does two main things: Filters the IQueryable to retrieve only the data displayed on the active page Sets the Totaltems property and calculates TotalPages on the Pager and that’s it! When the Pager renders it uses those values, plus the PageSize and ActivePage properties to render the Pager. In addition to IQueryable there are also filter methods for IEnumerable<T> and DataTable, but these versions just filter the data by removing rows/items from the entire already retrieved data. Output Generated and Paging Links The output generated creates pager links as plain href links. Here’s what the output looks like: <div id="ItemPager" class="pagercontainer"> <div class="pager"> <span class="pagertext">Pages: </span><a href="http://localhost/WestWindWebStore/itemlist.aspx?Page=1" class="pagerbutton" />1</a> <a href="http://localhost/WestWindWebStore/itemlist.aspx?Page=2" class="pagerbutton" />2</a> <a href="http://localhost/WestWindWebStore/itemlist.aspx?Page=3" class="pagerbutton" />3</a> <span class="pagerbutton-selected">4</span> <a href="http://localhost/WestWindWebStore/itemlist.aspx?Page=5" class="pagerbutton" />5</a> <a href="http://localhost/WestWindWebStore/itemlist.aspx?Page=6" class="pagerbutton" />6</a> <a href="http://localhost/WestWindWebStore/itemlist.aspx?Page=20" class="pagerbutton pagerbutton-last" />20</a>&nbsp;<a href="http://localhost/WestWindWebStore/itemlist.aspx?Page=3" class="pagerbutton pagerbutton-prev" />Prev</a>&nbsp;<a href="http://localhost/WestWindWebStore/itemlist.aspx?Page=5" class="pagerbutton pagerbutton-next" />Next</a></div> <br clear="all" /> </div> </div> The links point back to the current page and simply append a Page= page link into the page. When the page gets reloaded with the new page number the pager automatically detects the page number and automatically assigns the ActivePage property which results in the appropriate page to be displayed. The code shown in the previous section is all that’s needed to handle paging. Note that HTTP GET based paging is different than the Postback paging ASP.NET uses by default. Postback paging preserves modified page content when clicking on pager buttons, but this control will simply load a new page – no page preservation at this time. The advantage of not using Postback paging is that the URLs generated are plain HTML links that a search engine can follow where __doPostback() links are not. Pager with a Grid The pager also works in combination with grid controls so it’s easy to bypass the grid control’s paging features if desired. In the following example I use a gridView control and binds it to a DataTable result which is also filterable by the Pager control. The very basic plain vanilla ASP.NET grid markup looks like this: <div style="width: 600px; margin: 0 auto;padding: 20px; "> <asp:DataGrid runat="server" AutoGenerateColumns="True" ID="gdItems" CssClass="blackborder" style="width: 600px;"> <AlternatingItemStyle CssClass="gridalternate" /> <HeaderStyle CssClass="gridheader" /> </asp:DataGrid> <ww:Pager runat="server" ID="Pager" CssClass="gridpager" ContainerDivCssClass="gridpagercontainer" PageLinkCssClass="gridpagerbutton" SelectedPageCssClass="gridpagerbutton-selected" PageSize="8" RenderContainerDiv="true" MaxPagesToDisplay="6" /> </div> and looks like this when rendered: using custom set of CSS styles. The code behind for this code is also very simple: protected void Page_Load(object sender, EventArgs e) { string category = Request.Params["category"] ?? ""; busItem itemRep = WebStoreFactory.GetItem(); var items = itemRep.GetItemsByCategory(category) .Select(itm => new {Sku = itm.Sku, Description = itm.Description}); // run query into a DataTable for demonstration DataTable dt = itemRep.Converter.ToDataTable(items,"TItems"); // Remove all items not on the current page dt = Pager.FilterDataTable(dt,0); // bind and display gdItems.DataSource = dt; gdItems.DataBind(); } A little contrived I suppose since the list could already be bound from the list of elements, but this is to demonstrate that you can also bind against a DataTable if your business layer returns those. Unfortunately there’s no way to filter a DataReader as it’s a one way forward only reader and the reader is required by the DataSource to perform the bindings.  However, you can still use a DataReader as long as your business logic filters the data prior to rendering and provides a total item count (most likely as a second query). Control Creation The control itself is a pretty brute force ASP.NET control. Nothing clever about this other than some basic rendering logic and some simple calculations and update routines to determine which buttons need to be shown. You can take a look at the full code from the West Wind Web Toolkit’s Repository (note there are a few dependencies). To give you an idea how the control works here is the Render() method: /// <summary> /// overridden to handle custom pager rendering for runtime and design time /// </summary> /// <param name="writer"></param> protected override void Render(HtmlTextWriter writer) { base.Render(writer); if (TotalPages == 0 && TotalItems > 0) TotalPages = CalculateTotalPagesFromTotalItems(); if (DesignMode) TotalPages = 10; // don't render pager if there's only one page if (TotalPages < 2) return; if (RenderContainerDiv) { if (!string.IsNullOrEmpty(ContainerDivCssClass)) writer.AddAttribute("class", ContainerDivCssClass); writer.RenderBeginTag("div"); } // main pager wrapper writer.WriteBeginTag("div"); writer.AddAttribute("id", this.ClientID); if (!string.IsNullOrEmpty(CssClass)) writer.WriteAttribute("class", this.CssClass); writer.Write(HtmlTextWriter.TagRightChar + "\r\n"); // Pages Text writer.WriteBeginTag("span"); if (!string.IsNullOrEmpty(PagesTextCssClass)) writer.WriteAttribute("class", PagesTextCssClass); writer.Write(HtmlTextWriter.TagRightChar); writer.Write(this.PagesText); writer.WriteEndTag("span"); // if the base url is empty use the current URL FixupBaseUrl(); // set _startPage and _endPage ConfigurePagesToRender(); // write out first page link if (ShowFirstAndLastPageLinks && _startPage != 1) { writer.WriteBeginTag("a"); string pageUrl = StringUtils.SetUrlEncodedKey(BaseUrl, QueryStringPageField, (1).ToString()); writer.WriteAttribute("href", pageUrl); if (!string.IsNullOrEmpty(PageLinkCssClass)) writer.WriteAttribute("class", PageLinkCssClass + " " + PageLinkCssClass + "-first"); writer.Write(HtmlTextWriter.SelfClosingTagEnd); writer.Write("1"); writer.WriteEndTag("a"); writer.Write("&nbsp;"); } // write out all the page links for (int i = _startPage; i < _endPage + 1; i++) { if (i == ActivePage) { writer.WriteBeginTag("span"); if (!string.IsNullOrEmpty(SelectedPageCssClass)) writer.WriteAttribute("class", SelectedPageCssClass); writer.Write(HtmlTextWriter.TagRightChar); writer.Write(i.ToString()); writer.WriteEndTag("span"); } else { writer.WriteBeginTag("a"); string pageUrl = StringUtils.SetUrlEncodedKey(BaseUrl, QueryStringPageField, i.ToString()).TrimEnd('&'); writer.WriteAttribute("href", pageUrl); if (!string.IsNullOrEmpty(PageLinkCssClass)) writer.WriteAttribute("class", PageLinkCssClass); writer.Write(HtmlTextWriter.SelfClosingTagEnd); writer.Write(i.ToString()); writer.WriteEndTag("a"); } writer.Write("\r\n"); } // write out last page link if (ShowFirstAndLastPageLinks && _endPage < TotalPages) { writer.WriteBeginTag("a"); string pageUrl = StringUtils.SetUrlEncodedKey(BaseUrl, QueryStringPageField, TotalPages.ToString()); writer.WriteAttribute("href", pageUrl); if (!string.IsNullOrEmpty(PageLinkCssClass)) writer.WriteAttribute("class", PageLinkCssClass + " " + PageLinkCssClass + "-last"); writer.Write(HtmlTextWriter.SelfClosingTagEnd); writer.Write(TotalPages.ToString()); writer.WriteEndTag("a"); } // Previous link if (ShowPreviousNextLinks && !string.IsNullOrEmpty(PreviousText) && ActivePage > 1) { writer.Write("&nbsp;"); writer.WriteBeginTag("a"); string pageUrl = StringUtils.SetUrlEncodedKey(BaseUrl, QueryStringPageField, (ActivePage - 1).ToString()); writer.WriteAttribute("href", pageUrl); if (!string.IsNullOrEmpty(PageLinkCssClass)) writer.WriteAttribute("class", PageLinkCssClass + " " + PageLinkCssClass + "-prev"); writer.Write(HtmlTextWriter.SelfClosingTagEnd); writer.Write(PreviousText); writer.WriteEndTag("a"); } // Next link if (ShowPreviousNextLinks && !string.IsNullOrEmpty(NextText) && ActivePage < TotalPages) { writer.Write("&nbsp;"); writer.WriteBeginTag("a"); string pageUrl = StringUtils.SetUrlEncodedKey(BaseUrl, QueryStringPageField, (ActivePage + 1).ToString()); writer.WriteAttribute("href", pageUrl); if (!string.IsNullOrEmpty(PageLinkCssClass)) writer.WriteAttribute("class", PageLinkCssClass + " " + PageLinkCssClass + "-next"); writer.Write(HtmlTextWriter.SelfClosingTagEnd); writer.Write(NextText); writer.WriteEndTag("a"); } writer.WriteEndTag("div"); if (RenderContainerDiv) { if (RenderContainerDivBreak) writer.Write("<br clear=\"all\" />\r\n"); writer.WriteEndTag("div"); } } As I said pretty much brute force rendering based on the control’s property settings of which there are quite a few: You can also see the pager in the designer above. unfortunately the VS designer (both 2010 and 2008) fails to render the float: left CSS styles properly and starts wrapping after margins are applied in the special buttons. Not a big deal since VS does at least respect the spacing (the floated elements overlay). Then again I’m not using the designer anyway :-}. Filtering Data What makes the Pager easy to use is the filter methods built into the control. While this functionality is clearly not the most politically correct design choice as it violates separation of concerns, it’s very useful for typical pager operation. While I actually have filter methods that do something similar in my business layer, having it exposed on the control makes the control a lot more useful for typical databinding scenarios. Of course these methods are optional – if you have a business layer that can provide filtered page queries for you can use that instead and assign the TotalItems property manually. There are three filter method types available for IQueryable, IEnumerable and for DataTable which tend to be the most common use cases in my apps old and new. The IQueryable version is pretty simple as it can simply rely on on .Skip() and .Take() with LINQ: /// <summary> /// <summary> /// Queries the database for the ActivePage applied manually /// or from the Request["page"] variable. This routine /// figures out and sets TotalPages, ActivePage and /// returns a filtered subset IQueryable that contains /// only the items from the ActivePage. /// </summary> /// <param name="query"></param> /// <param name="activePage"> /// The page you want to display. Sets the ActivePage property when passed. /// Pass 0 or smaller to use ActivePage setting. /// </param> /// <returns></returns> public IQueryable<T> FilterIQueryable<T>(IQueryable<T> query, int activePage) where T : class, new() { ActivePage = activePage < 1 ? ActivePage : activePage; if (ActivePage < 1) ActivePage = 1; TotalItems = query.Count(); if (TotalItems <= PageSize) { ActivePage = 1; TotalPages = 1; return query; } int skip = ActivePage - 1; if (skip > 0) query = query.Skip(skip * PageSize); _TotalPages = CalculateTotalPagesFromTotalItems(); return query.Take(PageSize); } The IEnumerable<T> version simply  converts the IEnumerable to an IQuerable and calls back into this method for filtering. The DataTable version requires a little more work to manually parse and filter records (I didn’t want to add the Linq DataSetExtensions assembly just for this): /// <summary> /// Filters a data table for an ActivePage. /// /// Note: Modifies the data set permanently by remove DataRows /// </summary> /// <param name="dt">Full result DataTable</param> /// <param name="activePage">Page to display. 0 to use ActivePage property </param> /// <returns></returns> public DataTable FilterDataTable(DataTable dt, int activePage) { ActivePage = activePage < 1 ? ActivePage : activePage; if (ActivePage < 1) ActivePage = 1; TotalItems = dt.Rows.Count; if (TotalItems <= PageSize) { ActivePage = 1; TotalPages = 1; return dt; } int skip = ActivePage - 1; if (skip > 0) { for (int i = 0; i < skip * PageSize; i++ ) dt.Rows.RemoveAt(0); } while(dt.Rows.Count > PageSize) dt.Rows.RemoveAt(PageSize); return dt; } Using the Pager Control The pager as it is is a first cut I built a couple of weeks ago and since then have been tweaking a little as part of an internal project I’m working on. I’ve replaced a bunch of pagers on various older pages with this pager without any issues and have what now feels like a more consistent user interface where paging looks and feels the same across different controls. As a bonus I’m only loading the data from the database that I need to display a single page. With the preset class tags applied too adding a pager is now as easy as dropping the control and adding the style sheet for styling to be consistent – no fuss, no muss. Schweet. Hopefully some of you may find this as useful as I have or at least as a baseline to build ontop of… Resources The Pager is part of the West Wind Web & Ajax Toolkit Pager.cs Source Code (some toolkit dependencies) Westwind.css base stylesheet with .pager and .gridpager styles Pager Example Page © Rick Strahl, West Wind Technologies, 2005-2010Posted in ASP.NET  

    Read the article

  • Stochastic calculus library in python

    - by LeMiz
    Hello, I am looking for a python library that would allow me to compute stochastic calculus stuff, like the (conditional) expectation of a random process I would define the diffusion. I had a look a at simpy (simpy.sourceforge.net), but it does not seem to cover my needs. This is for quick prototyping and experimentation. In java, I used with some success the (now inactive) http://martingale.berlios.de/Martingale.html library. The problem is not difficult in itself, but there is a lot non trivial, boilerplate things to do (efficient memory use, variable reduction techniques, and so on). Ideally, I would be able to write something like this (just illustrative): def my_diffusion(t, dt, past_values, world, **kwargs): W1, W2 = world.correlated_brownians_pair(correlation=kwargs['rho']) X = past_values[-1] sigma_1 = kwargs['sigma1'] sigma_2 = kwargs['sigma2'] dX = kwargs['mu'] * X * dt + sigma_1 * W1 * X * math.sqrt(dt) + sigma_2 * W2 * X * X * math.sqrt(dt) return X + dX X = RandomProcess(diffusion=my_diffusion, x0 = 1.0) print X.expectancy(T=252, dt = 1./252., N_simul= 50000, world=World(random_generator='sobol'), sigma1 = 0.3, sigma2 = 0.01, rho=-0.1) Does someone knows of something else than reimplementing it in numpy for example ?

    Read the article

  • Physics System ignores collision in some rare cases

    - by Gajoo
    I've been developing a simple physics engine for my game. since the game physics is very simple I've decided to increase accuracy a little bit. Instead of formal integration methods like fourier or RK4, I'm directly computing the results after delta time "dt". based on the very first laws of physics : dx = 0.5 * a * dt^2 + v0 * dt dv = a * dt where a is acceleration and v0 is object's previous velocity. Also to handle collisions I've used a method which is somehow different from those I've seen so far. I'm detecting all the collision in the given time frame, stepping the world forward to the nearest collision, resolving it and again check for possible collisions. As I said the world consist of very simple objects, so I'm not loosing any performance due to multiple collision checking. First I'm checking if the ball collides with any walls around it (which is working perfectly) and then I'm checking if it collides with the edges of the walls (yellow points in the picture). the algorithm seems to work without any problem except some rare cases, in which the collision with points are ignored. I've tested everything and all the variables seem to be what they should but after leaving the system work for a minute or two the system the ball passes through one of those points. Here is collision portion of my code, hopefully one of you guys can give me a hint where to look for a potential bug! void PhysicalWorld::checkForPointCollision(Vec2 acceleration, PhysicsComponent& ball, Vec2& collisionNormal, float& collisionTime, Vec2 target) { // this function checks if there will be any collision between a circle and a point // ball contains informations about the circle (it's current velocity, position and radius) // collisionNormal is an output variable // collisionTime is also an output varialbe // target is the point I want to check for collisions Vec2 V = ball.mVelocity; Vec2 A = acceleration; Vec2 P = ball.mPosition - target; float wallWidth = mMap->getWallWidth() / (mMap->getWallWidth() + mMap->getHallWidth()) / 2; float r = ball.mRadius / (mMap->getWallWidth() + mMap->getHallWidth()); // r is ball radius scaled to match actual rendered object. if (A.any()) // todo : I need to first correctly solve the collisions in case there is no acceleration return; if (V.any()) // if object is not moving there will be no collisions! { float D = P.x * V.y - P.y * V.x; float Delta = r*r*V.length2() - D*D; if(Delta < eps) return; Delta = sqrt(Delta); float sgnvy = V.y > 0 ? 1: (V.y < 0?-1:0); Vec2 c1(( D*V.y+sgnvy*V.x*Delta) / V.length2(), (-D*V.x+fabs(V.y)*Delta) / V.length2()); Vec2 c2(( D*V.y-sgnvy*V.x*Delta) / V.length2(), (-D*V.x-fabs(V.y)*Delta) / V.length2()); float t1 = (c1.x - P.x) / V.x; float t2 = (c2.x - P.x) / V.x; if(t1 > eps && t1 <= collisionTime) { collisionTime = t1; collisionNormal = c1; } if(t2 > eps && t2 <= collisionTime) { collisionTime = t2; collisionNormal = c2; } } } // this function should step the world forward by dt. it doesn't check for collision of any two balls (components) // it just checks if there is a collision between the current component and 4 points forming a rectangle around it. void PhysicalWorld::step(float dt) { for (unsigned i=0;i<mObjects.size();i++) { PhysicsComponent &current = *mObjects[i]; Vec2 acceleration = current.mForces * current.mInvMass; float rt=dt; // stores how much more the world should advance while(rt > eps) { float collisionTime = rt; Vec2 collisionNormal = Vec2(0,0); float halfWallWidth = mMap->getWallWidth() / (mMap->getWallWidth() + mMap->getHallWidth()) / 2; // we check if there is any collision with any of those 4 points around the ball // if there is a collision both collisionNormal and collisionTime variables will change // after these functions collisionTime will be exactly the value of nearest collision (if any) // and if there was, collisionNormal will report in which direction the ball should return. checkForPointCollision(acceleration,current,collisionNormal,collisionTime,Vec2(floor(current.mPosition.x) + halfWallWidth,floor(current.mPosition.y) + halfWallWidth)); checkForPointCollision(acceleration,current,collisionNormal,collisionTime,Vec2(floor(current.mPosition.x) + halfWallWidth, ceil(current.mPosition.y) - halfWallWidth)); checkForPointCollision(acceleration,current,collisionNormal,collisionTime,Vec2( ceil(current.mPosition.x) - halfWallWidth,floor(current.mPosition.y) + halfWallWidth)); checkForPointCollision(acceleration,current,collisionNormal,collisionTime,Vec2( ceil(current.mPosition.x) - halfWallWidth, ceil(current.mPosition.y) - halfWallWidth)); // either if there is a collision or if there is not we step the forward since we are sure there will be no collision before collisionTime current.mPosition += collisionTime * (collisionTime * acceleration * 0.5 + current.mVelocity); current.mVelocity += collisionTime * acceleration; // if the ball collided with anything collisionNormal should be at least none zero in one of it's axis if (collisionNormal.any()) { collisionNormal *= Dot(collisionNormal, current.mVelocity) / collisionNormal.length2(); current.mVelocity -= 2 * collisionNormal; // simply reverse velocity along collision normal direction } rt -= collisionTime; } // reset all forces for current object so it'll be ready for later game event current.mForces.zero(); } }

    Read the article

  • I want to get 2 values returned by my query. How to do, using linq-to-entity

    - by Shantanu Gupta
    var dept_list = (from map in DtMapGuestDepartment.AsEnumerable() where map.Field<Nullable<long>>("GUEST_ID") == DRowGuestPI.Field<Nullable<long>>("PK_GUEST_ID") join dept in DtDepartment.AsEnumerable() on map.Field<Nullable<long>>("DEPARTMENT_ID") equals dept.Field<Nullable<long>>("DEPARTMENT_ID") select new { dept_id=dept.Field<long>("DEPARTMENT_ID") ,dept_name=dept.Field<long>("DEPARTMENT_NAME") }).Distinct(); DataTable dt = new DataTable(); dt.Columns.Add("DEPARTMENT_ID"); dt.Columns.Add("DEPARTMENT_NAME"); foreach (long? dept_ in dept_list) { dt.Rows.Add(dept_[0], dept_[1]); } EDIT In the previous question asked by me. I got an answer like this for single value. What is the difference between the two ? foreach (long? dept in dept_list) { dt.Rows.Add(dept); }

    Read the article

  • Would I really want to return the minimum date?

    - by Clay Shannon
    An old work colleague used to quote his father about tools, "You have to be smarter than it." In the code below, Resharper is telling me, "Value assigned is not used in any execution path" (pointing to the first line). If I accept its offer of help, dt is not assigned a value ("today"). Is this a case where "I have to be smarter than it" and ignore their warning, or is this a case where the tool is smarter than me, and I'm just not understanding it? My take on the situation is that if the if statement fails, the current date is returned (the default value I want), but if I acquiesce to Resharper's "demands" it would return the default value for Datetime, which is the minimum date, which I assume is something like 7/4/1776 or 1/1/0000 or so. DateTime dt = DateTime.Now; if (!(DateTime.TryParse(substr, out dt))) { using (var dtpDlgForm = new ReturnDate("Please select the Date that the file was created:")) { if (dtpDlgForm.ShowDialog() == DialogResult.OK) { dt = dtpDlgForm.ReturnVal; } } } return dt;

    Read the article

  • insert a date in mysql database

    - by kawtousse
    I use a jquery datepicker then i read it in my servlet like that: String dateimput=request.getParameter("datepicker");//1 then parse it like that: System.out.println("datepicker:" +dateimput); DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); java.util.Date dt = null; try { dt = df.parse(dateimput); System.out.println("date imput parssé1 est:" +dt); System.out.println("date imput parsée2 est:" +df.format(dt)); } catch (ParseException e) { e.printStackTrace(); } and insert query like that: String query = "Insert into dailytimesheet(trackingDate,activity,projectCode) values ("+df.format(dt)+", \""+activity+"\" ,\""+projet+"\")"; it pass successfully untill now but if i check the record inserted i found the date: 01/01/0001 00:00:00 l've tried to fix it but it still a mess for me.

    Read the article

  • How to input test data using the DecisionTree module in python?

    - by lifera1n
    On the Python DescisionTree module homepage (DecisionTree-1.6.1), they give a piece of example code. Here it is: dt = DecisionTree( training_datafile = "training.dat", debug1 = 1 ) dt.get_training_data() dt.show_training_data() root_node = dt.construct_decision_tree_classifier() root_node.display_decision_tree(" ") test_sample = ['exercising=>never', 'smoking=>heavy', 'fatIntake=>heavy', 'videoAddiction=>heavy'] classification = dt.classify(root_node, test_sample) print "Classification: ", classification My question is: How can I specify sample data (test_sample here) from variables? On the project homepage, it says: "You classify new data by first constructing a new data vector:" I have searched around but have been unable to find out what a data vector is or the answer to my question. Any help would be appreciated!

    Read the article

  • anonymous type and multiple properties

    - by ognjenb
    I have this error: An anonymous type cannot have multiple properties with the same name. Whether this can be resolved with alias ie, whether an alias exists in LINQ var device_query = from d in DevicesEntities.device join dt in DevicesEntities.devicetype on d.DeviceTypeId equals dt.Id join l in DevicesEntities.location on d.Id equals l.DeviceId join loc in DevicesEntities.locationname on l.LocationNameId equals loc.Id where l.DeviceId == d.Id select new { d.Id, d.DeviceTypeId, d.SerialNumber, d.FirmwareRev, d.ProductionDate, d.ReparationDate, d.DateOfLastCalibration, d.DateOfLastCalibrationCheck, d.CalCertificateFile, d.Notes, d.TestReportFile, d.WarrantyFile, d.CertificateOfOriginFile, d.QCPermissionFile, d.Reserved, d.ReservedFor, d.Weight, d.Price, d.SoftwareVersion, dt.Name, dt.ArticleNumber, dt.Type, l.StartDate, //AS LastStartDate, l.LocationNameId, loc.Name //in this line I have problem };

    Read the article

  • Using a parser to locate faulty code

    - by ryan.riverside
    Lately I've been working a lot in PHP and have run into an abnormally large number of parsing errors. I realize these are my own fault and a result of sloppy initial coding on my part, but it's getting to the point that I'm spending more time resolving tags than developing. In the interest of not slamming my productivity, are there any tricks to locating the problem in the code? What I'd really be looking for would be a line to put in the code which would output the entire faulty tag in the parsing error, or something similar. Purely for reference sake, my current error is Parse error: syntax error, unexpected '}' in /home/content/80/9480880/html/cache/tpl_prosilver_viewtopic_body.html.php on line 50 (which refers to this): </dd><dd><?php if ($_poll_option_val['POLL_OPTION_RESULT'] == 0) { echo ((isset($this->_rootref['L_NO_VOTES'])) ? $this->_rootref['L_NO_VOTES'] : ((isset($user->lang['NO_VOTES'])) ? $user->lang['NO_VOTES'] : '{ NO_VOTES }')); } else { echo $_poll_option_val['POLL_OPTION_PERCENT']; } ?></dd> </dl> <?php }} if ($this->_rootref['S_DISPLAY_RESULTS']) { ?> <dl> <dt>&nbsp;</dt> <dd class="resultbar"><?php echo ((isset($this->_rootref['L_TOTAL_VOTES'])) ? $this->_rootref['L_TOTAL_VOTES'] : ((isset($user->lang['TOTAL_VOTES'])) ? $user->lang['TOTAL_VOTES'] : '{ TOTAL_VOTES }')); ?> : <?php echo (isset($this->_rootref['TOTAL_VOTES'])) ? $this->_rootref['TOTAL_VOTES'] : ''; ?></dd> </dl> <?php } if ($this->_rootref['S_CAN_VOTE']) { ?> <dl style="border-top: none;"> <dt>&nbsp;</dt> <dd class="resultbar"><input type="submit" name="update" value="<?php echo ((isset($this->_rootref['L_SUBMIT_VOTE'])) ? $this->_rootref['L_SUBMIT_VOTE'] : ((isset($user->lang['SUBMIT_VOTE'])) ? $user->lang['SUBMIT_VOTE'] : '{ SUBMIT_VOTE }')); ?>" class="button1" /></dd> </dl> <?php } if (! $this->_rootref['S_DISPLAY_RESULTS']) { ?> <dl style="border-top: none;"> <dt>&nbsp;</dt> <dd class="resultbar"><a href="<?php echo (isset($this->_rootref['U_VIEW_RESULTS'])) ? $this->_rootref['U_VIEW_RESULTS'] : ''; ?>"><?php echo ((isset($this->_rootref['L_VIEW_RESULTS'])) ? $this->_rootref['L_VIEW_RESULTS'] : ((isset($user->lang['VIEW_RESULTS'])) ? $user->lang['VIEW_RESULTS'] : '{ VIEW_RESULTS }')); ?></a></dd> </dl> <?php } ?> </fieldset></div>

    Read the article

  • DATEFROMPARTS

    - by jamiet
    I recently overheard a remark by Greg Low in which he said something akin to "the most interesting parts of a new SQL Server release are the myriad of small things that are in there that make a developer's life easier" (I'm paraphrasing because I can't remember the actual quote but it was something like that). The new DATEFROMPARTS function is a classic example of that . It simply takes three integer parameters and builds a date out of them (if you have used DateSerial in Reporting Services then you'll understand). Take the following code which generates the first and last day of some given years: SELECT 2008 AS Yr INTO #Years UNION ALL SELECT 2009 UNION ALL SELECT 2010 UNION ALL SELECT 2011 UNION ALL SELECT 2012SELECT [FirstDayOfYear] = CONVERT(DATE,CONVERT(CHAR(8),((y.[Yr] * 10000) + 101))),      [LastDayOfYear] = CONVERT(DATE,CONVERT(CHAR(8),((y.[Yr] * 10000) + 1231)))FROM   #Years y here are the results: That code is pretty gnarly though with those CONVERTs in there and, worse, if the character string is constructed in a certain way then it could fail due to localisation, check this out: SET LANGUAGE french;SELECT dt,Month_Name=DATENAME(mm,dt)FROM   (       SELECT  dt = CONVERT(DATETIME,CONVERT(CHAR(4),y.[Yr]) + N'-01-02')       FROM    #Years y       )d;SET LANGUAGE us_english;SELECT dt,Month_Name=DATENAME(mm,dt)FROM   (       SELECT  dt = CONVERT(DATETIME,CONVERT(CHAR(4),y.[Yr]) + N'-01-02')       FROM    #Years y       )d; Notice how the datetime has been converted differently based on the language setting. When French, the string "2012-01-02" gets interpreted as 1st February whereas when us_english the same string is interpreted as 2nd January. Instead of all this CONVERTing nastiness we have DATEFROMPARTS: SELECT [FirstDayOfYear] = DATEFROMPARTS(y.[Yr],1,1),    [LasttDayOfYear] = DATEFROMPARTS(y.[Yr],12,31)FROM   #Years y How much nicer is that? The bad news of course is that you have to upgrade to SQL Server 2012 or migrate to SQL Azure if you want to use it, as is the way of the world! Don't forget that if you want to try this code out on SQL Azure right this second, for free, you can do so by connecting up to AdventureWorks On Azure. You don't even need to have SSMS handy - a browser that runs Silverlight will do just fine. Simply head to https://mhknbn2kdz.database.windows.net/ and use the following credentials: Database AdventureWorks2012 User sqlfamily Password sqlf@m1ly One caveat, SELECT INTO doesn't work on SQL Azure so you'll have to use this instead: DECLARE @y TABLE ( [Yr] INT);INSERT @y([Yr])SELECT 2008 AS Yr UNION ALL SELECT 2009 UNION ALL SELECT 2010 UNION ALL SELECT 2011 UNION ALL SELECT 2012;SELECT [FirstDayOfYear] = DATEFROMPARTS(y.[Yr],1,1),      [LastDayOfYear] = DATEFROMPARTS(y.[Yr],12,31)FROM @y y;SELECT [FirstDayOfYear] = CONVERT(DATE,CONVERT(CHAR(8),((y.[Yr] * 10000) + 101))),      [LastDayOfYear] = CONVERT(DATE,CONVERT(CHAR(8),((y.[Yr] * 10000) + 1231)))FROM @y y; @Jamiet

    Read the article

  • Is jQuery.parseJSON able to process all valid json?

    - by murze
    This piece of valid json (it has been generated using php's json_encode): {"html":"form is NOT valid<form id=\"articleform\" enctype=\"application\/x-www-form-urlencoded\" method=\"post\" action=\"\"><dl class=\"zend_form\">\n<dt id=\"title-label\">&nbsp;<\/dt>\n<dd id=\"title-element\">\n<input type=\"text\" name=\"title\" id=\"title\" value=\"Artikel K\"><\/dd>\n<dt id=\"articleFormSubmitted-label\">&nbsp;<\/dt>\n<dd id=\"articleFormSubmitted-element\">\n<input type=\"hidden\" name=\"articleFormSubmitted\" value=\"1\" id=\"articleFormSubmitted\"><\/dd>\n<dt id=\"submit-label\">&nbsp;<\/dt><dd id=\"submit-element\">\n<input type=\"submit\" name=\"submit\" id=\"submit\" value=\"Bewaar artikel\" onclick=\"this.value='Bezig...';\"><\/dd><\/dl><\/form><script type=\"text\/javascript\">\n\t $(\"#articleform\").submit(function(){\n $.post(\"\/admin\/ajax\/contenttree\/node\/9\/ajaxtarget\/ajaxContainer\", $(\"#articleform\").serialize(), function(html){$(\"#ajaxContainer\").html(html);} );\n\t\t return false;\n\t });\n\n <\/script>","newNodeName":""} is giving jQuery.parseJSON(data) and me a hard time. With this piece of code: alert('start'); alert(data); jQuery.parseJSON(data) alert('stop'); I get a message start and then the data (jsonstring above) is shown. The message "stop" never appears. When I use this json: {"html":"test","newNodeName":""} I've verified that my first big chick of json is valid. Why isn't it processed by jQuery.parseJSON Are there any special characters that don't go well with json?

    Read the article

  • Simple first-child js?

    - by Glister
    Searching for a simple first-child detection via javascript (no framework). It should add some class for the first child of the element. Like a css-hacks for ie, but in javascript and for a html file. Must work similar to :first-child When I say no framework, I mean some code like this: <script type="text/javascript">document.documentElement.id = "js"</script> For example: <div class="terms"> <dl> <dt>Term 1 name</dt> <dd>Term 1 description</dd> </dl> <dl> <dt>Term 2 name</dt> <dd>Term 2 description</dd> </dl> <dl> <dt>Term 3 name</dt> <dd>Term 3 description</dd> </dl> </div> Three <dl>, the first one includes Term 1. This css won't work in IE6, thats why I'm searching for a javascript solution. CSS-hacks are not allowed. .terms dl:first-child { float: right; }

    Read the article

  • Parent CSS (jQuery)

    - by Glister
    There is <dl> with padding-top <dl style="padding-top: 150px;"> <dt>text</dt> <dd><img width="150" height="150" src="..." /></dd> <dt>text 2</dt> <dd><img width="150" height="250" src="..." /></dd> <dt>text 3</dt> <dd><img width="150" height="350" src="..." /></dd> </dl> The difference between images - height. Trying to write a script, which will change a height of the <dl>, when <dd> is clicked. Height should be taken from the height attribute of the dd img. Tryed this, but it doesn't work: $("#posters dd").click(function(){ var parent_padding = $(this).find("img").attr("height"); $(this).parent().css({"padding-top":parent_padding}); }); Thanks.

    Read the article

  • Java: Match tokens between two strings and return the number of matched tokens

    - by Cryssie
    Need some help to find the number of matched tokens between two strings. I have a list of string stored in ArrayList (example given below): Line 0 : WRB VBD NN VB IN CC RB VBP NNP Line 1 : WDT NNS VBD DT NN NNP NNP Line 2 : WRB MD PRP VB DT NN IN NNS POS JJ NNS Line 3 : WDT NN VBZ DT NN IN DT JJ NN IN DT NNP Line 4 : WP VBZ DT JJ NN IN NN Here, you can see each string consists of a bunch of tokens separated by spaces. So, there's three things I need to work with.. Compare the first token (WRB) in Line 0 to the tokens in Line 1 to see if they match. Move on to the next tokens in Line 0 until a match is found. If there's a match, mark the matched tokens in Line 1 so that it will not be matched again. Return the number of matched tokens between Line 0 and Line 1. Return the distance of the matched tokens. Example: token NN is found on position 3 on line 0 and position 5 on Line 1. Distance = |3-5| = 2 I've tried using split string and store it to String[] but String[] is fixed and doesn't allow shrinking or adding of new elements. Tried Pattern Matcher but with disasterous results. Tried a few other methods but there's some problems with my nested for loops..(will post part of my coding if it will help). Any advice or pointers on how to solve this problem this would be very much appreciated. Thank you very much.

    Read the article

  • CommandBuilder and SqlTransaction to insert/update a row

    - by Jesse
    I can get this to work, but I feel as though I'm not doing it properly. The first time this runs, it works as intended, and a new row is inserted where "thisField" contains "doesntExist" However, if I run it a subsequent time, I get a run-time error that I can't insert a duplicate key as it violate the primary key "thisField". static void Main(string[] args) { using(var sqlConn = new SqlConnection(connString) ) { sqlConn.Open(); var dt = new DataTable(); var sqlda = new SqlDataAdapter("SELECT * FROM table WHERE thisField ='doesntExist'", sqlConn); sqlda.Fill(dt); DataRow dr = dt.NewRow(); dr["thisField"] = "doesntExist"; //Primary key dt.Rows.Add(dr); //dt.AcceptChanges(); //I thought this may fix the problem. It didn't. var sqlTrans = sqlConn.BeginTransaction(); try { sqlda.SelectCommand = new SqlCommand("SELECT * FROM table WITH (HOLDLOCK, ROWLOCK) WHERE thisField = 'doesntExist'", sqlConn, sqlTrans); SqlCommandBuilder sqlCb = new SqlCommandBuilder(sqlda); sqlda.InsertCommand = sqlCb.GetInsertCommand(); sqlda.InsertCommand.Transaction = sqlTrans; sqlda.DeleteCommand = sqlCb.GetDeleteCommand(); sqlda.DeleteCommand.Transaction = sqlTrans; sqlda.UpdateCommand = sqlCb.GetUpdateCommand(); sqlda.UpdateCommand.Transaction = sqlTrans; sqlda.Update(dt); sqlTrans.Commit(); } catch (Exception) { //... } } } Even when I can get that working through trial and error of moving AcceptChanges around, or encapsulating changes within Begin/EndEdit, then I begin to experience a "Concurrency violation" in which it won't update the changes, but rather tell me it failed to update 0 of 1 affected rows. Is there something crazy obvious I'm missing?

    Read the article

  • Selecting first instance of class but not nested instances via jQuery

    - by DA
    Given the following hypothetical markup: <ul class="monkey"> <li> <p class="horse"></p> <p class="cow"></p> </li> </ul> <dl class="monkey"> <dt class="horse"></dt> <dd class="cow"> <dl> <dt></dt> <dd></dd> </dl> <dl class="monkey"> <dt class="horse"></dt> <dd class="cow"></dd> </dl> </dd> </dl> I want to be able to grab the 'first level' of horse and cow classes within each monkey class. But I don't want the NESTED horse and cow classes. I started with .children, but that won't work with the UL example as they aren't direct children of .monkey. I can use find: $('.monkey').find('.horse, .cow') but that returns all instances, including the nested ones. I can filter the find: $('.monkey').find('.horse, .cow').not('.cow .horse, .cow .cow') but that prevents me from selecting nested instances on a second function call. So...I guess what I'm looking for is 'find first "level" of this descendant'. I could likely do this with some looping logic, but was wondering if there is a selector and/or some combo of selectors that would achieve that logic.

    Read the article

  • HTTP Handler error when downloading files - SSL

    - by Chiefy
    Ok big problem as this is affecting two projects on our new server. We have a file that is downloaded by users, the files are downloaded using a HTTPHandler. Since moving the site to the server and setting SSL the downloads have stopped working and we get an error message "Unable to download DownloadDocument.ashx" from site". DownloadDocument.ashx is the handler page that is set in the web.config and the button that goes there is a hyperlink with the id of the document as a querystring. Ive read the article on http://support.microsoft.com/kb/316431 and read a few other requests on this site but nothing seems to be working. This problem only happens in IE and works fine when I run it on the server in http instead of https. public override void HandleRequest(HttpContext context) { Guid guid = new Guid(context.Request.QueryString["ID"]); DataTable dt = Documents.GetDocument(guid); if (dt != null) { context.Response.Cache.SetCacheability(HttpCacheability.Private); context.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", dt.Rows[0]["DocumentName"].ToString())); context.Response.AddHeader("Content-Transfer-Encoding", "binary"); context.Response.AddHeader("Content-Length", ((byte[])dt.Rows[0]["Document"]).Length.ToString()); context.Response.ContentType = string.Format("application/{0}", dt.Rows[0]["Extension"].ToString().Remove(0, 1)); context.Response.Buffer = true; context.Response.BinaryWrite((byte[])dt.Rows[0]["Document"]); context.Response.Flush(); context.Response.End(); } } The above is my current code for the request. Ive used the base handler on http://haacked.com/archive/2005/03/17/AnAbstractBoilerplateHttpHandler.aspx. Any ideas on what this might be and how we can fix it. Thanks in advance for all responses.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >