Search Results

Search found 9542 results on 382 pages for 'row'.

Page 15/382 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • PHP while loop, table row

    - by Elliott
    Hi, I'm trying to loop through a database and output data into a div, if there are 3 divs horizontally accross it will the start a new tr until it reaches another 3 etc. It is currently outputted like : [] [] [] [] [] [] Currently I have it working when it reaches 3 it starts a new row, but I don't know how I can only echo a new tr once? As it creates a new table row each time. echo '<table><tr>'; while ($result) { $i ++; if ($i&3) { echo '<td> <div>Row Data</div> </td>'; } else { echo '<tr> <td> <div>Row Data</div> </td></tr>'; } } echo '</tr></table>'; The $result variable is the recordset from my sql query, everything works fine I just don't know how to only create a new table row once? Thanks

    Read the article

  • Delete duplicate rows, do not preserve one row

    - by Radley
    I need a query that goes through each entry in a database, checks if a single value is duplicated elsewhere in the database, and if it is - deletes both entries (or all, if more than two). Problem is the entries are URLs, up to 255 characters, with no way of identifying the row. Some existing answers on Stackoverflow do not work for me due to performance limitations, or they use uniqueid which obviously won't work when dealing with a string. Long Version: I have two databases containing URLs (and only URLs). One database has around 3,000 urls and the other around 1,000. However, a large majority of the 1,000 urls were taken from the 3,000 url database. I need to merge the 1,000 into the 3,000 as new entries only. For this, I made a third database with combined URLs from both tables, about 4,000 entries. I need to find all duplicate entries in this database and delete them (Both of them, without leaving either). I have followed the query of a few examples on this site, but whenever I try to delete both entries it ends up deleting all the entries, or giving sql errors. Alternatively: I have two databases, each containing the separate database. I need to check each row from one database against the other to find any that aren't duplicates, and then add those to a third database. Edit: I've got my own PHP solution which is pretty hacky, but works. I cannot answer my own question for 8 hours because I'm new, so here it is for now: I went with a PHP script to accomplish this, as I'm more familiar with PHP than MySQL. This generates a simple list of urls that only exist in the target database, but not both. If you have more than 7,000 entries to parse this may take awhile, and you will need to copy/paste the results into a text file or expand the script to store them back into a database. I'm just doing it manually to save time. Note: Uses MeekroDB <pre> <?php require('meekrodb.2.1.class.php'); DB::$user = 'root'; DB::$password = ''; DB::$dbName = 'testdb'; $all = DB::query('SELECT * FROM old_urls LIMIT 7000'); foreach($all as $row) { $test = DB::query('SELECT url FROM new_urls WHERE url=%s', $row['url']); if (!is_array($test)) { echo $row['url'] . "\n"; }else{ if (count($test) == 0) { echo $row['url'] . "\n"; } } } ?> </pre>

    Read the article

  • sql - getting the id from a row based on a group by

    - by user85116
    Table A tableAID tableBID grade Table B tableBID name description Table A links to Table b from the tableBID found in both tables. If I want to find the row in Table A, which has the highest grade, for each row in Table B, I would write my query like this: select max(grade) from TableA group by tableBID However, I don't just want the grade, I want the grade plus id of that row.

    Read the article

  • Know the row with max characters (C)

    - by l_core
    I have wrote a program in C, to find the row with the max number of characters. Here is the code #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> int main (int argc, char *argv[]) { char c; /* used to store the character with getc */ int c_tot = 0, c_rig = 0, c_max = 0; /* counters of characters*/ int r_tot = 0; /* counters of rows */ FILE *fptr; fptr = fopen(argv[1], "r"); if (fptr == NULL || argc != 2) { printf ("Error opening the file %s\n'", argv[1]); exit(EXIT_FAILURE); } while ( (c = getc(fptr)) != EOF) { if (c != ' ' && c != '\n') { c_tot++; c_rig++; } if (c == '\n') { r_tot++; if (c_rig > c_max) c_max = c_rig; c_rig = 0; } } printf ("Total rows: %d\n", r_tot); printf ("Total characters: %d\n", c_tot); printf ("Total characters in a row: %d\n", c_max); printf ("Average number of characters on a row: %d\n", (c_tot/r_tot)); printf ("The row with max characters is: %s\n", ??????) return 0; } I can easily find the row with the highest number of characters but how can i print that out? Thank You Folks

    Read the article

  • Fetching Cassandra row keys

    - by knorv
    Assume a Cassandra datastore with 20 rows, with row keys named "r1" .. "r20". Questions: How do I fetch the row keys of the first ten rows (r1 to r10)? How do I fetch the row keys of the next ten rows (r11 to r20)? I'm looking for the Cassandra analogy to: SELECT row_key FROM table LIMIT 0, 10; SELECT row_key FROM table LIMIT 10, 10;

    Read the article

  • MySql php: check if Row exists

    - by Jeff
    This is probably an easy thing to do but I'm an amateur and things just aren't working for me. I just want to check and see if a row exists where the $lectureName shows. If a row does exist with the $lectureName somewhere in it, I want the function to return "assigned" if not then it should return "available". Here's what I have. I'm fairly sure its a mess. Please help. function checkLectureStatus($lectureName) { $con = connectvar(); mysql_select_db("mydatabase", $con); $result = mysql_query("SELECT * FROM preditors_assigned WHERE lecture_name='$lectureName'"); while($row = mysql_fetch_array($result)); { if (!$row[$lectureName] == $lectureName) { mysql_close($con); return "Available"; } else { mysql_close($con); return "Assigned"; } } When I do this everything return available, even when it should return assigned.

    Read the article

  • C#: Select row from DataGridView

    - by Bi
    Hi I have a form with a DataGridView (of 3 columns) and a Button. Every time the user clicks on a button, I want the get the values stored in the 1st column of that row. Here is the code I have: private void myButton_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in ProductsGrid.Rows) { if (this.ProductsGrid.SelectedRows.Count == 1) { // get information of 1st column from the row string value = this.ProductsGrid.SelectedRows[0].Cells[0].ToString(); } } } However when I click on myButton, the this.ProductsGrid.SelectedRows.Count is 0. Also, how do I ensure that the user selects only one row and not multiple rows? Does this code look right?

    Read the article

  • Left Join only returning one row

    - by Adam
    I am trying to join two tables. I would like all the columns from the product_category table (there are a total of 6 now) and count the number of products, CatCount, that are in each category from the products_has_product_category table. My query result is 1 row with the first category and a total count of 68, when I am looking for 6 rows with each individual category's count. <?php $result = mysql_query(" SELECT a.*, COUNT(b.category_id) AS CatCount FROM `product_category` a LEFT JOIN `products_has_product_category` b ON a.product_category_id = b.category_id "); while($row = mysql_fetch_array($result)) { echo ' <li class="ui-shadow" data-count-theme="d"> <a href="' . $row['product_category_ref_page'] . '.php" data-icon="arrow-r" data-iconpos="right">' . $row['product_category_name'] . '</a><span class="ui-li-count">' . $row['CatCount'] . '</span></li>'; } ?> I have been working on this for a couple of hours and would really appreciate any help on what I am doing wrong.

    Read the article

  • Getting id of row just inserted into MySQL database

    - by James P
    I have my table columns set like this: likes(id, like_message, timestamp) id is the primary key that is auto incrementing. This is the SQL that I use to add a row: $sql = "INSERT INTO `likes` (like_message, timestamp) VALUES ('$likeMsg', $timeStamp)"; Everything works, but now I need to throw back the id attribute of the newly inserted row. For example, if I insert a row and the id of that row is 13, I need to echo out 13 so my AJAX request can pick that up and use it. Any help would be appreciated, as well as related code samples. Thanks :)

    Read the article

  • objectAtIndex:indexPath.row method always causes exception in IOS

    - by kalkin
    Hi I always seem to get exception when I use objectAtInded method to retrieve NSString from an array. I am reading data from a dictionary which is in the "PropertyList.plist" file.My code is - (void)viewDidLoad { [super viewDidLoad]; NSString *path = [[NSBundle mainBundle] pathForResource:@"PropertyList" ofType:@"plist"]; names = [[NSDictionary alloc] initWithContentsOfFile:path]; keys = [[[names allKeys] sortedArrayUsingSelector: @selector(compare:)] retain]; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSUInteger section = [indexPath section]; NSUInteger row = [indexPath row]; NSString *key = [keys objectAtIndex:section]; NSArray *nameSection = [names objectForKey:key]; static NSString *SectionsTableIdentifier = @"SectionsTableIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier]; if(cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SectionsTableIdentifier] autorelease]; } cell.textLabel.text = [nameSection objectAtIndex:row]; return cell; } The exception happens on the method "cellForRowAtIndexPath" in the line cell.textLabel.text = [nameSection objectAtIndex:row]; The error message is Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x6832440 Where ever I use "[nameSection objectAtIndex:row];" type of statement it always get exception.

    Read the article

  • Cutting Row with Data and moving to different sheet VBA

    - by user3709645
    I'm trying to cut a row that has the specified cell blank and then paste it into another sheet in the same workbook. My coding works fine to delete the row but everything I've tried to cut and paste keeps giving me errors. Here's the working code that deletes the rows: Sub Remove() 'Remove No Denovo &/or No Peak Seq Dim n As Long Dim nLastRow As Long Dim nFirstRow As Long Dim lastRow As Integer ActiveSheet.UsedRange Set r = ActiveSheet.UsedRange nLastRow = r.rows.Count + r.Row - 1 nFirstRow = r.Row For n = nLastRow To nFirstRow Step -1 If Cells(n, "G") = "" Then Cells(n, "G").EntireRow.Delete Next n End Sub Thanks for any help!

    Read the article

  • Problem with java and conditional (game of life)

    - by Muad'Dib
    Hello everybody, I'm trying to implement The Game of Life in java, as an exercise to learn this language. Unfortunately I have a problem, as I don't seem able to make this program run correctly. I implemented a torodial sum (the plane is a donut) with no problem: int SumNeighbours (int i, int j) { int value = 0; value = world[( i - 1 + row ) % row][( j - 1 + column ) % column]+world[( i - 1 + row ) % row][j]+world[( i - 1 + row ) % row][( j + 1 ) % column]; value = value + world[i][( j - 1 + column ) % column] + world[i][( j + 1 ) % column]; value = value + world[( i + 1 ) % row][( j - 1 + column ) % column] + world[( i + 1 ) % row][j]+world[ ( i+1 ) % row ][( j + 1 ) % column]; return value; } And it sums correctly when I test it: void NextWorldTest () { int count; int [][] nextWorld = new int[row][row]; nextWorld = world; for (int i=0; i<row; i++) { for (int j=0; j<column; j++) { count = SumNeighbours(i,j); System.out.print(" " + count + " "); } System.out.println(); } world=nextWorld; } Unfortunately when I add the conditions of game of life (born/death) the program stop working correctly, as it seems not able anymore to count correctly the alive cells in the neighborhood. It counts where there are none, and it doesn't count when there are some. E.g.: it doesn't count the one below some living cells. It's a very odd behaviour, and it's been giving me a headache for 3 days now... maybe I'm missing something basic about variables? Here you can find the class. void NextWorld () { int count; int [][] nextWorld = new int[row][column]; nextWorld = world; for (int i=0; i<row; i++) { for (int j=0; j<column; j++) { count = SumNeighbours(i,j); System.out.print(" " + count + " "); if ( ( world[i][j] == 0) && ( count == 3 ) ) { nextWorld[i][j] = 1; } else if ( ( world[i][j] == 1 ) && ( (count == 3) || (count == 2) )) { nextWorld[i][j] = 1; } else { nextWorld[i][j]=0; } } System.out.println(); } world=nextWorld; } } Am I doing something wrong? Below you can find the full package. package com.GaOL; public class GameWorld { int [][] world; int row; int column; public int GetRow() { return row; } public int GetColumn() { return column; } public int GetWorld (int i, int j) { return world[i][j]; } void RandomGen (int size, double p1) { double randomCell; row = size; column = size; world = new int[row][column]; for (int i = 0; i<row; i++ ) { for (int j = 0; j<column; j++ ) { randomCell=Math.random(); if (randomCell < 1-p1) { world[i][j] = 0; } else { world[i][j] = 1; } } } } void printToConsole() { double test = 0; for (int i=0; i<row; i++) { for (int j=0; j<column; j++) { if ( world[i][j] == 0 ) { System.out.print(" "); } else { System.out.print(" * "); test++; } } System.out.println(""); } System.out.println("ratio is " + test/(row*column)); } int SumNeighbours (int i, int j) { int value = 0; value = world[( i - 1 + row ) % row][( j - 1 + column ) % column]+world[( i - 1 + row ) % row][j]+world[( i - 1 + row ) % row][( j + 1 ) % column]; value = value + world[i][( j - 1 + column ) % column] + world[i][( j + 1 ) % column]; value = value + world[( i + 1 ) % row][( j - 1 + column ) % column] + world[( i + 1 ) % row][j]+world[ ( i+1 ) % row ][( j + 1 ) % column]; return value; } void NextWorldTest () { int count; int [][] nextWorld = new int[row][row]; nextWorld = world; for (int i=0; i<row; i++) { for (int j=0; j<column; j++) { count = SumNeighbours(i,j); System.out.print(" " + count + " "); } System.out.println(); } world=nextWorld; } void NextWorld () { int count; int [][] nextWorld = new int[row][column]; nextWorld = world; for (int i=0; i<row; i++) { for (int j=0; j<column; j++) { count = SumNeighbours(i,j); System.out.print(" " + count + " "); if ( ( world[i][j] == 0) && ( count == 3 ) ) { nextWorld[i][j] = 1; } else if ( ( world[i][j] == 1 ) && ( (count == 3) || (count == 2) )) { nextWorld[i][j] = 1; } else { nextWorld[i][j]=0; } } System.out.println(); } world=nextWorld; } } and here the test class: package com.GaOL; public class GameTestClass { public static void main(String[] args) { GameWorld prova = new GameWorld(); prova.RandomGen(10, 0.02); for (int i=0; i<3; i++) { prova.printToConsole(); prova.NextWorld(); } } }

    Read the article

  • EXCEL generate a character in one column of a row, only if other columns in the same row are not bl

    - by Simon
    My speadsheet keeps track of when patients leave a specific floor of the hospital. There are columns in which where each patient goes is documented (1 column for "home", another column for "rehab facility", another for "other floor", etc.). Only when the patient leaves the hospital altogether does it count as a discharge, in which case the “discharge” column needs to have something in it. What formula can I use to generate, say, an "x" in the "discharge" column if certain "where they went" columns in the same row contain something, but not if there is nothing in any of them? Currently, to accomplish this I am using =IF(OR(M30,N30,O30,P30,Q30,R30,S30),"x") in row 3 of the "discharge" column (rows 1 and 2 are headings), and I have used "fill down" in all subsequent rows. To suppress the "FALSE" this formula yields when the condition is not true, I have applied conditonal formatting to the entire column that if the value=FALSE then the font is white (same colour as background). Is there a more efficient, elegant and idiot-proof way of doing this? The conditional formatting of text colour could potentially confuse everyone but the person who built the spreadsheet (me).

    Read the article

  • Import data in Excel that doesn't have a row delimiter, but number of columns is known

    - by Alex B
    So i have this text file that looks something like this: Header1 Header2 Header3 Header4 A1 B1 C1 D1 A2 B2 C2 D2 and so on. When imported, I'd want the data to format itself in 4 columns. I tried the Get External Data from Text, and it successfully imports it, but it doesn't wrap it around, so it just keeps making columns for every space. I'd want it to go on the next line after 4 (in this case) elements have been added. What's the simplest way to achieve this? EDIT: My answer follows, since I'm not yet allowed to answer my own questions yet. The Excel function I needed is called indirect(). Not sure how it actually works though, so hopefully someone can help out with that, but the function call that worked for me is =INDIRECT(ADDRESS((ROW(A1)-1)*4+COLUMN(A1),1)) which i found over here: http://www.ozgrid.com/forum/showthread.php?t=101584&p=456031#post456031 Note: this required me to add the text to excel where i'd get this row full of columns, and then flip it so that i'd have a column full of rows.

    Read the article

  • Trying to Add Insert Row to Footer in GridView ASP.net

    - by chillconsulting
    I'm trying to give the user the ability to create a new record from the footer row and my event handler doesn't seem to be working... or maybe I'm going at this all wrong. The insert button that I enabled in the gridview doesn't work either...checkout the site at http://aisched.engr.oregonstate.edu/admin/courses.aspx Here is my code in front and behind: public partial class admin_courses : System.Web.UI.Page { public Table table; ListDictionary listValues = new ListDictionary(); TextBox textBox1 = new TextBox(); //Name TextBox textBox2 = new TextBox(); //CR TextBox textBox3 = new TextBox(); //CourseNum TextBox textBox4 = new TextBox(); //Dept protected void Page_Init() { } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType != DataControlRowType.Footer) return; //Escape if not footer textBox1.ID = "name"; textBox1.Width = 250; textBox2.ID = "credit_hours"; textBox2.Width = 25; textBox3.ID = "dept"; textBox3.Width = 30; textBox4.ID = "class"; textBox4.Width = 25; LinkButton add = new LinkButton(); add.ID = "add"; add.Text = "Add course"; add.CommandName = "add"; add.Click += new EventHandler(add_Click); e.Row.Cells[1].Controls.Add(textBox1); e.Row.Cells[2].Controls.Add(textBox2); e.Row.Cells[3].Controls.Add(textBox3); e.Row.Cells[4].Controls.Add(textBox4); e.Row.Cells[5].Controls.Add(add); } public void add_Click(object sender, EventArgs e) { Response.Write("you Clicked Add Course!"); if (textBox1.Text != null && textBox2.Text != null && textBox3.Text != null && textBox4.Text != null) { listValues.Add("name", textBox1.Text); listValues.Add("credit_hours", textBox2.Text); listValues.Add("dept", textBox4.Text); //For Visual listValues.Add("class", textBox3.Text); } LinqDataSource1.Insert(listValues); Response.Redirect("~/admin/courses.aspx"); } } <%@ Page Language="C#" MasterPageFile="~/admin.master" AutoEventWireup="true" CodeFile="courses.aspx.cs" Inherits="admin_courses" Title="OSU Aisched | Admin - Courses" %> <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %> <asp:Content ID="Content1" ContentPlaceHolderID="admin_nav_links" Runat="Server"> <ul id="main"> <li><a href="overview.aspx">Overview</a></li> <li><a href="users.aspx">Users</a></li> <li class="current_page_item"><a href="courses.aspx">Courses</a></li> <li><a href="programs.aspx">Programs</a></li> <li><a href="sections.aspx">Sections</a></li> <li><a href="import.aspx">Import</a></li> <li><a href="logs.aspx">Logs</a></li> </ul> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <form id="Form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="DataClassesDataContext" EnableDelete="True" EnableInsert="True" EnableUpdate="True" TableName="courses"> </asp:LinqDataSource> <h1><a>Courses</a></h1> <asp:UpdateProgress ID="UpdateProgress1" runat="server"> </asp:UpdateProgress> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="course_id" DataSourceID="LinqDataSource1" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" AllowSorting="True" ShowFooter="True" OnRowDataBound="GridView1_RowDataBound" > <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" /> <Columns> <asp:BoundField DataField="course_id" HeaderText="ID" ReadOnly="True" SortExpression="course_id" /> <asp:BoundField DataField="name" HeaderText="Name" SortExpression="name" /> <asp:BoundField DataField="credit_hours" HeaderText="CR" SortExpression="credit_hours" /> <asp:BoundField DataField="dept" HeaderText="Dept" SortExpression="dept" /> <asp:BoundField DataField="class" HeaderText="#" SortExpression="class" /> <asp:CommandField DeleteImageUrl="~/media/delete.png" ShowDeleteButton="True" ShowEditButton="True" ShowInsertButton="True"/> </Columns> <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" /> <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" /> </asp:GridView> <br /> <asp:HyperLink ID="HyperLink1" runat="server" Target="~/admin/addCourse.aspx" Enabled="true"NavigateUrl="~/admin/addCourse.aspx" Text="Add New course"></asp:HyperLink> <br /> </form> </asp:Content>

    Read the article

  • jqGrid - customizing the multi-select option (restrict single selection and adding custom events)

    - by Renso
    Goal: Using the jgGrid to enable a selection of a checkbox for row selection - which is easy to set in the jqGrid - but also only allowing a single row to be selectable at a time while adding events based on whether the row was selected or de-selected. Environment: jQuery 1.4.4 jqGrid 3.4.4a Issue: The jqGrid does not support the option to restrict the multi-select to only allow for a single selection. You may ask, why bother with the multi-select checkbox function if you only want to allow for the selection of a single row? Good question, as an example, you want to reserve the selection of a row to trigger another kind of event and use the checkbox multi-select to handle a different kind of event; in other words, when I select the row I want something entirely different to happen than when I select to check off the checkbox for that row. Also the setSelection method of the jqGrid is a toggle and has no support for determining whether the checkbox has already been selected or not, So it will simply act as a switch - which it is designed to do - but with no way out of the box to only check off the box (as in not to de-select) rather than act like a switch. Furthermore, the getGridParam('selrow') does not indicate if the row was selected or de-selected, which seems a bit strange and is the main reason for this blog post. Solution: How this will act: When you check off a multi-select checkbox in the gird, and then commence to select another row by checking off that row's multi-select checkbox - I'm not talking there about clicking on the row but using the grid's multi-select checkbox - it will de-select the previous selection so that you are always left with only a single selection. Furthermore, once you select or de-select a multi-select checkbox, fire off an event that will be determined by whether or not the row was selected or de-selected, not just merely clicked on. So if I de-select the row do one thing but when selecting it do another. Implementation (this of course is only a partial code snippet):             multiselect: true,             multiboxonly: true,             onSelectRow: function (rowId) {                 var gridSelRow = $(item).getGridParam('selrow');                 var s;                 s = $(item).getGridParam('selarrrow');                 if (!s || !s[0]) {                     $(item).resetSelection();                     $('#productLineDetails').fadeOut();                     lastsel = null;                     return;                 }                 var selected = $.inArray(rowId, s) != -1;                 if (selected) {                     $('#productLineDetails').show();                 }                 else {                     $('#productLineDetails').fadeOut();                 }                 if (rowId && rowId !== lastsel && selected) {                     $(item).GridToForm(gridSelRow, '#productLineDetails');                     if (lastsel) $(item).setSelection(lastsel, false);                 }                 lastsel = rowId;             }, In the example code above: The "item" property is the id of the jqGrid. The following to settings ensure that the jqGrid will add the new column to select rows with a checkbox and also the not allow for the selection by clicking on the row but to force the user to have to click on the multi-select checkbox to select the row: multiselect: true, multiboxonly: true, Unfortunately the var gridSelRow = $(item).getGridParam('selrow') function will only return the row the user clicked on or rather that the row's checkbox was clicked on and NOT whether or not it was selected nor de-selected, but it retrieves the row id, which is what we will need. The following piece get's all rows that have been selected so far, as in have a checked off multi-select checkbox: var s; s = $(item).getGridParam('selarrrow'); Now determine if the checkbox the user just clicked on was selected or de-selected: var selected = $.inArray(rowId, s) != -1; If it was selected then show a container "#productLineDetails", if not hide that container away. The following instruction populates a form with the grid data using the built-in GridToForm method (just mentioned here as an example) ONLY if the row has been selected and NOT de-selected but more importantly to de-select any other multi-select checkbox that may have been selected: if (rowId && rowId !== lastsel && selected) {                     $(item).GridToForm(gridSelRow, '#productLineDetails');                     if (lastsel) $(item).setSelection(lastsel, false); }

    Read the article

  • Negamax implementation doesn't appear to work with tic-tac-toe

    - by George Jiglau
    I've implemented Negamax as it can be found on wikipedia, which includes alpha/beta pruning. However, it seems to favor a losing move, which should be an invalid result. The game is Tic-Tac-Toe, I've abstracted most of the game play so it should be rather easy to spot an error within the algorithm. Here is the code, nextMove, negamax or evaluate are probably the functions that contain the fault: #include <list> #include <climits> #include <iostream> //#define DEBUG 1 using namespace std; struct Move { int row, col; Move(int row, int col) : row(row), col(col) { } Move(const Move& m) { row = m.row; col = m.col; } }; struct Board { char player; char opponent; char board[3][3]; Board() { } void read(istream& stream) { stream >> player; opponent = player == 'X' ? 'O' : 'X'; for(int row = 0; row < 3; row++) { for(int col = 0; col < 3; col++) { char playa; stream >> playa; board[row][col] = playa == '_' ? 0 : playa == player ? 1 : -1; } } } void print(ostream& stream) { for(int row = 0; row < 3; row++) { for(int col = 0; col < 3; col++) { switch(board[row][col]) { case -1: stream << opponent; break; case 0: stream << '_'; break; case 1: stream << player; break; } } stream << endl; } } void do_move(const Move& move, int player) { board[move.row][move.col] = player; } void undo_move(const Move& move) { board[move.row][move.col] = 0; } bool isWon() { if (board[0][0] != 0) { if (board[0][0] == board[0][1] && board[0][1] == board[0][2]) return true; if (board[0][0] == board[1][0] && board[1][0] == board[2][0]) return true; } if (board[2][2] != 0) { if (board[2][0] == board[2][1] && board[2][1] == board[2][2]) return true; if (board[0][2] == board[1][2] && board[1][2] == board[2][2]) return true; } if (board[1][1] != 0) { if (board[0][1] == board[1][1] && board[1][1] == board[2][1]) return true; if (board[1][0] == board[1][1] && board[1][1] == board[1][2]) return true; if (board[0][0] == board[1][1] && board[1][1] == board[2][2]) return true; if (board[0][2] == board [1][1] && board[1][1] == board[2][0]) return true; } return false; } list<Move> getMoves() { list<Move> moveList; for(int row = 0; row < 3; row++) for(int col = 0; col < 3; col++) if (board[row][col] == 0) moveList.push_back(Move(row, col)); return moveList; } }; ostream& operator<< (ostream& stream, Board& board) { board.print(stream); return stream; } istream& operator>> (istream& stream, Board& board) { board.read(stream); return stream; } int evaluate(Board& board) { int score = board.isWon() ? 100 : 0; for(int row = 0; row < 3; row++) for(int col = 0; col < 3; col++) if (board.board[row][col] == 0) score += 1; return score; } int negamax(Board& board, int depth, int player, int alpha, int beta) { if (board.isWon() || depth <= 0) { #if DEBUG > 1 cout << "Found winner board at depth " << depth << endl; cout << board << endl; #endif return player * evaluate(board); } list<Move> allMoves = board.getMoves(); if (allMoves.size() == 0) return player * evaluate(board); for(list<Move>::iterator it = allMoves.begin(); it != allMoves.end(); it++) { board.do_move(*it, -player); int val = -negamax(board, depth - 1, -player, -beta, -alpha); board.undo_move(*it); if (val >= beta) return val; if (val > alpha) alpha = val; } return alpha; } void nextMove(Board& board) { list<Move> allMoves = board.getMoves(); Move* bestMove = NULL; int bestScore = INT_MIN; for(list<Move>::iterator it = allMoves.begin(); it != allMoves.end(); it++) { board.do_move(*it, 1); int score = -negamax(board, 100, 1, INT_MIN + 1, INT_MAX); board.undo_move(*it); #if DEBUG cout << it->row << ' ' << it->col << " = " << score << endl; #endif if (score > bestScore) { bestMove = &*it; bestScore = score; } } if (!bestMove) return; cout << bestMove->row << ' ' << bestMove->col << endl; #if DEBUG board.do_move(*bestMove, 1); cout << board; #endif } int main() { Board board; cin >> board; #if DEBUG cout << "Starting board:" << endl; cout << board; #endif nextMove(board); return 0; } Giving this input: O X__ ___ ___ The algorithm chooses to place a piece at 0, 1, causing a guaranteed loss, do to this trap(nothing can be done to win or end in a draw): XO_ X__ ___ Perhaps it has something to do with the evaluation function? If so, how could I fix it?

    Read the article

  • UITableView having one Cell with multiple UITextFields (some of them in one row) scrolling crazy

    - by Allisone
    I have a UITableView (grouped). In that tableview I have several UITableViewCells, some custom with nib, some default. One Cell (custom) with nib has several UITextfields for address information, thus also one row has zip-code and city in one row. When I get the keyboard the tableview size seems to be adjusted automatically (vs. another viewController in the app with just a scrollview where I had to code this functionality on my own) so that i can scroll to the bottom of my tableview (and see it) even though the keyboard is up. That's good. BUT when I click on a textfield the tableview gets either scrolled up, or down, I can't figure out the logic. It seems to be rather random up/down scrolling / contentOffset setting. So I have bound the Editing Did Begin events of the textfields to a function that has this code. - (IBAction)textFieldDidBeginEditing:(UITextField *)textField { CGPoint pt; CGRect rc = [textField bounds]; rc = [textField convertRect:rc toView:self.tableView]; pt = rc.origin; pt.x = 0; [self.tableView setContentOffset:pt animated:YES]; ... } This, well, it seems to work most of the time, BUT it doesn't work if I click the first textfield (the view jumps so that the second row gets to the top and the first row is out of the current visible view frame) AND it also doesn't work if I first select the zip textfield and next the city textfield (both in one row) or vice versa. If I do so, the tableview seems to jump to the (grouped tableview) top of my viewForHeaderInSection(this section with this mentioned cell with all my textfields) What is is going on ? Why is this happening ? How to fix this ? Edit This on the other hand behaves as expected (for the two Textviews wit same origin.y) if (self.tableView.contentOffset.y == pt.y) { pt.y = pt.y + 1; [self.tableView setContentOffset:pt animated:YES]; }else { [self.tableView setContentOffset:pt animated:YES]; } But this is a stupid solution. I wouldn't like to keep it that way. And this also doesn't fix the wrong jumping, when clicking the first textfield at first.

    Read the article

  • iPad: Tables in Popover Views do not Scroll to Show Selected Row

    - by mahboudz
    I am having two problems with viewcontrollerss in landscape orientation on the iPad. (1) I have two popups which hold tables. The tables should scroll to a specific row to reflect a selection in the main view. Instead, the tables do scroll down some but the actual selected row remains off screen. (2) All my action sheets come up with a width of 320. In Interface Builder, all my views are created in landscape orientation. Only the main Window is not, but I don't see a way to change that. My Configuration: Upon launch, I get the following coordinates for my main window and the main viewcontroller view: Window frame {{0, 0}, {768, 1024}} mainView frame {{0, 0}, {748, 1024}} All other views after that show these coordinates when summoned (when loaded but before being presented): frame of keysig {{0, 0}, {1024, 768}} frame of instrumentSelect {{20, 0}, {1024, 768}} frame of settings {{0, 0}, {467, 300}} In all my viewControllers, i respond to shouldAutorotateToInterfaceOrientation with: return ((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (interfaceOrientation == UIInterfaceOrientationLandscapeRight)); Everything (almost) functions as expected. The app launches into one of the two landscape modes. The views (and viewcontrollers) display everything where it belongs and taps work all across the screen as expected. However, I still have the two problems. Problem 1: I have two popups containing tables long enough to run off screen. The tables should scroll to a selected row. They do scroll i.e. they don't start visually at row 1 but they don't scroll enough to actually show the selected row. It almost seems like a UITable internal rect gets created with the wrong number and stays that way but I've checked both of the UITableView's scrollView content coordinates and they seemed reasonable. Problem 2: I think this is related to problem 1 because my actionsheets come up with a width of 320. I can only assume that the iPad allows actionSheets in only 320 or 480 widths and since it somehow thinks that the screen is oriented in portrait mode, it uses the narrower width. There you have it. I can't believe I am still getting hung up on orientation issues. I swear Apple doesn't make it easy to have a landscape app. Any ideas?

    Read the article

  • Problem setting row backgrounds in Android Listview

    - by zchtodd
    I have an application in which I'd like one row at a time to have a certain color. This seems to work about 95% of the time, but sometimes instead of having just one row with this color, it will allow multiple rows to have the color. Specifically, a row is set to have the "special" color when it is tapped. In rare instances, the last row tapped will retain the color despite a call to setBackgroundColor attempting to make it otherwise. private OnItemClickListener mDirectoryListener = new OnItemClickListener(){ public void onItemClick(AdapterView parent, View view, int pos, long id){ if (stdir.getStationCount() == pos) { stdir.moreStations(); return; } if (playingView != null) playingView.setBackgroundColor(Color.DKGRAY); view.setBackgroundColor(Color.MAGENTA); playingView = view; playStation(pos); } }; I have confirmed with print statements that the code setting the row to gray is always called. Can anyone imagine a reason why this code might intermittently fail? If there is a pattern or condition that causes it, I can't tell. I thought it might have something to do with the activity lifecycle setting the "playingView" variable back to null, but I can't reliably reproduce the problem by switching activities or locking the phone. private class DirectoryAdapter extends ArrayAdapter { private ArrayList<Station> items; public DirectoryAdapter(Context c, int resLayoutId, ArrayList<Station> stations){ super(c, resLayoutId, stations); this.items = stations; } public int getCount(){ return items.size() + 1; } public View getView(int position, View convertView, ViewGroup parent){ View v = convertView; LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (position == this.items.size()) { v = vi.inflate(R.layout.morerow, null); return v; } Station station = this.items.get(position); v = vi.inflate(R.layout.songrow, null); if (station.playing) v.setBackgroundColor(Color.MAGENTA); else if (station.visited) v.setBackgroundColor(Color.DKGRAY); else v.setBackgroundColor(Color.BLACK); TextView title = (TextView)v.findViewById(R.id.title); title.setText(station.name); return v; } };

    Read the article

  • jQuery - How to Use slideDown (or show) function on a table row?

    - by Greg
    I'm trying to add a row to a table and have that row slide into view, however the slidedown function seems to be adding a display:block style to the table row which messes up the layout. Any ideas how to work around this? Here's the code: $.get('/some_url',{'val1':id}, function(data){ var row = $('#detailed_edit_row'); row.hide(); row.html(data); row.slideDown(1000); });

    Read the article

  • jquery - clone nth row of a table?

    - by John
    I'm trying to use jquery to clone a table row everytime someone presses the add-row button. Can anyone tell me what's wrong with my code? I'm using HTML + smarty templating language in my view. Here's what my template file looks like: <table> <tr> <td>Description</td> <td>Unit</td> <td>Qty</td> <td>Total</td> <td></td> </tr> <tbody id="entries"> {foreach from=$arrItem item=i name=inv} <tr> <td> <input type="hidden" name="invoice_item_id[]" value="{$i.invoice_item_id}"/> <input type="hidden" name="assignment_id[]" value="{$i.assignment_id}" /> <input type="text" name="description[]" value="{$i.description}"/> </td> <td><input type="text" class="unit_cost" name="unit_cost[]" value="{$i.unit_cost}"/></td> <td><input type="text" class="qty" name="qty[]" value="{$i.qty}"/></td> <td><input type="text" class="cost" name="cost[]" value="{$i.cost}"/></td> <td><a href="javascript:void(0);" class="delete-invoice-item">delete</a></td> </tr> {/foreach} </tbody> <tfoot> <tr><td colspan="5"><input type="button" id="add-row" value="add row" /></td></tr> </tfoot> </table> Here's my Jquery Javascript call, which I know gets fired when I put in an alert() statement. So the problem is with me not knowing how jquery works. $('#add-row').live('click', function() {$('#entries tr:nth-child(0)').clone().appendTo('#entries');}); So what am I doing wrong?

    Read the article

  • Php random row help...

    - by Skillman
    I've created some code that will return a random row, (well, all the rows in a random order) But i'm assuming its VERY uneffiecent and is gonna be a problem in a big database... Anyone know of a better way? Here is my current code: $count3 = 1; $count4 = 1; //Civilian stuff... $query = ("SELECT * FROM `*Table Name*` ORDER BY `Id` ASC"); $result = mysql_query($query); while($row = mysql_fetch_array($result)) { $count = $count + 1; $civilianid = $row['Id']; $arrayofids[$count] = $civilianid; //echo $arrayofids[$count]; } while($alldone != true) { $randomnum = (rand()%$count) + 1; //echo $randomnum . "<br>"; //echo $arrayofids[$randomnum] . "<br>"; $currentuserid = $arrayofids[$randomnum]; $count3 += 1; while($count4 < $count3) { $count4 += 1; $currentarrayid = $listdone[$count4]; //echo "<b>" . $currentarrayid . ":" . $currentuserid . "</b> "; if ($currentarrayid == $currentuserid){ $found = true; //echo " '" .$found. "' "; } } if ($found == true) { //Reset array/variables... $count4 = 1; $found = false; } else { $listdone[$count3] = $currentuserid; //echo "<u>" . $count3 .";". $listdone[$count3] . "</u> "; $query = ("SELECT * FROM `*Tablesname*` WHERE Id = '$currentuserid'"); $result = mysql_query($query); $row = mysql_fetch_array($result); $username = $row['Username']; echo $username . "<br>"; $count4 = 1; $amountdone += 1; if ($amountdone == $count) { //$count $alldone = true; } } } Basically it will loop until its gets an id (randomly) that hasnt been chosen yet. -So the last username could take hours :P Is this 'bad' code? :P :(

    Read the article

  • Combination of Operating Mode and Commit Strategy

    - by Kevin Yang
    If you want to populate a source into multiple targets, you may also want to ensure that every row from the source affects all targets uniformly (or separately). Let’s consider the Example Mapping below. If a row from SOURCE causes different changes in multiple targets (TARGET_1, TARGET_2 and TARGET_3), for example, it can be successfully inserted into TARGET_1 and TARGET_3, but failed to be inserted into TARGET_2, and the current Mapping Property TLO (target load order) is “TARGET_1 -> TARGET_2 -> TARGET_3”. What should Oracle Warehouse Builder do, in order to commit the appropriate data to all affected targets at the same time? If it doesn’t behave as you intended, the data could become inaccurate and possibly unusable.                                               Example Mapping In OWB, we can use Mapping Configuration Commit Strategies and Operating Modes together to achieve this kind of requirements. Below we will explore the combination of these two features and how they affect the results in the target tables Before going to the example, let’s review some of the terms we will be using (Details can be found in white paper Oracle® Warehouse Builder Data Modeling, ETL, and Data Quality Guide11g Release 2): Operating Modes: Set-Based Mode: Warehouse Builder generates a single SQL statement that processes all data and performs all operations. Row-Based Mode: Warehouse Builder generates statements that process data row by row. The select statement is in a SQL cursor. All subsequent statements are PL/SQL. Row-Based (Target Only) Mode: Warehouse Builder generates a cursor select statement and attempts to include as many operations as possible in the cursor. For each target, Warehouse Builder inserts each row into the target separately. Commit Strategies: Automatic: Warehouse Builder loads and then automatically commits data based on the mapping design. If the mapping has multiple targets, Warehouse Builder commits and rolls back each target separately and independently of other targets. Use the automatic commit when the consequences of multiple targets being loaded unequally are not great or are irrelevant. Automatic correlated: It is a specialized type of automatic commit that applies to PL/SQL mappings with multiple targets only. Warehouse Builder considers all targets collectively and commits or rolls back data uniformly across all targets. Use the correlated commit when it is important to ensure that every row in the source affects all affected targets uniformly. Manual: select manual commit control for PL/SQL mappings when you want to interject complex business logic, perform validations, or run other mappings before committing data. Combination of the commit strategy and operating mode To understand the effects of each combination of operating mode and commit strategy, I’ll illustrate using the following example Mapping. Firstly we insert 100 rows into the SOURCE table and make sure that the 99th row and 100th row have the same ID value. And then we create a unique key constraint on ID column for TARGET_2 table. So while running the example mapping, OWB tries to load all 100 rows to each of the targets. But the mapping should fail to load the 100th row to TARGET_2, because it will violate the unique key constraint of table TARGET_2. With different combinations of Commit Strategy and Operating Mode, here are the results ¦ Set-based/ Correlated Commit: Configuration of Example mapping:                                                     Result:                                                      What’s happening: A single error anywhere in the mapping triggers the rollback of all data. OWB encounters the error inserting into Target_2, it reports an error for the table and does not load the row. OWB rolls back all the rows inserted into Target_1 and does not attempt to load rows to Target_3. No rows are added to any of the target tables. ¦ Row-based/ Correlated Commit: Configuration of Example mapping:                                                   Result:                                                  What’s happening: OWB evaluates each row separately and loads it to all three targets. Loading continues in this way until OWB encounters an error loading row 100th to Target_2. OWB reports the error and does not load the row. It rolls back the row 100th previously inserted into Target_1 and does not attempt to load row 100 to Target_3. Then, if there are remaining rows, OWB will continue loading them, resuming with loading rows to Target_1. The mapping completes with 99 rows inserted into each target. ¦ Set-based/ Automatic Commit: Configuration of Example mapping: Result: What’s happening: When OWB encounters the error inserting into Target_2, it does not load any rows and reports an error for the table. It does, however, continue to insert rows into Target_3 and does not roll back the rows previously inserted into Target_1. The mapping completes with one error message for Target_2, no rows inserted into Target_2, and 100 rows inserted into Target_1 and Target_3 separately. ¦ Row-based/Automatic Commit: Configuration of Example mapping: Result: What’s happening: OWB evaluates each row separately for loading into the targets. Loading continues in this way until OWB encounters an error loading row 100 to Target_2 and reports the error. OWB does not roll back row 100th from Target_1, does insert it into Target_3. If there are remaining rows, it will continue to load them. The mapping completes with 99 rows inserted into Target_2 and 100 rows inserted into each of the other targets. Note: Automatic Correlated commit is not applicable for row-based (target only). If you design a mapping with the row-based (target only) and correlated commit combination, OWB runs the mapping but does not perform the correlated commit. In set-based mode, correlated commit may impact the size of your rollback segments. Space for rollback segments may be a concern when you merge data (insert/update or update/insert). Correlated commit operates transparently with PL/SQL bulk processing code. The correlated commit strategy is not available for mappings run in any mode that are configured for Partition Exchange Loading or that include a Queue, Match Merge, or Table Function operator. If you want to practice in your own environment, you can follow the steps: 1. Import the MDL file: commit_operating_mode.mdl 2. Fix the location for oracle module ORCL and deploy all tables under it. 3. Insert sample records into SOURCE table, using below plsql code: begin     for i in 1..99     loop         insert into source values(i, 'col_'||i);     end loop;     insert into source values(99, 'col_99'); end; 4. Configure MAPPING_1 to any combinations of operating mode and commit strategy you want to test. And make sure feature TLO of mapping is open. 5. Deploy Mapping “MAPPING_1”. 6. Run the mapping and check the result.

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >