Search Results

Search found 3425 results on 137 pages for 'polynomial math'.

Page 128/137 | < Previous Page | 124 125 126 127 128 129 130 131 132 133 134 135  | Next Page >

  • Building a DataTable in C# with one column at a time

    - by Awaken
    I am trying to build a Retirement Calculator as a chance to make something useful and learn C# better. Currently, I am trying to build a DataTable with a dynamic amount of rows/columns. For context, I ask the user for some inputs regarding salary, % of salary being invested, and expected ROI. I have some other stuff too, but it isn't really part of the issue I am having. Because the number of columns I need for the DataTable is unknown until the formula is run (while+for loop completes), I am having trouble doing things as DataColumns. Hopefully the code below will help. I am really trying to build the table one column at a time. I realize I could reverse it to build it one row at a time because the Years before retirement (yearsRetire) is known, but I would prefer not to and I want to learn more. Sorry for the indentation and commenting. I tried to leave some of my commented coding attempts in there. Thanks for any help. public double calcROI() { double testROI = 0.00; double tempRetireAmount = 0; double adjustRetire = goalAmount * (1 + (Math.Pow(inflation,yearsRetire))); // Loop through ROI values until the calculated retire amount with the test ROI // is greater than the target amount adjusted for inflation while (tempRetireAmount < adjustRetire) { //Increment ROI by 1% per while iteration testROI += .01; //Make a new Column to hold the values for ROI for this while iteration //dtMain.Columns.Add(Convert.ToString(testROI)); //DataColumn tempdc = new DataColumn(Convert.ToString(testROI)); //Loop through the number of years entered by user and see the amount //at Retirement with current ROI for (int i = 0; i < yearsRetire; i++) { //Main formula to calculate amount after i years tempRetireAmount = (tempRetireAmount + salary*savingsPct) * (1 + testROI); // Add value for this year/ROI to table/column //DataRow dr = .NewRow(); //dr tempRetireAmount; //tempdc[i] = tempRetireAmount; } //Need to add column of data to my Main DataTable //dtMain.Rows.Add(dr); //dtMain.Columns.Add(tempdc); } return testROI; }

    Read the article

  • Jquery help : How to implement a Previous/Next & Play/Pause toggle for this script

    - by rameshelamathi
    (function($){ // Creating the sweetPages jQuery plugin: $.fn.sweetPages = function(opts){ // If no options were passed, create an empty opts object if(!opts) opts = {}; var resultsPerPage = opts.perPage || 3; var swDiv = opts.getSwDiv || "swControls"; // The plugin works best for unordered lists, althugh ols would do just as well: var ul = this; var li = ul.find('li'); li.each(function(){ // Calculating the height of each li element, and storing it with the data method: var el = $(this); el.data('height',el.outerHeight(true)); }); // Calculating the total number of pages: var pagesNumber = Math.ceil(li.length/resultsPerPage); // If the pages are less than two, do nothing: if(pagesNumber<2) return this; // Creating the controls div: //var swControls = $('<div class="swControls">'); var swControls = $('<div class='+swDiv+'>'); for(var i=0;i<pagesNumber;i++) { // Slice a portion of the lis, and wrap it in a swPage div: li.slice(i*resultsPerPage,(i+1)*resultsPerPage).wrapAll('<div class="swPage" />'); // Adding a link to the swControls div: swControls.append('<a href="" class="swShowPage">'+(i+1)+'</a>'); } ul.append(swControls); var maxHeight = 0; var totalWidth = 0; var swPage = ul.find('.swPage'); swPage.each(function(){ // Looping through all the newly created pages: var elem = $(this); var tmpHeight = 0; elem.find('li').each(function(){tmpHeight+=$(this).data('height');}); if(tmpHeight>maxHeight) maxHeight = tmpHeight; totalWidth+=elem.outerWidth(); elem.css('float','left').width(ul.width()); }); swPage.wrapAll('<div class="swSlider" />'); // Setting the height of the ul to the height of the tallest page: //ul.height(maxHeight); var swSlider = ul.find('.swSlider'); swSlider.append('<div class="clear" />').width(totalWidth); var hyperLinks = ul.find('a.swShowPage'); hyperLinks.click(function(e){ // If one of the control links is clicked, slide the swSlider div // (which contains all the pages) and mark it as active: $(this).addClass('active').siblings().removeClass('active'); swSlider.stop().animate({'margin-left':-(parseInt($(this).text())-1)*ul.width()},'slow'); e.preventDefault(); }); // Mark the first link as active the first time this code runs: hyperLinks.eq(0).addClass('active'); // Center the control div: swControls.css({ 'right':'10%', 'margin-left':-swControls.width()/2 }); return this; }})(jQuery);

    Read the article

  • Save/Load jFreechart TimeSeriesCollection chart from XML

    - by IMAnis_tn
    I'm working with this exemple wich put rondom dynamic data into a TimeSeriesCollection chart. My problem is that i can't find how to : 1- Make a track of the old data (of the last hour) when they pass the left boundary (because the data point move from the right to the left ) of the view area just by implementing a horizontal scroll bar. 2- Is XML a good choice to save my data into when i want to have all the history of the data? public class DynamicDataDemo extends ApplicationFrame { /** The time series data. */ private TimeSeries series; /** The most recent value added. */ private double lastValue = 100.0; public DynamicDataDemo(final String title) { super(title); this.series = new TimeSeries("Random Data", Millisecond.class); final TimeSeriesCollection dataset = new TimeSeriesCollection(this.series); final JFreeChart chart = createChart(dataset); final ChartPanel chartPanel = new ChartPanel(chart); final JPanel content = new JPanel(new BorderLayout()); content.add(chartPanel); chartPanel.setPreferredSize(new java.awt.Dimension(500, 270)); setContentPane(content); } private JFreeChart createChart(final XYDataset dataset) { final JFreeChart result = ChartFactory.createTimeSeriesChart( "Dynamic Data Demo", "Time", "Value", dataset, true, true, false ); final XYPlot plot = result.getXYPlot(); ValueAxis axis = plot.getDomainAxis(); axis.setAutoRange(true); axis.setFixedAutoRange(60000.0); // 60 seconds axis = plot.getRangeAxis(); axis.setRange(0.0, 200.0); return result; } public void go() { final double factor = 0.90 + 0.2 * Math.random(); this.lastValue = this.lastValue * factor; final Millisecond now = new Millisecond(); System.out.println("Now = " + now.toString()); this.series.add(new Millisecond(), this.lastValue); } public static void main(final String[] args) throws InterruptedException { final DynamicDataDemo demo = new DynamicDataDemo("Dynamic Data Demo"); demo.pack(); RefineryUtilities.centerFrameOnScreen(demo); demo.setVisible(true); while(true){ demo.go(); Thread.currentThread().sleep(1000); } } }

    Read the article

  • Structures not working correctly?

    - by booby
    Fraction AddFractions(const Fraction& frac1, const Fraction& frac2) { Fraction frac3; if (frac1.denom == frac2.denom) { frac3.num = frac1.num + frac2.num; frac3.denom = frac1.denom; } else { frac3.denom = (frac1.denom * frac2.denom); frac3.num = (frac1.num * frac2.denom) + (frac2.num * frac1.denom); } return frac3; } This is my prototype and there is a structure defined as Fraction with int num and int denom when I call the function it just gives me back garbage? I don't know what's wrong with it. Please help. =( cout << "Please enter two Fractions" << endl; cout << endl; GetFraction(frac1); cout << "Your fisrt fraction is: "; PrintFraction(frac1); cout << endl; cout << endl; GetFraction(frac2); cout << "Your second fraction is: "; PrintFraction(frac2); cout << endl; do { choice1 = MathMenu(); if (choice1 == ErrorOpt) { cout << "There was an error with what you have entered" << endl; } else if(choice1 != QuitOpt) { // do the math options switch (choice1) { case AddOpt: AddFractions(frac1, frac2); break; case SubtractOpt: SubtractFractions(frac1, frac2); break; case MultiplyOpt: MultiplyFractions(frac1, frac2); break; case DivideOpt: DivideFractions(frac1, frac2); break; } //print the results PrintFraction(frac1); PrintMathOption(choice1); PrintFraction(frac2); cout << " = "; Standardize(frac3); Reduce(frac3); PrintFraction(frac3); cout << endl; Pause();

    Read the article

  • Making an efficient algorithm

    - by James P.
    Here's my recent submission for the FB programming contest (qualifying round only requires to upload program output so source code doesn't matter). The objective is to find two squares that add up to a given value. I've left it as it is as an example. It does the job but is too slow for my liking. Here's the points that are obviously eating up time: List of squares is being recalculated for each call of getNumOfDoubleSquares(). This could be precalculated or extended when needed. Both squares are being checked for when it is only necessary to check for one (complements). There might be a more efficient way than a double-nested loop to find pairs. Other suggestions? Besides this particular problem, what do you look for when optimizing an algorithm? public static int getNumOfDoubleSquares( Integer target ){ int num = 0; ArrayList<Integer> squares = new ArrayList<Integer>(); ArrayList<Integer> found = new ArrayList<Integer>(); int squareValue = 0; for( int j=0; squareValue<=target; j++ ){ squares.add(j, squareValue); squareValue = (int)Math.pow(j+1,2); } int squareSum = 0; System.out.println( "Target=" + target ); for( int i = 0; i < squares.size(); i++ ){ int square1 = squares.get(i); for( int j = 0; j < squares.size(); j++ ){ int square2 = squares.get(j); squareSum = square1 + square2; if( squareSum == target && !found.contains( square1 ) && !found.contains( square2 ) ){ found.add(square1); found.add(square2); System.out.println( "Found !" + square1 +"+"+ square2 +"="+ squareSum); num++; } } } return num; }

    Read the article

  • StringIndexOutOfBoundsException: String index out of range 0

    - by Evan F
    I'm trying to write a program to take the first letter of the user input to generate a username. I'm trying to write it so that if the user leaves the input blank, then the letter that would otherwise be taken to generate the username defaults to the letter 'z'. Here is my full code: import java.util.Scanner; /** UsernameGenerator.java Generates a username based on the users inputs. @author: Evan Fravert */ public class UsernameGenerator { /** * Generates a username based on the users inputs. *@param args command line argument */ public static void main(String[] args) { // abcde String first; String middle; String last; String password1; String password2; int randomNum; randomNum = (int) (Math.random() * 1000) + 100; Scanner userInput = new Scanner(System.in); System.out.println("Please enter your first name:"); first = userInput.nextLine(); String firstLower = first.toLowerCase(); System.out.println("Please enter your middle name:"); middle = userInput.nextLine(); String middleLower = middle.toLowerCase(); System.out.println("Please enter your last name:"); last = userInput.nextLine(); int lastEnd = last.length()-1; String lastLower = last.toLowerCase(); System.out.println("Please enter your password:"); password1 = userInput.nextLine(); System.out.println("Please enter your password again:"); password2 = userInput.nextLine(); char firstLetter = firstLower.charAt(0); char middleLetter = middleLower.charAt(0); char lastLetter = lastLower.charAt(0); char lastLast = lastLower.charAt(lastEnd); if first.length() == 0) { firstLetter = 'z'; } else { firstLetter = firstLower.charAt(0); } System.out.println("Your username is " + firstLetter + "" + middleLetter + "" + lastLetter + "" + "" + lastLast + "" + randomNum); System.out.println("Your password is " + password1); System.out.println("Welcome " + first + " " + middle + " " + last + "!"); } }

    Read the article

  • Is it possible to make JQuery keydown respond faster?

    - by Drew Paul
    I am writing a simple page with JQuery and HTML5 canvas tags where I move a shape on the canvas by pressing 'w' for up, 's' for down, 'a' for left, and 'd' for right. I have it all working, but I would like the shape to start moving at a constant speed upon striking a key. Right now there is some kind of hold period and then the movement starts. How can I get the movement to occur immediately? Here the important part of my code: Your browser does not support the HTML5 canvas tag. start navigating coords should pop up here key should pop up here var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); //keypress movements var xtriggered = 0; var keys = {}; var north = -10; var east = 10; var flipednorth = 0; $(document).ready(function(e){ $("input").keydown(function(){ keys[event.which] = true; if (event.which == 13) { event.preventDefault(); } //press w for north if (event.which == 87) { north++; flipednorth--; } //press s for south if (event.which == 83) { north--; flipednorth++; } //press d for east if (event.which == 68) { east++; } //press a for west if (event.which == 65) { east--; } var msg = 'x: ' + flipednorth*5 + ' y: ' + east*5; ctx.beginPath(); ctx.arc(east*6,flipednorth*6,40,0,2*Math.PI); ctx.stroke(); $('#soul2').html(msg); $('#soul3').html(event.which ); $("input").css("background-color","#FFFFCC"); }); $("input").keyup(function(){ delete keys[event.which]; $("input").css("background-color","#D6D6FF"); }); }); </script> please let me know if I shouldn't be posting code this lengthy.

    Read the article

  • Replace text in XSL using wildcards

    - by JosephThomas
    This is similar to an earlier problem I was having which you guys solved in less than a day. I am working with XML files that are generated by a digital video camera. The camera allows the user to save all of the camera's settngs to an SD card so that the settings can be recalled or loaded into another camera. The XSL stylesheet I am writing will allow users to view the camera's settings, as saved to the SD card in a web browser. While most of the values in the XML file -- as formatted by my stylesheet -- make sense to humans, some do not. What I would like to do is have the stylesheet display text that is based on the value in the XML file but more easily understood by humans. A typical value that can be written to the XML file is "_23_970" which represents the camera's frame rate. This would be better displayed as 23.970 (or 023.970). The first underscore is a sort of place holder to make a space for values over 099.999. The second underscore, obviously represents the decimal. My previous (similar) question involved replacing predictable text, and the solution was matching templates. In this case, however, the camera can be set at any one of 119,999 frame rates (I think I did that math correctly). The approach, I would guess, is to pass a value to the displayed webpage that keeps the numeric values (each digit), replaces the second underscore with a decimal, and replaces the first underscore with either an nbsp or a zero (whichever is easier). If the first character in the string is a "1" (the camera can run at frame rates up to 120.000) then the one should be passed on to the page displayed by the stylesheet. I have read other posts here regarding wildcards, but couldn't find one that answered this question. EDIT: Sorry for leaving out important info. I fared better on my first try at asking a question! I guess I got complacent. Anyhow . . . I should have shown you the code that displays the text in the XSL file as is: <tr> <xsl:for-each select="Settings/Groups/Recording"> <tr><td class="title_column">Frame Rate</td><td><xsl:value-of select="RecOutLinkSpeed"/></td></tr> </xsl:for-each> </tr> I should also have given you the URL for the sample file I have been working with: http://josephthomas.info/Alexa/Setup_120511_140322.xml

    Read the article

  • Should we use temporary variables for the returned values of functions?

    - by totymedli
    I thought about this: Is there a performance difference in these two practices: Store the return value of a function in a temporary variable than give that variable as a parameter to another function. Put the function into the other function. Specification Assuming all classes and functions are written correctly. Case 1. ClassA a = function1(); ClassB b = function2(a); function3(b); Case 2. function3(function2(function1())); I know there aren't a big difference with only one run, but supposed that we could run this a lot of times in a loop, I created some tests. Test #include <iostream> #include <ctime> #include <math.h> using namespace std; int main() { clock_t start = clock(); clock_t ends = clock(); // Case 1. start = clock(); for (int i=0; i<10000000; i++) { double a = cos(1); double b = pow(a, 2); sqrt(b); } ends = clock(); cout << (double) (ends - start) / CLOCKS_PER_SEC << endl; // Case 2. start = clock(); for (int i=0; i<10000000; i++) sqrt(pow(cos(1),2)); ends = clock(); cout << (double) (ends - start) / CLOCKS_PER_SEC << endl; return 0; } Results Case 1 = 6.375 Case 2 = 0.031 Why is the first one is much slower, and if the second one is faster why dont we always write code that way? Anyway does the second pratice has a name? I also wondered what happens if I create the variables outside the for loop in the first case, but the result was the same. Why?

    Read the article

  • jQuery Sales Tax

    - by CKallemeres
    Hello everyone! I have created a function (see below) that calculates a 7.5% sales tax. Now I need help doing the following: Have totalTax() take in 2 arguments one for the price and one for the tax. On submit (use the onSubmit event handler to call this function) have the function process the price and the tax by manipulating the arguments you passed in. Have the sales tax on the page update dynamically with what ever the sales tax is that you defined for the function 7.5 percent sales tax: Instead of using .innerHTML use jQuery to access these document elements and write to them: document.getElementById('requestedAmount' ).innerHTML = priceInput; document.getElementById('requestedTax' ).innerHTML = salesTax; document.getElementById('requestedTotal' ).innerHTML = totalAmount; Original Code: <script type="text/javascript"> $().ready(function() { // validate the comment form when it is submitted $("#inputForm").validate(); $("#priceInput").priceFormat({ prefix: '', limit: 5, centsLimit: 2 }); }); function totalTax(){ var priceInput = document.getElementById( 'priceInput' ).value; var salesTax = Math.round(((priceInput / 100) * 7.5)*100)/100; var totalAmount = (priceInput*1) + (salesTax * 1); document.getElementById( 'requestedAmount' ).innerHTML = priceInput; document.getElementById( 'requestedTax' ).innerHTML = salesTax; document.getElementById( 'requestedTotal' ).innerHTML = totalAmount; } </script> <body> <form class="cmxform" id="inputForm" method="get" action=""> <p> <label for="priceInput">Enter the price: </label> <input id="priceInput" name="name" class="required"/> </p> <p> <input class="submit" type="submit" value="Submit" onclick="totalTax();"/> </p> </form> <div>Entered price: <p id="requestedAmount"></p> </div> <div>7.5 percent sales tax: <p id="requestedTax"></p> </div> <div>Total: <p id="requestedTotal"> </p> </div>

    Read the article

  • Numpy/Python performing terribly vs. Matlab

    - by Nissl
    Novice programmer here. I'm writing a program that analyzes the relative spatial locations of points (cells). The program gets boundaries and cell type off an array with the x coordinate in column 1, y coordinate in column 2, and cell type in column 3. It then checks each cell for cell type and appropriate distance from the bounds. If it passes, it then calculates its distance from each other cell in the array and if the distance is within a specified analysis range it adds it to an output array at that distance. My cell marking program is in wxpython so I was hoping to develop this program in python as well and eventually stick it into the GUI. Unfortunately right now python takes ~20 seconds to run the core loop on my machine while MATLAB can do ~15 loops/second. Since I'm planning on doing 1000 loops (with a randomized comparison condition) on ~30 cases times several exploratory analysis types this is not a trivial difference. I tried running a profiler and array calls are 1/4 of the time, almost all of the rest is unspecified loop time. Here is the python code for the main loop: for basecell in range (0, cellnumber-1): if firstcelltype == np.array((cellrecord[basecell,2])): xloc=np.array((cellrecord[basecell,0])) yloc=np.array((cellrecord[basecell,1])) xedgedist=(xbound-xloc) yedgedist=(ybound-yloc) if xloc>excludedist and xedgedist>excludedist and yloc>excludedist and yedgedist>excludedist: for comparecell in range (0, cellnumber-1): if secondcelltype==np.array((cellrecord[comparecell,2])): xcomploc=np.array((cellrecord[comparecell,0])) ycomploc=np.array((cellrecord[comparecell,1])) dist=math.sqrt((xcomploc-xloc)**2+(ycomploc-yloc)**2) dist=round(dist) if dist>=1 and dist<=analysisdist: arraytarget=round(dist*analysisdist/intervalnumber) addone=np.array((spatialraw[arraytarget-1])) addone=addone+1 targetcell=arraytarget-1 np.put(spatialraw,[targetcell,targetcell],addone) Here is the matlab code for the main loop: for basecell = 1:cellnumber; if firstcelltype==cellrecord(basecell,3); xloc=cellrecord(basecell,1); yloc=cellrecord(basecell,2); xedgedist=(xbound-xloc); yedgedist=(ybound-yloc); if (xloc>excludedist) && (yloc>excludedist) && (xedgedist>excludedist) && (yedgedist>excludedist); for comparecell = 1:cellnumber; if secondcelltype==cellrecord(comparecell,3); xcomploc=cellrecord(comparecell,1); ycomploc=cellrecord(comparecell,2); dist=sqrt((xcomploc-xloc)^2+(ycomploc-yloc)^2); if (dist>=1) && (dist<=100.4999); arraytarget=round(dist*analysisdist/intervalnumber); spatialsum(1,arraytarget)=spatialsum(1,arraytarget)+1; end end end end end end Thanks!

    Read the article

  • Calendar Day View in PHP

    - by JamesArmes
    I'm working on adding a day view option to an existing calendar solution. Like many people implementing their own calendars, I am trying to model Google Calendars. They have an excellent calendar solution and their day view provides a lot of flexibility. For most part, the implementation is going well; however, I'm having issues when it comes to conflicting events. Essentially, I want the events to share the same space, side by side. Events that start at the same time should have the longest event first. In the example data set I'm working with, I have four events: A: 10:30 - 11:30 B: 13:30 - 14:30 C: 10:30 - 11:00 D: 10:45 - 14:00 I can handle A, C, and D just fine, the problem comes with D. A should be left of C which should be left of D; each taking one third of the width (it's fixed width so I can do simple math to figure that out). The problem is that B should be under A and C, to the left of D. Ideally, B would take up the same amount of space as A and C (two thirds width), but I would even settle for it only taking up only one third width. My array of events looks similar to the following: $events = array( '1030' => array( 'uniqueID1' => array( 'start_time' => '1030', 'end_time' => '1130', ), 'uniqueID2' => array( 'start_time' => '1030', 'end_time' => '1100', ), ), '1045' => array( 'uniqueID3' => array( 'start_time' => '1045', 'end_time' => '1400', ), ), '1330' => array( 'uniqueID3' => array( 'start_time' => '1330', 'end_time' => '1430', ), ), ); My plan is to add some indexes to each event that include how many events it conflicts with (so I can calculate the width) and which position in that series it should be (so I can calculate the left value). However, that doesn't help the B. I'm thinking I might need an algorithm that uses some basic geometry and matrices, but I'm not sure where to begin. Any help is greatly appreciated.

    Read the article

  • java nested for() loop throws ArrayIndexOutOfBoundsException

    - by Mike
    I'm working through a JPanel exercise in a Java book. I'm tasked with creating a 5x4 grid using GridLayout. When I loop through the container to add panels and buttons, the first add() throws the OOB exception. What am I doing wrong? package mineField; import java.awt.*; import javax.swing.*; @SuppressWarnings("serial") public class MineField extends JFrame { private final int WIDTH = 250; private final int HEIGHT = 120; private final int MAX_ROWS = 5; private final int MAX_COLUMNS = 4; public MineField() { super("Minefield"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container mineFieldGrid = getContentPane(); mineFieldGrid.setLayout(new GridLayout(MAX_ROWS, MAX_COLUMNS)); // loop through arrays, add panels, then add buttons to panels. for (int i = 0; i < MAX_ROWS; i++) { JPanel[] rows = new JPanel[i]; mineFieldGrid.add(rows[i], rows[i].getName()); rows[i].setBackground(Color.blue); for (int j = 0; j < MAX_COLUMNS; j++) { JButton[] buttons = new JButton[i]; rows[i].add(buttons[j], buttons[j].getName()); } } mineFieldGrid.setSize(WIDTH, HEIGHT); mineFieldGrid.setVisible(true); } public int setRandomBomb(Container con) { int bombID; bombID = (int) (Math.random() * con.getComponentCount()); return bombID; } /** * @param args */ public static void main(String[] args) { //int randomBomb; //JButton bombLocation; MineField minePanel = new MineField(); //minePanel[randomBomb] = minePanel.setRandomBomb(minePanel); } } I'm sure I'm over-engineering a simple nested for loop. Since I'm new to Java, please be kind. I'm sure I'll return the favor some day.

    Read the article

  • Calling compiled C from R with .C()

    - by Sarah
    I'm trying to call a program (function getNBDensities in the C executable measurementDensities_out) from R. The function is passed several arrays and the variable double runsum. Right now, the getNBDensities function basically does nothing: it prints to screen the values of passed parameters. My problem is the syntax of calling the function: array(.C("getNBDensities", hr = as.double(hosp.rate), # a vector (s x 1) sp = as.double(samplingProbabilities), # another vector (s x 1) odh = as.double(odh), # another vector (s x 1) simCases = as.integer(x[c("xC1","xC2","xC3")]), # another vector (s x 1) obsCases = as.integer(y[c("yC1","yC2","yC3")]), # another vector (s x 1) runsum = as.double(runsum), # double DUP = TRUE, NAOK = TRUE, PACKAGE = "measurementDensities_out")$f, dim = length(y[c("yC1","yC2","yC3")]), dimnames = c("yC1","yC2","yC3")) The error I get, after proper execution of the function (i.e., the right output is printed to screen), is Error in dim(data) <- dim : attempt to set an attribute on NULL I'm unclear what the dimensions are that I should be passing the function: should it be s x 5 + 1 (five vectors of length s and one double)? I've tried all sorts of combinations (including sx5+1) and have found only seemingly conflicting descriptions/examples online of what's supposed to happen here. For those who are interested, the C code is below: #include <R.h> #include <Rmath.h> #include <math.h> #include <Rdefines.h> #include <R_ext/PrtUtil.h> #define NUM_STRAINS 3 #define DEBUG void getNBDensities( double *hr, double *sp, double *odh, int *simCases, int *obsCases, double *runsum ); void getNBDensities( double *hr, double *sp, double *odh, int *simCases, int *obsCases, double *runsum ) { #ifdef DEBUG for ( int s = 0; s < NUM_STRAINS; s++ ) { Rprintf("\nFor strain %d",s); Rprintf("\n\tHospitalization rate = %lg", hr[s]); Rprintf("\n\tSimulation probability = %lg",sp[s]); Rprintf("\n\tSimulated cases = %d",simCases[s]); Rprintf("\n\tObserved cases = %d",obsCases[s]); Rprintf("\n\tOverdispersion parameter = %lg",odh[s]); } Rprintf("\nRunning sum = %lg",runsum[0]); #endif } naive solution While better (i.e., potentially faster or syntactically clearer) solutions may exist (see Dirk's answer below), the following simplification of the code works: out<-.C("getNBDensities", hr = as.double(hosp.rate), sp = as.double(samplingProbabilities), odh = as.double(odh), simCases = as.integer(x[c("xC1","xC2","xC3")]), obsCases = as.integer(y[c("yC1","yC2","yC3")]), runsum = as.double(runsum)) The variables can be accessed in >out.

    Read the article

  • Submitting form in php file accessed by Ajax?

    - by dronnoc
    Hi people, I am trying to figure out how to submit a form in a page being accessed by Ajax? here are some code snippets to help demonstrate what i am trying to say. HTML BODY - THIS IS WHAT THE USER WILL SEE. <html> <head> <script language="javascript" src="linktoajaxfile.js"> </head> <body onLoad="gotoPage(0)"> <div id="fillThis"> </div> </body> </html> AJAX FILE var xmlhttp function gotoPage(phase) { xmlhttp=GetXmlHttpObject(); if (xmlhttp==null) { alert ("Your browser does not support AJAX!"); return; } var url="pageofstuffce.php"; url=url+"?stg="+phase; url=url+"&sid="+Math.random(); xmlhttp.onreadystatechange=stateChanged; xmlhttp.open("GET",url,true); xmlhttp.send(null); } function stateChanged() { if (xmlhttp.readyState==4) { document.getElementById("fillThis").innerHTML=xmlhttp.responseText; } } function GetXmlHttpObject() { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari return new XMLHttpRequest(); } if (window.ActiveXObject) { // code for IE6, IE5 return new ActiveXObject("Microsoft.XMLHTTP"); } return null; } PAGE OF DATA <?php $stage = $_GET['stg']; if($stage == 0) { echo '<a onClick="gotoPage(1)">click me</a>'; } elseif($stage == 1) { <form> <input type="text" name="name"> <input type="submit" name="submit"> </form> } elseif(somehow can reach here) { show data from form. } ?> Can anyone perhaps help me get past the form and display the data in the same page? Also, i have looked around, and i don't think anything around has what i need... correct me if i'm wrong though :) Thanks in advance, and i hope i didn't put in too much detail :) Dronnoc EDIT Forgot to mention what I've tried; I have tried submitting the form to itself (same file) and that destroyed the ajax link, and opened the page. i have also tried just having the button move the page onto another step, but the $_POST variable is empty... i am at a loss, so does anyone else have any ideas?

    Read the article

  • JavaScript Coding for Finding Shipping Total

    - by user2913279
    I am having a very hard time with this code. I have been working on it for days and cannot seem to figure it out. Please help!! Here are the specific I need for the code: Many companies normally charge a shipping and handling charge for purchases. Create a Web page that allows a user to enter a purchase price into a text box and includes a JavaScript function that calculates shipping and handling. Add functionality to the script that adds a minimum shipping and handling charge of $1.50 for any purchase that is less than or equal to $25.00. For any orders over $25.00, add 10% to the total purchase price for shipping and handling, but do not include the $1.50 minimum shipping and handling charge. The formula for calculating a percentage is price * percent / 100. For example, the formula for calculating 10% of a $50.00 purchase price is 50 * 10 / 100, which results in a shipping and handling charge of $5.00. After you determine the total cost of the order (purchase plus shipping and handling), display it in an alert dialog box. Here is the code I have: <!DOCTYPE> <head> <title>Calculate Shipping</title> <script type="text/javascript"> function parseInt() { var salesPrice = document.salesForm.Price.value; var minCharge = salesPrice + 1.50; var shipping = salesPrice * 10/100; if (salesPrice <= 25) window.alert('Your sales total including shipping is $' + minCharge); else window.alert('Your sales total including shipping is $' + salesPrice + shipping); } </script> </head> <body> <form name="salesForm"> <div > <p>Enter Your Purchase Price</p> <input type="text" name="Price" /><br /><br /> <input type="button" name="Calculate" value="Calculate Shipping" onclick="parseInt ()" /> </div> </form> </body> </html> Everything works except for the math in the alert box. It will show an incorrect total...

    Read the article

  • No warning from gcc when function definition in linked source different from function prototype in h

    - by c_c
    Hi, I had a problem with a part of my code, which after some iterations seemed to read NaN as value of a int of a struct. I think I found the error, but am still wondering why gcc (version 3.2.3 on a embedded Linux with busybox) did not warn me. Here are the important parts of the code: A c file and its header for functions to acquire data over USB: // usb_control.h typedef struct{ double mean; short *values; } DATA_POINTS; typedef struct{ int size; DATA_POINTS *channel1; //....7 more channels } DATA_STRUCT; DATA_STRUCT *create_data_struct(int N); // N values per channel int free_data_struct(DATA_STRUCT *data); int aqcu_data(DATA_STRUCT *data, int N); A c and header file with helper function (math, bitshift,etc...): // helper.h int mean(DATA_STRUCT *data); // helper.c (this is where the error is obviously) double mean(DATA_STRUCT *data) { // sum in for loop data->channel1->mean = sum/data->N; // ...7 more channels // a printf here displayed the mean values corretly } The main file // main.c #include "helper.h" #include "usb_control.h" // Allocate space for data struct DATA_STRUCT *data = create_data_struct(N); // get data for different delays for (delay = 0; delay < 500; delay += pw){ acqu_data(data, N); mean(data); // printf of the mean values first is correct. Than after 5 iterations // it is always NaN for channel1. The other channels are displayed correctly; } There were no segfaults nor any other missbehavior, just the NaN for channel1 in the main file. After finding the error, which was not easy, it was of course east to fix. The return type of mean(){} was wrong in the definition. Instead of double mean() it has to be int mean() as the prototype defines. When all the functions are put into one file, gcc warns me that there is a redefinition of the function mean(). But as I compile each c file seperately and link them afterwards gcc seems to miss that. So my questions would be. Why didn't I get any warnings, even non with gcc -Wall? Or is there still another error hidden which is just not causing problems now? Regards, christian

    Read the article

  • string and z-depth animation, as3

    - by VideoDnd
    How do I pass this string to my children? formatCount(fcount) is the value I'm trying to pass to children timer is the value the children are recieving now Timer that loops through an array of displayObjects var timer:Timer = new Timer(100); var count:int = 0; var fcount:int = 0; timer.addEventListener(TimerEvent.TIMER, countdown); function countdown(event:TimerEvent) { count++; fcount=int(count*count/1000); //myText.text = formatCount(fcount); //LOOPS THROUGH MY LIST ITEMS 'see array at bottom' var currentFrame:int = timer.currentCount % frames.length; for (var i:int = 0; i < frames.length; ++i) { frames[i].visible = (i == currentFrame); } } timer.start(); //SUBSTRING AND ZERO PLACEHOLDER function formatCount(i:int):String { var fraction:int = i % 100; var whole:int = i / 100; return ("0000000" + whole).substr(-7, 7) + "." + (fraction < 10 ? "0" + fraction : fraction); } //PASS MATH TO SPRITE HANDLER function spriteHandler(e:Event):void { numbers.setTime(formatCount(fcount)); } //LOST ARGUMENT==>GOES TO NUMBERSVIEW //var numbers:NumbersView; var numbers:*; //MY ARRAY 'list of numbers, one-to-zero' var frames:Array = [new Frame1(),new Frame2(),new Frame3(), new Frame4(),new Frame5(),new Frame6(),new Frame7(),new Frame8(),new Frame9(), new Frame0()]; for each (var frame:Sprite in frames) { addChild(frame); } Example of NumbersView 'increment and place display objects across the stage' function NumbersView() { _listItems = new Array(); previousNums = new Array(); var item:NumberImage; for (var i:Number = 0; i <= 9; i++) { item = new NumberImage(); addChild(item); item.x = i * item.width; _listItems.push(item); } }

    Read the article

  • Indexing with pointer C/C++

    - by Leavenotrace
    Hey I'm trying to write a program to carry out newtons method and find the roots of the equation exp(-x)-(x^2)+3. It works in so far as finding the root, but I also want it to print out the root after each iteration but I can't get it to work, Could anyone point out my mistake I think its something to do with my indexing? Thanks a million :) #include <stdio.h> #include <math.h> #include <malloc.h> //Define Functions: double evalf(double x) { double answer=exp(-x)-(x*x)+3; return(answer); } double evalfprime(double x) { double answer=-exp(-x)-2*x; return(answer); } double *newton(double initialrt,double accuracy,double *data) { double root[102]; data=root; int maxit = 0; root[0] = initialrt; for (int i=1;i<102;i++) { *(data+i)=*(data+i-1)-evalf(*(data+i-1))/evalfprime(*(data+i-1)); if(fabs(*(data+i)-*(data+i-1))<accuracy) { maxit=i; break; } maxit=i; } if((maxit+1==102)&&(fabs(*(data+maxit)-*(data+maxit-1))>accuracy)) { printf("\nMax iteration reached, method terminated"); } else { printf("\nMethod successful"); printf("\nNumber of iterations: %d\nRoot Estimate: %lf\n",maxit+1,*(data+maxit)); } return(data); } int main() { double root,accuracy; double *data=(double*)malloc(sizeof(double)*102); printf("NEWTONS METHOD PROGRAMME:\nEquation: f(x)=exp(-x)-x^2+3=0\nMax No iterations=100\n\nEnter initial root estimate\n>> "); scanf("%lf",&root); _flushall(); printf("\nEnter accuracy required:\n>>"); scanf("%lf",&accuracy); *data= *newton(root,accuracy,data); printf("Iteration Root Error\n "); printf("%d %lf \n", 0,*(data)); for(int i=1;i<102;i++) { printf("%d %5.5lf %5.5lf\n", i,*(data+i),*(data+i)-*(data+i-1)); if(*(data+i*sizeof(double))-*(data+i*sizeof(double)-1)==0) { break; } } getchar(); getchar(); free(data); return(0); }

    Read the article

  • if non zero elements in same column count only once

    - by George
    I want to check the elements above the main diagonal and if I found non zero values , count one. If the non zero values are found in the same column ,then count just one ,not the number of the non zero values. For example , it should be count = 2 and not 3 in this example because 12 and 6 are in the same column. A= 1 11 12 4 5 6 0 7 0 #include <stdio.h> #include <stdlib.h> #include <math.h> int main( int argc, const char* argv[] ){ int Rows = 3 , Cols = 3; float *A = (float *) malloc ( Rows * Cols * sizeof (float) ); A[0] = 1.0; A[1] = 11.0; A[2] = 12.0; A[3] = 4.0; A[4] = 5.0; A[5] = 6.0; A[6] = 0.0; A[7] = 7.0; A[8] = 0.0; // print input matrix printf("\n Input matrix \n\n"); for ( int i = 0; i < Rows; i++ ) for ( int j = 0; j < Cols; j++ ) { printf("%f\t",A[ i * Cols + j ]); if( j == Cols-1 ) printf("\n"); } printf("\n"); int count = 0; for ( int j = 0 ; j < Cols; j++ ) { for ( int i = ( Rows - 1 ); i >= 0; i-- ) { // check the diagonal elements above the main diagonal if ( j > i ) { if ( ( A[ i * Cols + j ] != 0 ) ) { printf("\n Above nonzero Elmts = %f\n",( A[i * Cols + j] ) ); count++; } } } } printf("\ncount = %d\n",count ); return 0; }

    Read the article

  • AJAX Div Retrieval every 60 seconds

    - by Sam
    Hello everyone! What I would like to do is retrieve the contents of a PHP file and insert it into a div every 60 seconds, basically refreshing the dynamic div. I've come up with the following code so far, however it doesn't seem to be working. The code is just like this, nothing extra, apart from the MYSQL login. PHP to grab: <?php $time = date("m/d/Y h:i:s a", time()); mysql_query("UPDATE djs SET requesttime='{$time}' WHERE username='{$djs['username']}'") or die(mysql_error()); $request_db = mysql_query("SELECT * FROM requests WHERE haveplayed='0'") or die(mysql_error()); echo "<table style=\"border:1px solid;width:99%;margin-left:auto;margin-right:auto;\" border=\"1\">"; echo "<tr><th>Title</th><th>Artist</th><th>Dedicated To...</th></tr>"; while($request = mysql_fetch_array( $request_db )) { echo "<tr><td style=\"width:33%;padding:1px;\">"; echo $request['SongName']; echo "</td><td style=\"width:33%;\">"; echo $request['Artist']; echo "</td><td style=\"width:33%;\">"; echo $request['DedicatedTo']; echo "</td></tr>"; } echo "</table>"; ?> The original PHP code is just the same, enclosed in a div with an id attribute of 'ajax_table'. The JavaScript is: // JavaScript Document var xmlHttp_moniter function moniter() { xmlHttp_moniter = GetXmlHttpObject_parcel() if(xmlHttp_moniter == null) { alert("browser does not support HTTP Request") return } var url="ajax_table.php?random=" + Math.random() xmlHttp_moniter.onreadystatechange = stateChanged xmlHttp_moniter.open("GET",url,true) xmlHttp_moniter.send(null) } function stateChanged() { if(xmlHttp_moniter.readyState==4 || xmlHttp_moniter.readyState == "complete") { document.getElementById("ajax_table").innerHTML = xmlHttp_moniter.responseText setTimeout('ajax_table()',60000); } } function GetXmlHttpObject_parcel() { var xmlHttp_moniter=null; try { xmlHttp_moniter=new XMLHttpRequest(); } catch (e) { //Internet Explorer try { xmlHttp_moniter=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp_moniter=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp_moniter; } and that is on the page that is requesting the other php page.

    Read the article

  • ThreadQueue problems in "Accelerated C# 2008"

    - by Singlet
    Example for threading queue book "Accelerated C# 2008" (CrudeThreadPool class) not work correctly. If I insert long job in WorkFunction() on 2-processor machine executing for next task don't run before first is over. How to solve this problem? I want to load the processor to 100 percent public class CrudeThreadPool { static readonly int MAX_WORK_THREADS = 4; static readonly int WAIT_TIMEOUT = 2000; public delegate void WorkDelegate(); public CrudeThreadPool() { stop = 0; workLock = new Object(); workQueue = new Queue(); threads = new Thread[ MAX_WORK_THREADS ]; for( int i = 0; i < MAX_WORK_THREADS; ++i ) { threads[i] = new Thread( new ThreadStart(this.ThreadFunc) ); threads[i].Start(); } } private void ThreadFunc() { lock( workLock ) { int shouldStop = 0; do { shouldStop = Interlocked.Exchange( ref stop, stop ); if( shouldStop == 0 ) { WorkDelegate workItem = null; if( Monitor.Wait(workLock, WAIT_TIMEOUT) ) { // Process the item on the front of the queue lock( workQueue ) { workItem =(WorkDelegate) workQueue.Dequeue(); } workItem(); } } } while( shouldStop == 0 ); } } public void SubmitWorkItem( WorkDelegate item ) { lock( workLock ) { lock( workQueue ) { workQueue.Enqueue( item ); } Monitor.Pulse( workLock ); } } public void Shutdown() { Interlocked.Exchange( ref stop, 1 ); } private Queue workQueue; private Object workLock; private Thread[] threads; private int stop; } public class EntryPoint { static void WorkFunction() { Console.WriteLine( "WorkFunction() called on Thread {0}",Thread.CurrentThread.GetHashCode() ); //some long job double s = 0; for (int i = 0; i < 100000000; i++) s += Math.Sin(i); } static void Main() { CrudeThreadPool pool = new CrudeThreadPool(); for( int i = 0; i < 10; ++i ) { pool.SubmitWorkItem( new CrudeThreadPool.WorkDelegate( EntryPoint.WorkFunction) ); } pool.Shutdown(); } }

    Read the article

  • CUDA memory transfer issue

    - by Vaibhav Sundriyal
    I am trying to execute a code which first transfers data from CPU to GPU memory and vice-versa. In spite of increasing the volume of data, the data transfer time remains the same as if no data transfer is actually taking place. I am posting the code. #include <stdio.h> /* Core input/output operations */ #include <stdlib.h> /* Conversions, random numbers, memory allocation, etc. */ #include <math.h> /* Common mathematical functions */ #include <time.h> /* Converting between various date/time formats */ #include <cuda.h> /* CUDA related stuff */ #include <sys/time.h> __global__ void device_volume(float *x_d,float *y_d) { int index = blockIdx.x * blockDim.x + threadIdx.x; } int main(void) { float *x_h,*y_h,*x_d,*y_d,*z_h,*z_d; long long size=9999999; long long nbytes=size*sizeof(float); timeval t1,t2; double et; x_h=(float*)malloc(nbytes); y_h=(float*)malloc(nbytes); z_h=(float*)malloc(nbytes); cudaMalloc((void **)&x_d,size*sizeof(float)); cudaMalloc((void **)&y_d,size*sizeof(float)); cudaMalloc((void **)&z_d,size*sizeof(float)); gettimeofday(&t1,NULL); cudaMemcpy(x_d, x_h, nbytes, cudaMemcpyHostToDevice); cudaMemcpy(y_d, y_h, nbytes, cudaMemcpyHostToDevice); cudaMemcpy(z_d, z_h, nbytes, cudaMemcpyHostToDevice); gettimeofday(&t2,NULL); et = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms et += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms printf("\n %ld\t\t%f\t\t",nbytes,et); et=0.0; //printf("%f %d\n",seconds,CLOCKS_PER_SEC); // launch a kernel with a single thread to greet from the device //device_volume<<<1,1>>>(x_d,y_d); gettimeofday(&t1,NULL); cudaMemcpy(x_h, x_d, nbytes, cudaMemcpyDeviceToHost); cudaMemcpy(y_h, y_d, nbytes, cudaMemcpyDeviceToHost); cudaMemcpy(z_h, z_d, nbytes, cudaMemcpyDeviceToHost); gettimeofday(&t2,NULL); et = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms et += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms printf("%f\n",et); cudaFree(x_d); cudaFree(y_d); cudaFree(z_d); return 0; } Can anybody help me with this issue? Thanks

    Read the article

  • CPU/JVM/JBoss 7 slows down over time

    - by lukas
    I'm experiencing performance slow down on JBoss 7.1.1 Final. I wrote simple program that demostrates this behavior. I generate an array of 100,000 of random integers and run bubble sort on it. @Model public class PerformanceTest { public void proceed() { long now = System.currentTimeMillis(); int[] arr = new int[100000]; for(int i = 0; i < arr.length; i++) { arr[i] = (int) (Math.random() * 200000); } long now2 = System.currentTimeMillis(); System.out.println((now2 - now) + "ms took to generate array"); now = System.currentTimeMillis(); bubbleSort(arr); now2 = System.currentTimeMillis(); System.out.println((now2 - now) + "ms took to bubblesort array"); } public void bubbleSort(int[] arr) { boolean swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; j++; for (int i = 0; i < arr.length - j; i++) { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; } } } } } Just after I start the server, it takes approximately 22 seconds to run this code. After few days of JBoss 7.1.1. running, it takes 330 sec to run this code. In both cases, I launch the code when the CPU utilization is very low (say, 1%). Any ideas why? I run the server with following arguments: -Xms1280m -Xmx2048m -XX:MaxPermSize=2048m -Djava.net.preferIPv4Stack=true -Dorg.jboss.resolver.warning=true -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 -Djboss.modules.system.pkgs=org.jboss.byteman -Djava.awt.headless=true -Duser.timezone=UTC -Djboss.server.default.config=standalone-full.xml -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n I'm running it on Linux 2.6.32-279.11.1.el6.x86_64 with java version "1.7.0_07". It's within J2EE applicaiton. I use CDI so I have a button on JSF page that will call method "proceed" on @RequestScoped component PerformanceTest. I deploy this as separate war file and even if I undeploy other applications, it doesn't change the performance. It's a virtual machine that is sharing CPUs with another machine but that one doesn't consume anything. Here's yet another observation: when the server is after fresh start and I run the bubble sort, It utilizes 100% of one processor core. It never switches to another core or drops utilization below 95%. However after some time the server is running and I'm experiencing the performance problems, the method above is utilizing CPU core usually 100%, however I just found out from htop that this task is being switched very often to other cores. That is, at the beginning it's running on core #1, after say 2 seconds it's running on #5 then after say 2 seconds #8 etc. Furthermore, the utilization is not kept at 100% at the core but sometimes drops to 80% or even lower. For the server after fresh start, even though If I simulate a load, it never switches the task to another core.

    Read the article

  • SharePoint - Summing Calculated Columns By Groups (DVWP)

    - by Mark Rackley
    I had a problem… okay.. okay.. so I have many problems… but let’s focus on one in particular or this blog post would never end… okay? Thank you…. So, I had an electronic timesheet where users entered hours for each day of the week. It also had a “Week Total” column which was a calculated column of the sum. The calculated column looked like this: Pretty easy.. nothing spectacular. So, what’s the problem? WELL……………….. There is a row in the timesheet for each task a person worked on in a given week. So, if you worked on 4 tasks, you would have 4 rows of data, and 4 week totals for that week: This is all fine and dandy, but I want to know what the total was for the entire week. Yes.. I realize the answer is 24 from my example… I mean, I know how to add! I just want SharePoint to display it for me for the executives (we all know, they have math problems).  You may be thinking, hey genius (in a sarcastic tone of course), why don’t you just go to the view and total on the “Week Total” field. What a brilliant idea! Why didn’t I think of that… let’s go to the view and do just that…. Ohhhhhh… you can’t total on a Calculated Column.. it’s not even an option…  Yeah… I had the same moment. So, what do you do? Well… what do you think I did? 1) Googled “SharePoint total calculated column” 2) Said it couldn’t be done 3) Took a nap 4) Asked the question on twitter? The correct answer of course is number 4… followed by number 3… although I may have told my boss number 2 so that I look more brilliant than I am? It’s safe to say I did NOT try to find the solution on my own doing step 1… that would be just WAY to easy… So, anyway, I posted the question on Twitter and it turns out several people had suggestions from using jQuery to using DVWPs. I tend to be a big fan of the DVWP except for the disgusting process of deploying them to another farm.. ugh… just shoot me…. so, that is the solution I went with. Laura Rogers (@WonderLaura) has a super duper easy to follow video on the subject over at EndUserSharePoint.com: SharePoint: Displaying Calculated Column SUMS in a View (Screencast) Laura’s video was very easy to follow and was ALMOST exactly what I needed. She does a great job walking you through every step of summing up a calculated field which was PART of my problem. The other part was my list is grouped by date! So, I wanted to see for a given week, the summed “Week Total” of hours. Laura got me on the right track with her video and I dug a little deeper into the DVWP to accomplish my task. So, here are the steps you follow: 1. Click on the "chevron” (I didn’t know it was actually called that until I heard Laura say it).. I always call it the “little-button-in-the-top-right-corner-with-the-greater-than-sign”.. but “chevron” is much shorter. So, click on the chevron, click on “Sort and Group”. The Add the field you want to group by, in my example it is the “Monday Date” of the timesheet entry. Make sure to check the check boxes for “Show Group Header” AND “Show Group Footer”. Click “OK”. The view now shows the count of each grouped set of data: Interesting, this looks very similar to Laura’s video… right? So, let’s take a look at the code for the Count: Count : <xsl:value-of select="count($nodeset)" /> Wow, also very similar… except in Laura’s video it looks like: Count : <xsl:value-of select="count($Rows)" /> So.. the only difference is that instead of $Rows we have $nodeset. It turns out the $nodeset will go through each Row in the group just like $Rows goes through each row in the entire view. So, using the exact same logic as in Laura’s blog except replacing $Rows with $nodeset we get the functionality of being able to sum up the values for a group. So, I want to replace “Count: #” with the total hours, this is done using the following changes to the above code: Week Total : <xsl:value-of select="sum($nodeset/@Monday)+sum($nodeset/@Tuesday) +sum($nodeset/@Wednesday)+sum($nodeset/@Thursday)+sum($nodeset/@Friday) +sum($nodeset/@Saturday)+sum($nodeset/@Sunday)" /> Our final output has the summed hours for each group! So… long story short… follow Laura’s blog, then group your list, then replace “$Rows” with “$nodeset”. One caveat, this will not work if you group by a person field. For some reason the person field does not go through each row in the group. I haven’t dug into this much yet. Maybe if I find some time… whatever that is… Anyway, Laura did all the work, I just took it one small step forward… as always, feel free to leave any additional insights you may have. We’re all learning here!

    Read the article

< Previous Page | 124 125 126 127 128 129 130 131 132 133 134 135  | Next Page >