Search Results

Search found 1785 results on 72 pages for 'beauness round'.

Page 64/72 | < Previous Page | 60 61 62 63 64 65 66 67 68 69 70 71  | Next Page >

  • C++ - Conway's Game of Life & Stepping Backwards

    - by Gabe
    I was able to create a version Conway's Game of Life that either stepped forward each click, or just ran forward using a timer. (I'm doing this using Qt.) Now, I need to be able to save all previous game grids, so that I can step backwards by clicking a button. I'm trying to use a stack, and it seems like I'm pushing the old gridcells onto the stack correctly. But when I run it in QT, the grids don't change when I click BACK. I've tried different things for the last three hours, to no avail. Any ideas? gridwindow.cpp - My problem should be in here somewhere. Probably the handleBack() func. #include <iostream> #include "gridwindow.h" using namespace std; // Constructor for window. It constructs the three portions of the GUI and lays them out vertically. GridWindow::GridWindow(QWidget *parent,int rows,int cols) : QWidget(parent) { QHBoxLayout *header = setupHeader(); // Setup the title at the top. QGridLayout *grid = setupGrid(rows,cols); // Setup the grid of colored cells in the middle. QHBoxLayout *buttonRow = setupButtonRow(); // Setup the row of buttons across the bottom. QVBoxLayout *layout = new QVBoxLayout(); // Puts everything together. layout->addLayout(header); layout->addLayout(grid); layout->addLayout(buttonRow); setLayout(layout); } // Destructor. GridWindow::~GridWindow() { delete title; } // Builds header section of the GUI. QHBoxLayout* GridWindow::setupHeader() { QHBoxLayout *header = new QHBoxLayout(); // Creates horizontal box. header->setAlignment(Qt::AlignHCenter); this->title = new QLabel("CONWAY'S GAME OF LIFE",this); // Creates big, bold, centered label (title): "Conway's Game of Life." this->title->setAlignment(Qt::AlignHCenter); this->title->setFont(QFont("Arial", 32, QFont::Bold)); header->addWidget(this->title); // Adds widget to layout. return header; // Returns header to grid window. } // Builds the grid of cells. This method populates the grid's 2D array of GridCells with MxN cells. QGridLayout* GridWindow::setupGrid(int rows,int cols) { isRunning = false; QGridLayout *grid = new QGridLayout(); // Creates grid layout. grid->setHorizontalSpacing(0); // No empty spaces. Cells should be contiguous. grid->setVerticalSpacing(0); grid->setSpacing(0); grid->setAlignment(Qt::AlignHCenter); for(int i=0; i < rows; i++) //Each row is a vector of grid cells. { std::vector<GridCell*> row; // Creates new vector for current row. cells.push_back(row); for(int j=0; j < cols; j++) { GridCell *cell = new GridCell(); // Creates and adds new cell to row. cells.at(i).push_back(cell); grid->addWidget(cell,i,j); // Adds to cell to grid layout. Column expands vertically. grid->setColumnStretch(j,1); } grid->setRowStretch(i,1); // Sets row expansion horizontally. } return grid; // Returns grid. } // Builds footer section of the GUI. QHBoxLayout* GridWindow::setupButtonRow() { QHBoxLayout *buttonRow = new QHBoxLayout(); // Creates horizontal box for buttons. buttonRow->setAlignment(Qt::AlignHCenter); // Clear Button - Clears cell; sets them all to DEAD/white. QPushButton *clearButton = new QPushButton("CLEAR"); clearButton->setFixedSize(100,25); connect(clearButton, SIGNAL(clicked()), this, SLOT(handlePause())); // Pauses timer before clearing. connect(clearButton, SIGNAL(clicked()), this, SLOT(handleClear())); // Connects to clear function to make all cells DEAD/white. buttonRow->addWidget(clearButton); // Forward Button - Steps one step forward. QPushButton *forwardButton = new QPushButton("FORWARD"); forwardButton->setFixedSize(100,25); connect(forwardButton, SIGNAL(clicked()), this, SLOT(handleForward())); // Signals to handleForward function.. buttonRow->addWidget(forwardButton); // Back Button - Steps one step backward. QPushButton *backButton = new QPushButton("BACK"); backButton->setFixedSize(100,25); connect(backButton, SIGNAL(clicked()), this, SLOT(handleBack())); // Signals to handleBack funciton. buttonRow->addWidget(backButton); // Start Button - Starts game when user clicks. Or, resumes game after being paused. QPushButton *startButton = new QPushButton("START/RESUME"); startButton->setFixedSize(100,25); connect(startButton, SIGNAL(clicked()), this, SLOT(handlePause())); // Deletes current timer if there is one. Then restarts everything. connect(startButton, SIGNAL(clicked()), this, SLOT(handleStart())); // Signals to handleStart function. buttonRow->addWidget(startButton); // Pause Button - Pauses simulation of game. QPushButton *pauseButton = new QPushButton("PAUSE"); pauseButton->setFixedSize(100,25); connect(pauseButton, SIGNAL(clicked()), this, SLOT(handlePause())); // Signals to pause function which pauses timer. buttonRow->addWidget(pauseButton); // Quit Button - Exits program. QPushButton *quitButton = new QPushButton("EXIT"); quitButton->setFixedSize(100,25); connect(quitButton, SIGNAL(clicked()), qApp, SLOT(quit())); // Signals the quit slot which ends the program. buttonRow->addWidget(quitButton); return buttonRow; // Returns bottom of layout. } /* SLOT method for handling clicks on the "clear" button. Receives "clicked" signals on the "Clear" button and sets all cells to DEAD. */ void GridWindow::handleClear() { for(unsigned int row=0; row < cells.size(); row++) // Loops through current rows' cells. { for(unsigned int col=0; col < cells[row].size(); col++) // Loops through the rows'columns' cells. { GridCell *cell = cells[row][col]; // Grab the current cell & set its value to dead. cell->setType(DEAD); } } } /* SLOT method for handling clicks on the "start" button. Receives "clicked" signals on the "start" button and begins game simulation. */ void GridWindow::handleStart() { isRunning = true; // It is running. Sets isRunning to true. this->timer = new QTimer(this); // Creates new timer. connect(this->timer, SIGNAL(timeout()), this, SLOT(timerFired())); // Connect "timerFired" method class to the "timeout" signal fired by the timer. this->timer->start(500); // Timer to fire every 500 milliseconds. } /* SLOT method for handling clicks on the "pause" button. Receives "clicked" signals on the "pause" button and stops the game simulation. */ void GridWindow::handlePause() { if(isRunning) // If it is running... this->timer->stop(); // Stops the timer. isRunning = false; // Set to false. } void GridWindow::handleForward() { if(isRunning); // If it's running, do nothing. else timerFired(); // It not running, step forward one step. } void GridWindow::handleBack() { std::vector<std::vector<GridCell*> > cells2; if(isRunning); // If it's running, do nothing. else if(backStack.empty()) cout << "EMPTYYY" << endl; else { cells2 = backStack.peek(); for (unsigned int f = 0; f < cells.size(); f++) // Loop through cells' rows. { for (unsigned int g = 0; g < cells.at(f).size(); g++) // Loop through cells columns. { cells[f][g]->setType(cells2[f][g]->getType()); // Set cells[f][g]'s type to cells2[f][g]'s type. } } cout << "PRE=POP" << endl; backStack.pop(); cout << "OYYYY" << endl; } } // Accessor method - Gets the 2D vector of grid cells. std::vector<std::vector<GridCell*> >& GridWindow::getCells() { return this->cells; } /* TimerFired function: 1) 2D-Vector cells2 is declared. 2) cells2 is initliazed with loops/push_backs so that all its cells are DEAD. 3) We loop through cells, and count the number of LIVE neighbors next to a given cell. --> Depending on how many cells are living, we choose if the cell should be LIVE or DEAD in the next simulation, according to the rules. -----> We save the cell type in cell2 at the same indice (the same row and column cell in cells2). 4) After check all the cells (and save the next round values in cells 2), we set cells's gridcells equal to cells2 gridcells. --> This causes the cells to be redrawn with cells2 types (white or black). */ void GridWindow::timerFired() { backStack.push(cells); std::vector<std::vector<GridCell*> > cells2; // Holds new values for 2D vector. These are the next simulation round of cell types. for(unsigned int i = 0; i < cells.size(); i++) // Loop through the rows of cells2. (Same size as cells' rows.) { vector<GridCell*> row; // Creates Gridcell* vector to push_back into cells2. cells2.push_back(row); // Pushes back row vectors into cells2. for(unsigned int j = 0; j < cells[i].size(); j++) // Loop through the columns (the cells in each row). { GridCell *cell = new GridCell(); // Creates new GridCell. cell->setType(DEAD); // Sets cell type to DEAD/white. cells2.at(i).push_back(cell); // Pushes back the DEAD cell into cells2. } // This makes a gridwindow the same size as cells with all DEAD cells. } for (unsigned int m = 0; m < cells.size(); m++) // Loop through cells' rows. { for (unsigned int n = 0; n < cells.at(m).size(); n++) // Loop through cells' columns. { unsigned int neighbors = 0; // Counter for number of LIVE neighbors for a given cell. // We know check all different variations of cells[i][j] to count the number of living neighbors for each cell. // We check m > 0 and/or n > 0 to make sure we don't access negative indexes (ex: cells[-1][0].) // We check m < size to make sure we don't try to access rows out of the vector (ex: row 5, if only 4 rows). // We check n < row size to make sure we don't access column item out of the vector (ex: 10th item in a column of only 9 items). // If we find that the Type = 1 (it is LIVE), then we add 1 to the neighbor. // Else - we add nothing to the neighbor counter. // Neighbor is the number of LIVE cells next to the current cell. if(m > 0 && n > 0) { if (cells[m-1][n-1]->getType() == 1) neighbors += 1; } if(m > 0) { if (cells[m-1][n]->getType() == 1) neighbors += 1; if(n < (cells.at(m).size() - 1)) { if (cells[m-1][n+1]->getType() == 1) neighbors += 1; } } if(n > 0) { if (cells[m][n-1]->getType() == 1) neighbors += 1; if(m < (cells.size() - 1)) { if (cells[m+1][n-1]->getType() == 1) neighbors += 1; } } if(n < (cells.at(m).size() - 1)) { if (cells[m][n+1]->getType() == 1) neighbors += 1; } if(m < (cells.size() - 1)) { if (cells[m+1][n]->getType() == 1) neighbors += 1; } if(m < (cells.size() - 1) && n < (cells.at(m).size() - 1)) { if (cells[m+1][n+1]->getType() == 1) neighbors += 1; } // Done checking number of neighbors for cells[m][n] // Now we change cells2 if it should switch in the next simulation step. // cells2 holds the values of what cells should be on the next iteration of the game. // We can't change cells right now, or it would through off our other cell values. // Apply game rules to cells: Create new, updated grid with the roundtwo vector. // Note - LIVE is 1; DEAD is 0. if (cells[m][n]->getType() == 1 && neighbors < 2) // If cell is LIVE and has less than 2 LIVE neighbors -> Set to DEAD. cells2[m][n]->setType(DEAD); else if (cells[m][n]->getType() == 1 && neighbors > 3) // If cell is LIVE and has more than 3 LIVE neighbors -> Set to DEAD. cells2[m][n]->setType(DEAD); else if (cells[m][n]->getType() == 1 && (neighbors == 2 || neighbors == 3)) // If cell is LIVE and has 2 or 3 LIVE neighbors -> Set to LIVE. cells2[m][n]->setType(LIVE); else if (cells[m][n]->getType() == 0 && neighbors == 3) // If cell is DEAD and has 3 LIVE neighbors -> Set to LIVE. cells2[m][n]->setType(LIVE); } } // Now we've gone through all of cells, and saved the new values in cells2. // Now we loop through cells and set all the cells' types to those of cells2. for (unsigned int f = 0; f < cells.size(); f++) // Loop through cells' rows. { for (unsigned int g = 0; g < cells.at(f).size(); g++) // Loop through cells columns. { cells[f][g]->setType(cells2[f][g]->getType()); // Set cells[f][g]'s type to cells2[f][g]'s type. } } } stack.h - Here's my stack. #ifndef STACK_H_ #define STACK_H_ #include <iostream> #include "node.h" template <typename T> class Stack { private: Node<T>* top; int listSize; public: Stack(); int size() const; bool empty() const; void push(const T& value); void pop(); T& peek() const; }; template <typename T> Stack<T>::Stack() : top(NULL) { listSize = 0; } template <typename T> int Stack<T>::size() const { return listSize; } template <typename T> bool Stack<T>::empty() const { if(listSize == 0) return true; else return false; } template <typename T> void Stack<T>::push(const T& value) { Node<T>* newOne = new Node<T>(value); newOne->next = top; top = newOne; listSize++; } template <typename T> void Stack<T>::pop() { Node<T>* oldT = top; top = top->next; delete oldT; listSize--; } template <typename T> T& Stack<T>::peek() const { return top->data; // Returns data in top item. } #endif gridcell.cpp - Gridcell implementation #include <iostream> #include "gridcell.h" using namespace std; // Constructor: Creates a grid cell. GridCell::GridCell(QWidget *parent) : QFrame(parent) { this->type = DEAD; // Default: Cell is DEAD (white). setFrameStyle(QFrame::Box); // Set the frame style. This is what gives each box its black border. this->button = new QPushButton(this); //Creates button that fills entirety of each grid cell. this->button->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); // Expands button to fill space. this->button->setMinimumSize(19,19); //width,height // Min height and width of button. QHBoxLayout *layout = new QHBoxLayout(); //Creates a simple layout to hold our button and add the button to it. layout->addWidget(this->button); setLayout(layout); layout->setStretchFactor(this->button,1); // Lets the buttons expand all the way to the edges of the current frame with no space leftover layout->setContentsMargins(0,0,0,0); layout->setSpacing(0); connect(this->button,SIGNAL(clicked()),this,SLOT(handleClick())); // Connects clicked signal with handleClick slot. redrawCell(); // Calls function to redraw (set new type for) the cell. } // Basic destructor. GridCell::~GridCell() { delete this->button; } // Accessor for the cell type. CellType GridCell::getType() const { return(this->type); } // Mutator for the cell type. Also has the side effect of causing the cell to be redrawn on the GUI. void GridCell::setType(CellType type) { this->type = type; redrawCell(); // Sets type and redraws cell. } // Handler slot for button clicks. This method is called whenever the user clicks on this cell in the grid. void GridCell::handleClick() { // When clicked on... if(this->type == DEAD) // If type is DEAD (white), change to LIVE (black). type = LIVE; else type = DEAD; // If type is LIVE (black), change to DEAD (white). setType(type); // Sets new type (color). setType Calls redrawCell() to recolor. } // Method to check cell type and return the color of that type. Qt::GlobalColor GridCell::getColorForCellType() { switch(this->type) { default: case DEAD: return Qt::white; case LIVE: return Qt::black; } } // Helper method. Forces current cell to be redrawn on the GUI. Called whenever the setType method is invoked. void GridCell::redrawCell() { Qt::GlobalColor gc = getColorForCellType(); //Find out what color this cell should be. this->button->setPalette(QPalette(gc,gc)); //Force the button in the cell to be the proper color. this->button->setAutoFillBackground(true); this->button->setFlat(true); //Force QT to NOT draw the borders on the button } Thanks a lot. Let me know if you need anything else.

    Read the article

  • How can I position some divs inside an unordered list so they line up with the root element of the l

    - by Ronedog
    I want to position all the divs to line up to the left on the same x coordinate so it looks nice. Notice the picture below, how based on the number of nested categories the div (and its contents) show up at slightly different x coordinates. I need to have the div's line up at exactly the same x coordinate no matter how deeply nested. Note, the bottom most category always has a div for the content, but that div has to be situated inside the last < li . I am using an unordered list to display the menu and thought the best solution would be to grab the root category (Cat 2, and mCat1) and obtain their left offset using jquery, then simply use that value to update the positioning of the div...but I couldn't seem to get it to work just right. I would appreciate any advice or help that you are willing to give. Heres the HTML <ul id="nav> <li>Cat 2 <ul> <li>sub cat2</li> </ul> </li> <li>mCat1 <ul> <li>Subcat A <ul> <li>Subcat A.1 <ul> <li>Annie</li> </ul> </li> </ul> </li> </ul> </li> </ul> Heres some jquery I tried (I have do insert the div inside this .each() loop in order to retrieve some values, but basically, this selector is grabbing the last < li in the menu tree and placing a div after it and that is the div that I want to position. the 245 value was something I was playing around with to see how I could get things to line up, and I know its out of wack, but the problem is still the same no matter what I do: $("#nav li:not(:has(li))").each(function () { var self = $(this); var position = self.offset(); var xLeft = Math.round(position.left)- 245; console.log("xLeft:", xLeft ); self.after( '<div id="' + self.attr('p_node') + '_p_cont_div" class="property_position" style="display:none; left:' + xLeft + 'px;" /> ' ); }); Heres the css: .property_position{ float:left; position: relative; top: 0px; padding-top:5px; padding-bottom:10px; }

    Read the article

  • Learning MVC - Maintaining model state

    - by GenericTypeTea
    First of all, I'm very new to MVC. Bought the books, but not got the T-Shirt yet. I've put together my first little application, but I'm looking at the way I'm maintaining my model and I don't think it looks right. My form contains the following: <% using (Html.BeginForm("Reconfigured", null, FormMethod.Post, new { id = "configurationForm" })) { %> <%= Html.DropDownList("selectedCompany", new SelectList(Model.Companies, Model.SelectedCompany), new { onchange = "$('#configurationForm').submit()" })%> <%= Html.DropDownList("selectedDepartment", new SelectList(Model.Departments, Model.SelectedDepartment), new { onchange = "$('#configurationForm').submit()" })%> <%=Html.TextArea("comment", Model.Comment) %> <%} %> My controller has the following: public ActionResult Index(string company, string department, string comment) { TestModel form = new TestModel(); form.Departments = _someRepository.GetList(); form.Companies = _someRepository.GetList(); form.Comment = comment; form.SelectedCompany = company; form.SelectedDepartment = department; return View(form); } [HttpPost] public ActionResult Reconfigured(string selectedCompany, string selectedDepartment, string comment) { return RedirectToAction("Index", new { company = selectedCompany, department = selectedDepartment, comment = comment}); } And finally, this is my route: routes.MapRoute( "Default", "{controller}/{company}/{department}", new { controller = "CompanyController", action = "Index", company="", department="" } ); Now, every time I change DropDownList value, all my values are maintained. I end up with a URL like the following after the Reconfigure action is called: http://localhost/Main/Index/Company/Sales?comment=Foo%20Bar Ideally I'd like the URL to remain as: http://localhost/Main/Index My routing object is probably wrong. This can't be the right way? It seems totally wrong to me as for each extra field I add, I have to add the property into the Index() method? I had a look at this answer where the form is passed through TempData. This is obviously an improvement, but it's not strongly typed? Is there a way to do something similar but have it strongly typed? This may be a simple-enough question, but the curse of 10 years of WinForms/WebForms makes this MVC malarky hard to get your head 'round.

    Read the article

  • stats::reorder vs Hmisc::reorder

    - by learnr
    I am trying to get around the strange overlap of stats::reorder vs Hmisc::reorder. Without Hmisc loaded I get the result I want, i.e. an unordered factor: > with(InsectSprays, reorder(spray, count, median)) [1] A A A A A A A A A A A A B B B B B B B B B B B B C C C C C C C C C C C C D D [39] D D D D D D D D D D E E E E E E E E E E E E F F F F F F F F F F F F attr(,"scores") A B C D E F 14.0 16.5 1.5 5.0 3.0 15.0 Levels: C E D A F B Now after loading Hmisc the result is an ordered factor: > library(Hmisc) Loading required package: survival Loading required package: splines Attaching package: 'Hmisc' The following object(s) are masked from 'package:survival': untangle.specials The following object(s) are masked from 'package:base': format.pval, round.POSIXt, trunc.POSIXt, units > with(InsectSprays, reorder(spray, count, median)) [1] A A A A A A A A A A A A B B B B B B B B B B B B C C C C C C C C C C C C D D [39] D D D D D D D D D D E E E E E E E E E E E E F F F F F F F F F F F F Levels: C < E < D < A < F < B In calling stats::reorder directly, I now for some reason get an ordered factor. > with(InsectSprays, stats::reorder(spray, count, median)) [1] A A A A A A A A A A A A B B B B B B B B B B B B C C C C C C C C C C C C D D [39] D D D D D D D D D D E E E E E E E E E E E E F F F F F F F F F F F F Levels: C < E < D < A < F < B Specifying, that I would need an unordered factor results in an error suggesting that stats::reorder is not used? > with(InsectSprays, stats::reorder(spray, count, median, order = FALSE)) Error in FUN(X[[1L]], ...) : unused argument(s) (order = FALSE) So the question really is how do I get an unordered factor with Hmisc loaded?

    Read the article

  • How do I make a SignalR client something when it receives a message?

    - by Ben
    I want to do something when a client receives a message via a SignalR hub. I've put together a basic chat app, but want people to be able to "like" a chat comment. I'm thinking the way to do this is to find the chat message on the client's page and update it using javascript. In the meantime to "prove the concept" I just want to make an alert popup on the client machine to say another user likes the comment. Trouble is, I'm not sure where to put it. (Am struggling to find SignalR documentation to be honest.) can't get my head round what is calling what here. My ChatHub class is as follows: public class ChatHub : Hub { public void Send(string name, string message) { // Call the broadcastMessage method to update clients. Clients.All.broadcastMessage(name, message); } } And my JavaScript is: $(function () { // Declare a proxy to reference the hub. var chat = $.connection.chatHub; // Create a function that the hub can call to broadcast messages. chat.client.broadcastMessage = function (name, message) { // Html encode display name and message. var encodedName = $('<div />').text(name).html(); var encodedMsg = $('<div />').text(message).html(); // Add the message to the page. var divContent = $('#discussion').html(); $('#discussion').html('<div class="container">' + '<div class="content">' + '<p class="username">' + encodedName + '</p>' + '<p class="message">' + encodedMsg + '</p>' + '</div>' + '<div class="slideout">' + '<div class="clickme" onclick="slideMenu(this)"></div>' + '<div class="slidebutton"><img id="imgid" onclick="likeButtonClick(this)" src="Images/like.png" /></div>' + '<div class="slidebutton"><img onclick="commentButtonClick(this)" src="Images/comment.png" /></div>' + '<div class="slidebutton" style="margin-right:0px"><img onclick="redcardButtonClick(this)" src="Images/redcard.png" /></div>' + '</div>' + '</div>' + divContent); }; // Set initial focus to message input box. $('#message').focus(); // Start the connection. $.connection.hub.start().done(function () { $('#sendmessage').click(function () { // Call the Send method on the hub. chat.server.send($('#lblUser').html(), $('#message').val()); // Clear text box and reset focus for next comment. $('#message').val('').focus(); }); });

    Read the article

  • Silverlight with MVVM Inheritance: ModelView and View matching the Model

    - by moonground.de
    Hello Stackoverflowers! :) Today I have a special question on Silverlight (4 RC) MVVM and inheritance concepts and looking for a best practice solution... I think that i understand the basic idea and concepts behind MVVM. My Model doesn't know anything about the ViewModel as the ViewModel itself doesn't know about the View. The ViewModel knows the Model and the Views know the ViewModels. Imagine the following basic (example) scenario (I'm trying to keep anything short and simple): My Model contains a ProductBase class with a few basic properties, a SimpleProduct : ProductBase adding a few more Properties and ExtendedProduct : ProductBase adding another properties. According to this Model I have several ViewModels, most essential SimpleProductViewModel : ViewModelBase and ExtendedProductViewModel : ViewModelBase. Last but not least, according Views SimpleProductView and ExtendedProductView. In future, I might add many product types (and matching Views + VMs). 1. How do i know which ViewModel to create when receiving a Model collection? After calling my data provider method, it will finally end up having a List<ProductBase>. It containts, for example, one SimpleProduct and two ExtendedProducts. How can I transform the results to an ObservableCollection<ViewModelBase> having the proper ViewModel types (one SimpleProductViewModel and two ExtendedProductViewModels) in it? I might check for Model type and construct the ViewModel accordingly, i.e. foreach(ProductBase currentProductBase in resultList) if (currentProductBase is SimpleProduct) viewModels.Add( new SimpleProductViewModel((SimpleProduct)currentProductBase)); else if (currentProductBase is ExtendedProduct) viewModels.Add( new ExtendedProductViewModels((ExtendedProduct)currentProductBase)); ... } ...but I consider this very bad practice as this code doesn't follow the object oriented design. The other way round, providing abstract Factory methods would reduce the code to: foreach(ProductBase currentProductBase in resultList) viewModels.Add(currentProductBase.CreateViewModel()) and would be perfectly extensible but since the Model doesn't know the ViewModels, that's not possible. I might bring interfaces into game here, but I haven't seen such approach proven yet. 2. How do i know which View to display when selecting a ViewModel? This is pretty the same problem, but on a higher level. Ended up finally having the desired ObservableCollection<ViewModelBase> collection would require the main view to choose a matching View for the ViewModel. In WPF, there is a DataTemplate concept which can supply a View upon a defined DataType. Unfortunately, this doesn't work in Silverlight and the only replacement I've found was the ResourceSelector of the SLExtensions toolkit which is buggy and not satisfying. Beside that, all problems from Question 1 apply as well. Do you have some hints or even a solution for the problems I describe, which you hopefully can understand from my explanation? Thank you in advance! Thomas

    Read the article

  • Finding the closest object in proxmity to the mouse Coordinates

    - by Cam
    Hey there, i've been working on a problem for a while now, which involves targeting the closest movieClip in relation to the x y coords of the mouse, I've attached a nice little acompanying graphic. Each mc added to the stage has it's own sub-class (HotSpots) which uses Pythag to measure distance from mouse. At this stage i can determine the closest value from my Main class but can't figure out how to reference it back to the movieclip... hope this makes sense. Below are the two Classes. My Main Class which attachs the mcs, and monitors mouse movement and traces closest value package { import flash.display.*; import flash.text.*; import flash.events.*; public class Main extends MovieClip { var pos:Number = 50; var nodeArray:Array; public function Main(){ nodeArray = []; for(var i:int = 0; i < 4; i++) { var hotSpot_mc:HotSpots = new HotSpots; hotSpot_mc.x += pos; hotSpot_mc.y += pos; addChild(hotSpot_mc); nodeArray.push(hotSpot_mc); // set some pos pos += 70; } stage.addEventListener(MouseEvent.MOUSE_MOVE,updateProxmity) } public function updateProxmity(e:MouseEvent):void { var tempArray:Array = new Array(); for(var i:int = 0; i < 4; i++) { this['tf'+[i]].text = String(nodeArray[i].dist); tempArray.push(nodeArray[i].dist); } tempArray.sort(Array.NUMERIC); var minValue:int = tempArray[0]; trace(minValue) } } } My HotSpots Class package { import flash.display.MovieClip; import flash.events.Event; import flash.text.TextField; public class HotSpots extends MovieClip { public var XSide:Number; public var YSide:Number; public var dist:Number = 0; public function HotSpots() { addEventListener(Event.ENTER_FRAME, textUp); } public function textUp(event:Event):void { XSide = this.x - MovieClip(root).mouseX; YSide = this.y - MovieClip(root).mouseY; dist = Math.round((Math.sqrt(XSide*XSide + YSide*YSide))); } } } thanks in advance

    Read the article

  • CSS3's border-radius property and border-collapse:collapse don't mix. How can I use border-radius to

    - by vamin
    Edit - Original Title: Is there an alternative way to achieve border-collapse:collapse in CSS (in order to have a collapsed, rounded corner table)? Since it turns out that simply getting the table's borders to collapse does not solve the root problem, I have updated the title to better reflect the discussion. I am trying to make a table with rounded corners using the CSS3 border-radius property. The table styles I'm using look something like this: table { -moz-border-radius:10px; -webkit-border-radius:10px; border-radius:10px} Here's the problem. I also want to set the border-collapse:collapse property, and when that is set border-radius no longer works (at least in Firefox)(edit- I thought this might just be a difference in mozilla's implementation, but it turns out this is the way it's supposed to work according to the w3c). Is there a CSS-based way I can get the same effect as border-collapse:collapse without actually using it? Edits: I've made a simple page to demonstrate the problem here (Firefox/Safari only). It seems that a large part of the problem is that setting the table to have rounded corners does not affect the corners of the corner td elements. If the table was all one color, this wouldn't be a problem since I could just make the top and bottom td corners rounded for the first and last row respectively. However, I am using different background colors for the table to differentiate the headings and for striping, so the inner td elements would show their rounded corners as well. Summary of proposed solutions: Surrounding the table with another element with round corners doesn't work because the table's square corners "bleed through." Specifying border width to 0 doesn't collapse the table. Bottom td corners still square after setting cellspacing to zero. Using javascript instead- works by avoiding the problem. Possible solutions: The tables are generated in php, so I could just apply a different class to each of the outer th/tds and style each corner separately. I'd rather not do this, since it's not very elegant and a bit of a pain to apply to multiple tables, so please keep suggestions coming. Possible solution 2 is to use javascript (jQuery, specifically) to style the corners. This solution also works, but still not quite what I'm looking for (I know I'm picky). I have two reservations: 1) this is a very lightweight site, and I'd like to keep javascript to the barest minimum 2) part of the appeal that using border-radius has for me is graceful degradation and progressive enhancement. By using border-radius for all rounded corners, I hope to have a consistently rounded site in CSS3-capable browsers and a consistently square site in others (I'm looking at you, IE). I know that trying to do this with CSS3 today may seem needless, but I have my reasons. I would also like to point out that this problem is a result of the w3c speficication, not poor CSS3 support, so any solution will still be relevant and useful when CSS3 has more widespread support.

    Read the article

  • AdornerDecorator and tab stop issues

    - by Trev
    Hi, I am using IDataErrorInfo to validate and indicate errors in my text boxes. I am finding I have to tab once for the text box and once for the adornerdecorator. I have an error template: <ControlTemplate x:Key="ErrorTemplate"> <StackPanel KeyboardNavigation.IsTabStop="False" > <Border KeyboardNavigation.IsTabStop="False" BorderBrush="Red" BorderThickness="1" Padding="2" CornerRadius="2"> <AdornedElementPlaceholder KeyboardNavigation.IsTabStop="False" /> </Border> </StackPanel> </ControlTemplate> a textbox template: <Style x:Key="TextBoxInError" TargetType="{x:Type TextBox}"> <Setter Property="KeyboardNavigation.TabNavigation" Value="None"/> <Setter Property="FocusVisualStyle" Value="{x:Null}"/> <Setter Property="Margin" Value="0,5,0,5"/> <Setter Property="AllowDrop" Value="true"/> <Setter Property="HorizontalContentAlignment" Value="left"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type TextBox}"> <Grid KeyboardNavigation.IsTabStop="False" > <Border KeyboardNavigation.IsTabStop="False" x:Name="Border" Background="{DynamicResource WindowBackgroundBrush}" BorderBrush="{DynamicResource SolidBorderBrush}" BorderThickness="1" Padding="2" CornerRadius="2"> <ScrollViewer IsTabStop="False" Margin="0" x:Name="PART_ContentHost" Style="{DynamicResource SimpleScrollViewer}" Background="{TemplateBinding Background}"/> </Border> </Grid> <ControlTemplate.Triggers> <Trigger Property="Validation.HasError" Value="true"> <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors), Converter={StaticResource errorConverter}}"/> </Trigger> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Foreground" Value="Gray"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> and declare a text box like this: <AdornerDecorator KeyboardNavigation.IsTabStop="False" > <TextBox Margin="5,5,5,3" x:Name="txtName" IsEnabled="{Binding EditMode}" Validation.ErrorTemplate="{StaticResource ErrorTemplate}" Text="{Binding ApplicationName, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True, ValidatesOnDataErrors=True}" Height="25" MaxLength="50" MaxLines="1" Style="{StaticResource TextBoxInError}"/> </AdornerDecorator> If the adorner is round one text box as above then I tab once to leave the text box and once to leave the 'adornment' (it seems) If I have the adorner around a stackpanel of text boxes then I tab once each for the text boxes then have to go back through all the 'adornments' in turn. When tabbing through the adornments the focus goes on the red border defined in the control template.. any ideas? thanks

    Read the article

  • How To Create A Download Quota.

    - by snikolov
    I need to create an handy file down loader which will count the amount of bytes downloaded and stop when it has exceed a preset limit. i need to mirror some files but i only have 7 gb per moth of bandwidth and i dont want to exceed the limit. Example limits can be in bytes or number of files, each user has their own limit, as well as a limit for Download Quota itself. So if you set a limit of 2 gigabytes for Download Quota, downloads stop at 2 gigabytes, even if you have 3 users with a limit of 1 gigabyte each. if ($range) { //pass client Range header to rapidshare // _insert($range); $cookie .= "\r\nRange: $range"; $multipart = true; header("X-UR-RANGE-Range: $range"); } //octet-stream + attachment => client always stores file header('Content-type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . $fn . '"'); //always included so clients know this script supports resuming header("Accept-Ranges: bytes"); //awful hack to pass rapidshare the premium cookie $user_agent = ini_get("user_agent"); ini_set("user_agent", $user_agent . "\r\nCookie: enc=$cookie"); $httphandle = fopen($url, "r"); $headers = stream_get_meta_data($httphandle); //let's check the return header of rapidshare for range / length indicators //we'll just pass these to the client foreach ($headers["wrapper_data"] as $header) { $header = trim($header); if (substr(strtolower($header), 0, strlen("content-range")) == "content-range") { // _insert($range); header($header); header("X-RS-RANGE-" . $header); $multipart = true; //content-range indicates partial download } elseif (substr(strtolower($header), 0, strlen("Content-Length")) == "content-length") { // _insert($range); header($header); header("X-RS-CL-" . $header); } } //now show the client he has a partial download if ($multipart) header('HTTP/1.1 206 Partial Content'); flush(); $download_rate = 100; while (!feof($httphandle)) { // send the current file part to the browser $var_stat = fread($httphandle, round($download_rate * 1024)); $var12 = strlen($var_stat); ////////////////////////////////// echo $var_stat; ///////////////////////////////// // flush the content to the browser flush(); // sleep one second sleep(1); }

    Read the article

  • Create Marker Categories & Display Markers on Click Only

    - by MizAkita
    I am trying to create marker categories and display markers on click... For example, "Eat", "Banks", "Places of Interest" and clicking on them would produce only the markers in those categories. You can see it live HERE Here is a code snippet: //<![CDATA[ //<![CDATA[ var map = null; var gmarkers = []; var gicons = []; var icon = []; function initialize() { var myOptions = { zoom: 13, center: new google.maps.LatLng(37.979183,-121.302381), mapTypeControl: true, mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}, navigationControl: true, mapTypeId: google.maps.MapTypeId.ROADMAP } map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); google.maps.event.addListener(map, 'click', function() { infowindow.close(); }); // Add markers to the map // Set up three markers with info windows ///////////////////////// EATS ////////////////////////////////////////////// var point = new google.maps.LatLng(37.988012,-121.311901); var image = 'icons/orangepointer.png'; var marker = createMarker(point,'<div style="width:205"><center><img src="icons/tigeryogurt.jpg" /></center><br><b>Tiger Yogurt</b><small><br>4343 Pacific Avenue<br>209.952.6042<br><br><a href="http://maps.google.com/maps?saddr=&daddr=' + point.toUrlValue() + '" target ="_blank">Get Directions<\/a></small><\/div>', image); // this will be gmarkers[0] var point = new google.maps.LatLng(37.987054,-121.311655); var image = 'icons/orangepointer.png'; var marker = createMarker(point,'<div style="width:205"><center><img src="icons/mwbakery.jpg" /></center><br><b>M&W Bakery<br>Cakes & Sandwiches</b><small><br>4343 Pacific Avenue<br>209.473.3828<br><br>On the web visit:<br><a href="http://www.mandwdutchamericanbakery.com" target ="_blank">MandWDutchAmericanBakery.com<\/a><br><br><a href="http://maps.google.com/maps?saddr=&daddr=' + point.toUrlValue() + '" target ="_blank">Get Directions<\/a></small><\/div>', image); // this will be gmarkers[1] Currently, all markers display. I can easily get the markers not to display... however, i am trying to have only categories display and individual listings to display on click only! CREATE MARKER FUNCTION: } var infowindow = new google.maps.InfoWindow( { size: new google.maps.Size(150,50) }); function triggerClick(i) { google.maps.event.trigger(gmarkers[i],"click") }; function createMarker(latlng, html, img) { var contentString = html; var marker = new google.maps.Marker({ position: latlng, map: map, icon: img, zIndex: Math.round(latlng.lat()*-100000)<<5 }); google.maps.event.addListener(marker, 'click', function() { infowindow.setContent(contentString); infowindow.open(map,marker); }); gmarkers.push(marker); }

    Read the article

  • Android pluginable application

    - by Alxandr
    I've been trying to create an android-application the last couple of weeks, and mostly everything has worked out great, but there is one thing that I was wondering about, and that is pluginability trough the use of intents. What I'm trying to create is basically a comic-reader. As of the version I use now, I open the application and get a list of commics that are my favourites, then I enter one to get a detailed view, and finally I enter a page. This is managed trough 3 activities. List, Details and Page. However, as of now the application can only read comics of one source (a specialiced xml-feed comming from my server), and I was hoping to be able to expand this a litle (also, the page-activity and some other stuff needs to be cleaned up in, so I'm thinking about remaking from scratch, and just take the first go as a learning-round). And I came up with an idea which I think sounds great, but I don't know if it's possible, but this is what I'm thinking about: The user enters the application and get an (first time empty) list of comics. The user hits a button to find comics, this launces an intent that says something like "find comic" or something like that. This should cause the system to display all matching activities. This would make it possible to provide different comic-providers trough different applications. Another activity kicks in and might displays some options to the user (for instance a file-browser), or might not (in the example of an xml-feed, which should just load). The list is returned to the first activity and displayed to the user. The second (find) activity is closed. The user picks a comic from the list. This should open some details-activity. The details-activity should receive a key which corresponds to the comic selected. This should be unique amongst the comic-providers. The details-view should get it's data trough some cind of content-provider, or an activity (whichever is most suited, if one of them is). The user can select a page. This should be the same routine as step 5. My question is, is this possible in the android system, and if it is, is it a bad idea? And also, is there any better way to achieve more or less the same thing?

    Read the article

  • Moving a unit precisely along a path in x,y coordinates

    - by Adam Eberbach
    I am playing around with a strategy game where squads move around a map. Each turn a certain amount of movement is allocated to a squad and if the squad has a destination the points are applied each turn until the destination is reached. Actual distance is used so if a squad moves one position in the x or y direction it uses one point, but moving diagonally takes ~1.4 points. The squad maintains actual position as float which is then rounded to allow drawing the position on the map. The path is described by touching the squad and dragging to the end position then lifting the pen or finger. (I'm doing this on an iPhone now but Android/Qt/Windows Mobile would work the same) As the pointer moves x, y points are recorded so that the squad gains a list of intermediate destinations on the way to the final destination. I'm finding that the destinations are not evenly spaced but can be further apart depending on the speed of the pointer movement. Following the path is important because obstacles or terrain matter in this game. I'm not trying to remake Flight Control but that's a similar mechanic. Here's what I've been doing, but it just seems too complicated (pseudocode): getDestination() { - self.nextDestination = remove_from_array(destinations) - self.gradient = delta y to destination / delta x to destination - self.angle = atan(self.gradient) - self.cosAngle = cos(self.angle) - self.sinAngle = sin(self.angle) } move() { - get movement allocation for this turn - if self.nextDestination not valid - - getNextDestination() - while(nextDestination valid) && (movement allocation remains) { - - find xStep and yStep using movement allocation and sinAngle/cosAngle calculated for current self.nextDestination - - if current position + xStep crosses the destination - - - find x movement remaining after self.nextDestination reached - - - calculate remaining direct path movement allocation (xStep remaining / cosAngle) - - - make self.position equal to self.nextDestination - - else - - - apply xStep and yStep to current position - } - round squad's float coordinates to integer screen coordinates - draw squad image on map } That's simplified of course, stuff like sign needs to be tweaked to ensure movement is in the right direction. If trig is the best way to do it then lookup tables can be used or maybe it doesn't matter on modern devices like it used to. Suggestions for a better way to do it? an update - iPhone has zero issues with trig and tracking tens of positions and tracks implemented as described above and it draws in floats anyway. The Bresenham method is more efficient, trig is more precise. If I was to use integer Bresenham I would want to multiply by ten or so to maintain a little more positional accuracy to benefit collisions/terrain detection.

    Read the article

  • Matlab cell length

    - by AP
    Ok I seem to have got the most of the problem solved, I just need an expert eye to pick my error as I am stuck. I have a file of length [125 X 27] and I want to convert it to a file of length [144 x 27]. Now, I want to replace the missing files (time stamps) rows of zeros. (ideally its a 10 min daily average thus should have file length of 144) Here is the code I am using: fid = fopen('test.csv', 'rt'); data = textscan(fid, ['%s' repmat('%f',1,27)], 'HeaderLines', 1, 'Delimiter', ','); fclose(fid); %//Make time a datenum of the first column time = datenum(data{1} , 'mm/dd/yyyy HH:MM') %//Find the difference in minutes from each row timeDiff = round(diff(datenum(time)*(24*60))) %//the rest of the data data = cell2mat(data(2:28)); newdata=zeros(144,27); for n=1:length(timeDiff) if timeDiff(n)==10 newdata(n,:)=data(n,:); newdata(n+1,:)=data(n+1,:); else p=timeDiff(n)/10 n=n+p; end end Can somebody please help me to find the error inside my for loop. My output file seems to miss few timestamped values. %*********************************************************************************************************** Can somebody help me to figure out the uiget to read the above file?? i am replacing fid = fopen('test.csv', 'rt'); data = textscan(fid, ['%s' repmat('%f',1,27)], 'HeaderLines', 1, 'Delimiter', ','); fclose(fid); With [c,pathc]=uigetfile({'*.txt'},'Select the file','C:\data'); file=[pathc c]; file= textscan(c, ['%s' repmat('%f',1,27)], 'HeaderLines', 1, 'Delimiter', ','); And its not working % NEW ADDITION to old question p = 1; %index into destination for n = 1:length(timeDiff) % if timeDiff(n) == 10 % newfile(p,:) = file(n,:); % newfile(p+1,:)=file(n+1,:); % p = p + 1; % else % p = p + (timeDiff(n)/10); % end q=cumsum(timeDiff(n)/10); if q==1 newfile(p,:)=file(n,:); p=p+1; else p = p + (timeDiff(n)/10); end end xlswrite('testnewws11.xls',newfile); even with the cumsum command this code fails when my file has 1,2 time stamps in middle of long missing ones example 8/16/2009 0:00 5.34 8/16/2009 0:10 3.23 8/16/2009 0:20 2.23 8/16/2009 0:30 1.23 8/16/2009 0:50 70 8/16/2009 2:00 5.23 8/16/2009 2:20 544 8/16/2009 2:30 42.23 8/16/2009 3:00 71.23 8/16/2009 3:10 3.23 My output looks like 5.34 3.23 2.23 0 0 0 0 0 0 0 0 0 5.23 544. 42.23 0 0 0 3.23 Any ideas?

    Read the article

  • My mental block - struggling to learn Objective C

    - by iqessar
    Hello people, this would be my first question after signing up! Anyway heres my question, I did Java at university and I was always told I am a good programmer. However I never pursued it as a career - I went into support and management instead. Im pretty much bored with my job, I have therefore started to learn Objective C so that I can develop apps for the iphone. I am currently watching several different Videos / Books. My problem is that when I go through the Apple documentation, although I understand most of it, sometimes I stumble. I believe that because you/we have the Apple documentation (i.e. Framework references) , everything should be clear, and therefore you should have no need to refer to a book or video (in order to learn how to use a particular class). But I alway do refer to a book and video and subsequently feel guilty as I believe the framework reference should be enough. (I therefore feel I am not up to being a programmer) I also believe that you shouldn't need example code in order to learn how to use a particular class because Apple provides documentation for each class, but AGAIN I find my self googling example code and I find my answer like that - again I feel guilty for doing this. Am I right in saying that Apple documentation is simply not clear? and that its ok to refer to a video/book or google? or forums for that matter? I have proffesional programmers who tell me that I am worrying too much and that I should get on with it and use all the resources that I have. I just cant seem to get round this mental block that I have in my head. When I start a programming project I am able to use the excellent search skills that I have to find the code I need, copy and paste it (yes I do understand it) BUT then I feel guilty telling myself that why didn't you think up the code yourself???? Therefore your not a real programmer, your just good at googling. Currently I am going through 20+ books so that I can learn most of the frameworks, syntax etc to develop iphone apps. I believe if I do this, then when I think of a project I can make it quickly. Should I read a few books, like 2-3 and then just start a project /app , and if I get stuck just google it and get the code I need? Can anybody please answer my questions?

    Read the article

  • How to detect Links with out anchor element in a plain text

    - by dhee
    If user enters his text in the text box and saves it and again what's to add some more text he can edit that text and save it if required. Firstly if user enters that text with some links I, detected them and converted any hyperlinks to linkify in new tab. Secondly if user wants to add some more text and links he clicks on edit and add them and save it at this time I must ignore the links that already hyperlinked with anchor button Please help and advice For example: what = "<span>In the task system, is there a way to automatically have any site / page URL or image URL be hyperlinked in a new window?</span><br><br><span>So If I type or copy http://www.stackoverflow.com/&nbsp; for example anywhere in the description, in any of the internal messages or messages to clients, it automatically is a hyperlink in a new window.</span><br><a href="http://www.stackoverflow.com/">http://www.stackoverflow.com/</a><br> <br><span>Or if I input an image URL anywhere in support description, internal messages or messages to cleints, it automatically is a hyperlink in a new window:</span><br> <span>https://static.doubleclick.net/viewad/4327673/1-728x90.jpg</span><br><br><a href="https://static.doubleclick.net/viewad/4327673/1-728x90.jpg">https://static.doubleclick.net/viewad/4327673/1-728x90.jpg</a><br><br><br><span>This would save us a lot time in task building, reviewing and creating messages.</span> Test URL's http://www.stackoverflow.com/ http://stackoverflow.com/ https://stackoverflow.com/ www.stackoverflow.com //stackoverflow.com/ <a href='http://stackoverflow.com/'>http://stackoverflow.com/</a>"; I've tried this code function Linkify(what) { str = what; out = ""; url = ""; i = 0; do { url = str.match(/((https?:\/\/)?([a-z\-]+\.)*[\-\w]+(\.[a-z]{2,4})+(\/[\w\_\-\?\=\&\.]*)*(?![a-z]))/i); if(url!=null) { // get href value href = url[0]; if(href.substr(0,7)!="http://") href = "http://"+href; // where the match occured where = str.indexOf(url[0]); // add it to the output out += str.substr(0,where); // link it out += '<a href="'+href+'" target="_blank">'+url[0]+'</a>'; // prepare str for next round str = str.substr((where+url[0].length)); } else { out += str; str = ""; } } while(str.length>0); return out; } Please help Thanks.

    Read the article

  • Need help simplifying my php table

    - by user342391
    I am relatively new to php and have a feeling that I am going the long way round when displaying data from mysql. I have a table a I want to show a few fields from my database. How would I achieve this without having to echo every bit of the table??? Here is the code: <?php $query1 = mysql_send("SELECT firstname, lastname, email, user, country FROM customers WHERE id='".$_COOKIE['custid']."'"); while ($row = mysql_fetch_array($query1)) { echo ' <table id="account_table" style="width:550px; border:none; "> <tr> <td width="155">Contact Name</td>'; echo '<td width="335">'; echo $row['firstname'] ; echo '&nbsp;'; echo $row['lastname']; echo '</td> </tr> <tr> <td>Email Address</td> <td>'; echo $row['email']; echo ' </td> </tr> <tr> <td>Username</td> <td>' ; echo $row['user']; echo '</td> </tr> <tr> <td>Country</td> <td>'; echo $row['country']; echo '</td> </tr> <tr> <td>Time Zone</td> <td>GMT+1</td> </tr> <tr> <td>Activated</td> <td>16 Dec 2009</td> </tr> </table>'; } ?>

    Read the article

  • Soften a colour border, maybe with a gradient, programmatically.

    - by ProfK
    I have a narrow header in corporate colour, bright red, with the content below on a just-off-white background. Ive tried softening the long line where these colours meet using border type divs with intermediate backgrounds, but I think I need the original type curved gradient 'area transitions'. I could copy the 1024px wide, and too narrow (vertically), header gif from their web site, and chop it up for eight border images, but that seems clumsy, and I'm looking for something I can apply anywhere, without needing images. I am able to do round borders in the x-y plane, but I'm curious as to how I can apply a gradient to any chosen colour transition. The extra divs I'm using as border elements above and below '#top-section' arose when I was toying with making many divs for one bordered element. This seemed the ultimate in border manipulation, sans code, but very tedious to spec in CSS and lay out a new border for each bordered element. <div id="topsection"> <div style="float: right; width: 300px; padding-right: 5px;"> <div style="font-size: small; text-align: right;"> Provantage Media Management System</div> <div style="font-size: x-small; text-align: right;"> <asp:LoginStatus ID="loginStatus" runat="server" LoginText="Log in" LogoutText="Log out" /> </div> </div> <span style="padding-left: 15px;">Main Menu</span><span id="content-title"> <asp:ContentPlaceHolder ID="titlePlaceHolder" runat="server"> </asp:ContentPlaceHolder> </span> <div style="background-color: white; height: 2px;"> </div> <div style="background-color: white; height: 3px;"></div> And the CSS: #topsection { background-color: #EB2728; color: white; height: 35px; font-size: large; font-weight: bold; }

    Read the article

  • CTE Join query issues

    - by Lee_McIntosh
    Hi everyone, this problem has me head going round in circles at the moment and i wondering if anyone could give any pointers as to where im going wrong. Im trying to produce a SPROC that produces a dataset to be called by SSRS for graphs spanning the last 6 months. The data for example purposes uses three tables (theres more but the it wont change the issue at hand) and are as follows: tbl_ReportList: Report Site ---------------- North abc North def East bbb East ccc East ddd South poa South pob South poc South pod West xyz tbl_TicketsRaisedThisMonth: Date Site Type NoOfTickets --------------------------------------------------------- 2010-07-01 00:00:00.000 abc Support 101 2010-07-01 00:00:00.000 abc Complaint 21 2010-07-01 00:00:00.000 def Support 6 ... 2010-12-01 00:00:00.000 abc Support 93 2010-12-01 00:00:00.000 xyz Support 5 tbl_FeedBackRequests: Date Site NoOfFeedBackR ---------------------------------------------------------------- 2010-07-01 00:00:00.000 abc 101 2010-07-01 00:00:00.000 def 11 ... 2010-12-01 00:00:00.000 abc 63 2010-12-01 00:00:00.000 xyz 4 I'm using CTE's to simplify the code, which is as follows: DECLARE @ReportName VarChar(200) SET @ReportName = 'North'; WITH TicketsRaisedThisMonth AS ( SELECT [Date], Site, SUM(NoOfTickets) AS NoOfTickets FROM tbl_TicketsRaisedThisMonth WHERE [Date] >= DATEADD(mm, DATEDIFF(m,0,GETDATE())-6,0) GROUP BY [Date], Site ), FeedBackRequests AS ( SELECT [Date], Site, SUM(NoOfFeedBackR) AS NoOfFeedBackR FROM tbl_FeedBackRequests WHERE [Date] >= DATEADD(mm, DATEDIFF(m,0,GETDATE())-6,0) GROUP BY [Date], Site ), SELECT trtm.[Date] SUM(trtm.NoOfTickets) AS NoOfTickets, SUM(fbr.NoOfFeedBackR) AS NoOfFeedBackR, FROM Reports rpts LEFT OUTER JOIN TotalIncidentsDuringMonth trtm ON rpts.Site = trtm.Site LEFT OUTER JOIN LoggedComplaints fbr ON rpts.Site = fbr.Site WHERE rpts.report = @ReportName GROUP BY trtm.[Date] And the output when the sproc is pass a parameter such as 'North' to be as follows: Date NoOfTickets NoOfFeedBackR ----------------------------------------------------------------------------------- 2010-07-01 00:00:00.000 128 112 2010-08-01 00:00:00.000 <data for that month> <data for that month> 2010-09-01 00:00:00.000 <data for that month> <data for that month> 2010-10-01 00:00:00.000 <data for that month> <data for that month> 2010-11-01 00:00:00.000 <data for that month> <data for that month> 2010-12-01 00:00:00.000 122 63 The issue I'm having is that when i execute the query I'm given a repeated list of values of each month, such as 128 will repeat 6 times then another value for the next months value repeated 6 times, etc. argh!

    Read the article

  • Any thoughts on how to create a true 'punch-out' area in a Sprite?

    - by rhtx
    I've been working on this for awhile, now. You might also call it a 'reverse mask', or an 'inverse mask'. Basically, I'm creating a view window within a display object. I need to allow objects on the stage that are under the window to be able to interact with the mouse. This is similar to a WPF question: http://stackoverflow.com/questions/740994/use-wpf-object-to-punch-hole-in-another, which has a much shorter write-up. I've got a Class called PunchOutShield, which creates a Sprite that covers the stage (or over some desired area). The Sprite's Graphics object is filled using the color and transparency of Flex's modal screen. The result is a screen that looks like the screen which appears behind a modal PopUp. PunchOutShield has a method called punch, which takes two arguments - the first is a Shape object, which defines the shape of the punch-through area; the second is a Point object, which indicates where to position the punch-through area. It took some experimenting, but I found that I can successfully create a punch-out area (i.e. - the modal screen does not display within the bounds of the given Shape). To do this, I set cacheAsBitmap to true on the Sprite that is used to create the modal screen, and also on the Shape object, which is added to the modal screen Sprite's displayList. If I set the blend mode of the Shape to ERASE, a completely transparent area is created in the modal screen. So far, great. The problem is that Shape does not subclass InteractiveObject, so there is no way to set mouseEnabled = false on it. And so, it prevents interaction between the mouse and any objects that are visible through the punch-out area. On top of that, InteractiveObject isn't available to look at, so I can't see if there is a way to borrow what it's doing to provide the mouseEnabled functionality and apply it to a subclass of Shape. I've tried using another Sprite object, rather than a Shape object, but the blending doesn't work out correctly. I'm not sure why there is a difference, but the Shape object seems to somehow combine with the parenting Sprite, allowing the ERASE blendMode to effect the desired punch-out visual appearance. It wouldn't be the end of the world if I had to draw up the screen with a series of rectangles so that the punch-out area was just simply not drawn, but that approach won't work if the punch-out area is complex. Or round. Any thoughts on this approach, or on an alternative approach?

    Read the article

  • Flash: How to preload upcoming SWF while current one plays

    - by pthesis
    I have a Flash slideshow that plays SWFs listed in an XML file. I would like to have the upcoming SWF load while the current one displays. I've tried all sorts of combinations of LoadMovie and LoadMovieNum, including creating an empty movie clip, but there's something I'm just not getting. Right now, after making the first round through all the files, it transitions smoothly from slide to slide, but I'd like for it to preload so that it transitions without the "Loading..." screen the first time around. It can be viewed here: slideshow Where should I put the LoadMovie line to load the next file (image[p+1]), and how should it look? function loadXML(loaded) { if (loaded) { xmlNode = this.firstChild; image = []; description = []; total = xmlNode.childNodes.length; for (i=0; i<total; i++) { image[i] = xmlNode.childNodes[i].childNodes[0].firstChild.nodeValue; description[i] = xmlNode.childNodes[i].childNodes[1].firstChild.nodeValue; } firstImage(); } else { content = "file not loaded!"; } } xmlData = new XML(); xmlData.ignoreWhite = true; xmlData.onLoad = loadXML; xmlData.load("xmlfile.xml"); ///////////////////////////////////// back_btn.onRelease = function () { backImage(); }; next_btn.onRelease = function () { nextImage(); }; p = 0; function nextImage() { if (p<(total-1)) { p++; trace(this); _root.mc_loadfile.loadMovie (image[p]); _root.movie_name.text = image[p]; next_btn._visible = true; back_btn._visible = true; if (getBytesLoaded() == getBytesTotal()) slideshow(); } else if (p == (total-1)) { p = 0; firstImage(); } } function backImage() { clearInterval(myInterval); if (p>0) { --p; _root.mc_loadfile.loadMovie (image[p]); _root.movie_name.text = image[p]; next_btn._visible = true; if (p != 0) { back_btn._visible = true; } else { back_btn._visible = false; } slideshow(); } } I'd appreciate any help.

    Read the article

  • New to MVC. Actionscript 3.0 Appreciate your help.

    - by Combustion007
    Hello Everyone, I am new to design patterns and am trying to learn the MVC implementation. I have written four classes: DataModel DataView DataController Main Main serves as the application facade. The main FLA is called HelloWorld. I have a symbol called "Box" in HelloWorld. I just would like to add an instance of the "Box" on the stage. Eventually I would like to place a button and when the button is clicked, the Box instance color will be changed. I would appreciate any help, please help me figure out what am I doing wrong. Here are my Classes: DATAMODEL CLASS: package { import flash.events.*; public class DataModel extends EventDispatcher { public static const UPDATE:String = "modelUpdate"; private var _color:Number = (Math.round(Math.random()* 0xffffff)); public function DataModel() { trace("DATA MODEL INIT"); } public function get color():Number { return _color; } public function set color(p:Number):void { _color = p; notifyObserver(); } public function notifyObserver():void { dispatchEvent(new Event(DataModel.UPDATE)); } } } //DATACONTROLLER CLASS: package { import flash.events.; import flash.display.; import flash.errors.*; public class DataController { private var _model:DataModel; public function DataController(m:DataModel) { trace("DATACONTROLLER INIT"); _model = m; } } } DATAVIEW CLASS: package { import flash.events.; import flash.display.; import flash.errors.*; public class DataView extends Sprite { private var _model:DataModel; private var _controller:DataController; private var b:Box; public function DataView(m:DataModel, c:DataController) { _model = m; _controller = c; b = new Box(); b.x = b.y = 100; addChild(b); } } } And Finally THE FACADE: package { import flash.display.; import flash.events.; import flash.text.; import flash.errors.; public class Main extends Sprite { private var _model:DataModel; private var _controller:DataController; private var _view:DataView; public function Main(m:DataModel, c:DataController, v:DataView) { _model = m; _controller = c; _view = v; addChild(v); } } } When I test the movie: I get this error: ArgumentError: Error #1063: Argument count mismatch on Main(). Expected 3, got 0. Thanks alot.

    Read the article

  • Publishing/subscribing multiple subsets of the same server collection

    - by matb33
    How does one go about publishing different subsets (or "views") of a single collection on the server as multiple collections on the client? Here is some pseudo-code to help illustrate my question: items collection on the server Assume that I have an items collection on the server with millions of records. Let's also assume that: 50 records have the enabled property set to true, and; 100 records have the processed property set to true. All others are set to false. items: { "_id": "uniqueid1", "title": "item #1", "enabled": false, "processed": false }, { "_id": "uniqueid2", "title": "item #2", "enabled": false, "processed": true }, ... { "_id": "uniqueid458734958", "title": "item #458734958", "enabled": true, "processed": true } Server code Let's publish two "views" of the same server collection. One will send down a cursor with 50 records, and the other will send down a cursor with 100 records. There are over 458 million records in this fictitious server-side database, and the client does not need to know about all of those (in fact, sending them all down would probably take several hours in this example): var Items = new Meteor.Collection("items"); Meteor.publish("enabled_items", function () { // Only 50 "Items" have enabled set to true return Items.find({enabled: true}); }); Meteor.publish("processed_items", function () { // Only 100 "Items" have processed set to true return Items.find({processed: true}); }); Client code In order to support the latency compensation technique, we are forced to declare a single collection Items on the client. It should become apparent where the flaw is: how does one differentiate between Items for enabled_items and Items for processed_items? var Items = new Meteor.Collection("items"); Meteor.subscribe("enabled_items", function () { // This will output 50, fine console.log(Items.find().count()); }); Meteor.subscribe("processed_items", function () { // This will also output 50, since we have no choice but to use // the same "Items" collection. console.log(Items.find().count()); }); My current solution involves monkey-patching _publishCursor to allow the subscription name to be used instead of the collection name. But that won't do any latency compensation. Every write has to round-trip to the server: // On the client: var EnabledItems = new Meteor.Collection("enabled_items"); var ProcessedItems = new Meteor.Collection("processed_items"); With the monkey-patch in place, this will work. But go into Offline mode and changes won't appear on the client right away -- we'll need to be connected to the server to see changes. What's the correct approach?

    Read the article

  • JPA Database strcture for internationalisation

    - by IrishDubGuy
    I am trying to get a JPA implementation of a simple approach to internationalisation. I want to have a table of translated strings that I can reference in multiple fields in multiple tables. So all text occurrences in all tables will be replaced by a reference to the translated strings table. In combination with a language id, this would give a unique row in the translated strings table for that particular field. For example, consider a schema that has entities Course and Module as follows :- Course int course_id, int name, int description Module int module_id, int name The course.name, course.description and module.name are all referencing the id field of the translated strings table :- TranslatedString int id, String lang, String content That all seems simple enough. I get one table for all strings that could be internationalised and that table is used across all the other tables. How might I do this in JPA, using eclipselink 2.4? I've looked at embedded ElementCollection, ala this... JPA 2.0: Mapping a Map - it isn't exactly what i'm after cos it looks like it is relating the translated strings table to the pk of the owning table. This means I can only have one translatable string field per entity (unless I add new join columns into the translatable strings table, which defeats the point, its the opposite of what I am trying to do). I'm also not clear on how this would work across entites, presumably the id of each entity would have to use a database wide sequence to ensure uniqueness of the translatable strings table. BTW, I tried the example as laid out in that link and it didn't work for me - as soon as the entity had a localizedString map added, persisting it caused the client side to bomb but no obvious error on the server side and nothing persisted in the DB :S I been around the houses on this about 9 hours so far, I've looked at this Internationalization with Hibernate which appears to be trying to do the same thing as the link above (without the table definitions it hard to see what he achieved). Any help would be gratefully achieved at this point... Edit 1 - re AMS anwser below, I'm not sure that really addresses the issue. In his example it leaves the storing of the description text to some other process. The idea of this type of approach is that the entity object takes the text and locale and this (somehow!) ends up in the translatable strings table. In the first link I gave, the guy is attempting to do this by using an embedded map, which I feel is the right approach. His way though has two issues - one it doesn't seem to work! and two if it did work, it is storing the FK in the embedded table instead of the other way round (I think, I can't get it to run so I can't see exactly how it persists). I suspect the correct approach ends up with a map reference in place of each text that needs translating (the map being locale-content), but I can't see how to do this in a way that allows for multiple maps in one entity (without having corresponding multiple columns in the translatable strings table)...

    Read the article

  • MySQL multiple dependent subqueries, painfully slow

    - by matt80
    I have a working query that retrieves the data that I need, but unfortunately it is painfully slow (runs over 3 minutes). I have indexes in place, but I think the problem is the multiple dependent subqueries. I've been trying to rewrite the query using joins but I can't seem to get it to work. Any help would be greatly appreciated. The tables: Basically, I have 2 tables. The first (prices) holds the prices of items in a store. Each row is the price of an item that day, and new rows are added every day with an updated price. The second table (watches_US) holds the item information (name, description, etc). CREATE TABLE `prices` ( `prices_id` int(11) NOT NULL auto_increment, `prices_locale` enum('CA','DE','FR','JP','UK','US') NOT NULL default 'US', `prices_watches_ID` char(10) NOT NULL, `prices_date` datetime NOT NULL, `prices_am` varchar(10) default NULL, `prices_new` varchar(10) default NULL, `prices_used` varchar(10) default NULL, PRIMARY KEY (`prices_id`), KEY `prices_am` (`prices_am`), KEY `prices_locale` (`prices_locale`), KEY `prices_watches_ID` (`prices_watches_ID`), KEY `prices_date` (`prices_date`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=61764 ; CREATE TABLE `watches_US` ( `watches_ID` char(10) NOT NULL, `watches_date_added` datetime NOT NULL, `watches_last_update` datetime default NULL, `watches_title` varchar(255) default NULL, `watches_small_image_height` int(11) default NULL, `watches_small_image_width` int(11) default NULL, `watches_description` text, PRIMARY KEY (`watches_ID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; The query retrieves the last 10 prices changes over a period of 30 hours, ordered by the size of the price change. So I have subqueries to get the newest price, the oldest price within 30 hours, and then to calculate the price change. Here's the query: SELECT watches_US.*, prices.*, watches_US.watches_ID as current_ID, ( SELECT prices_am FROM prices WHERE prices_watches_ID = current_ID AND prices_locale = 'US' ORDER BY prices_date DESC LIMIT 1 ) as new_price, ( SELECT prices_date FROM prices WHERE prices_watches_ID = current_ID AND prices_locale = 'US' ORDER BY prices_date DESC LIMIT 1 ) as new_price_date, ( SELECT prices_am FROM prices WHERE ( prices_watches_ID = current_ID AND prices_locale = 'US') AND ( prices_date >= DATE_SUB(new_price_date,INTERVAL 30 HOUR) ) ORDER BY prices_date ASC LIMIT 1 ) as old_price, ( SELECT ROUND(((new_price - old_price)/old_price)*100,2) ) as percent_change, ( SELECT (new_price - old_price) ) as absolute_change FROM watches_US LEFT OUTER JOIN prices ON prices.prices_watches_ID = watches_US.watches_ID WHERE ( prices_locale = 'US' ) AND ( prices_am IS NOT NULL ) AND ( prices_am != '' ) HAVING ( old_price IS NOT NULL ) AND ( old_price != 0 ) AND ( old_price != '' ) AND ( absolute_change < 0 ) AND ( prices.prices_date = new_price_date ) ORDER BY absolute_change ASC LIMIT 10 How would I rewrite this to use joins instead, or otherwise optimize this so it doesn't take over 3 minutes to get a result? Any help would be greatly appreciated! Thank you kindly.

    Read the article

< Previous Page | 60 61 62 63 64 65 66 67 68 69 70 71  | Next Page >