Search Results

Search found 8083 results on 324 pages for 'total newbie'.

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

  • adding only odd numbers

    - by Jessica M.
    So the question I'm trying to solve the user is supposed to enter any positive number. Then I'm trying to write a program that adds only the odd numbers up to the number the user enters and displays the total. So for example if the user enters 4 my program should add four odd numbers. 1 + 3 + 5 + 7 = 16. The only tools I have available are for statement, if, if/else if,while loop and println. I can only figure out how to print out the odd numbers. I know I want to create a variable named total to store the value of adding up all the odd numbers but I don't know how that fits into the program. import acm.program.*; public class AddingOddNumbers extends ConsoleProgram { public void run() { int n = readInt("enter a positive nunber: "); int total = 0; for (int i = 0; i < n; i++) { if (n == 1) { println(1); } else { println((i * 2) + 1); } } } }

    Read the article

  • New Perl user: using a hash of arrays

    - by Zach H
    I'm doing a little datamining project where a perl script grabs info from a SQL database and parses it. The data consists of several timestamps. I want to find how many of a particular type of timestamp exist on any particular day. Unfortunately, this is my first perl script, and the nature of perl when it comes to hashes and arrays is confusing me quite a bit. Code segment: my %values=();#A hash of the total values of each type of data of each day. #The key is the day, and each key stores an array of each of the values I need. my @proposal; #[drafted timestamp(0), submitted timestamp(1), attny approved timestamp(2),Organiziation approved timestamp(3), Other approval timestamp(4), Approved Timestamp(5)] while(@proposal=$sqlresults->fetchrow_array()){ #TODO: check to make sure proposal is valid #Increment the number of timestamps of each type on each particular date my $i; for($i=0;$i<=5;$i++) $values{$proposal[$i]}[$i]++; #Update rolling average of daily #TODO: To check total load, increment total load on all dates between attourney approve date and accepted date for($i=$proposal[1];$i<=$proposal[2];$i++) $values{$i}[6]++; } I keep getting syntax errors inside the for loops incrementing values. Also, considering that I'm using strict and warnings, will Perl auto-create arrays of the right values when I'm accessing them inside the hash, or will I get out-of bounds errors everywhere? Thanks for any help, Zach

    Read the article

  • Getting percentage of "Count(*)" to the number of all items in "GROUP BY"

    - by celalo
    Let's say I need to have the ratio of "number of items available from certain category" to "the the number of all items". Please consider a MySQL table like this: /* mysql> select * from Item; +----+------------+----------+ | ID | Department | Category | +----+------------+----------+ | 1 | Popular | Rock | | 2 | Classical | Opera | | 3 | Popular | Jazz | | 4 | Classical | Dance | | 5 | Classical | General | | 6 | Classical | Vocal | | 7 | Popular | Blues | | 8 | Popular | Jazz | | 9 | Popular | Country | | 10 | Popular | New Age | | 11 | Popular | New Age | | 12 | Classical | General | | 13 | Classical | Dance | | 14 | Classical | Opera | | 15 | Popular | Blues | | 16 | Popular | Blues | +----+------------+----------+ 16 rows in set (0.03 sec) mysql> SELECT Category, COUNT(*) AS Total -> FROM Item -> WHERE Department='Popular' -> GROUP BY Category; +----------+-------+ | Category | Total | +----------+-------+ | Blues | 3 | | Country | 1 | | Jazz | 2 | | New Age | 2 | | Rock | 1 | +----------+-------+ 5 rows in set (0.02 sec) */ What I need is basically a result set resembles this one: /* +----------+-------+-----------------------------+ | Category | Total | percentage to the all items | (Note that number of all available items is "9") +----------+-------+-----------------------------+ | Blues | 3 | 33 | (3/9)*100 | Country | 1 | 11 | (1/9)*100 | Jazz | 2 | 22 | (2/9)*100 | New Age | 2 | 22 | (2/9)*100 | Rock | 1 | 11 | (1/9)*100 +----------+-------+-----------------------------+ 5 rows in set (0.02 sec) */ How can I achieve such a result set in a single query? Thanks in advance.

    Read the article

  • Invalid conversion from int to int

    - by FOXMULDERIZE
    #include <iostream> #include<fstream> using namespace std; void showvalues(int,int,int []); void showvalues2(int,int); void sumtotal(int,int); int main() { const int SIZE_A= 9; int arreglo[SIZE_A]; ifstream archivo_de_entrada; archivo_de_entrada.open("numeros.txt"); int count,suma,total,a,b,c,d,e,f; int total1=0; int total2=0; //lee/// for(count =0 ;count < SIZE_A;count++) archivo_de_entrada>>arreglo[count] ; archivo_de_entrada.close(); showvalues(0,3,9); HERE IS THE PROBLEM showvalues2(5,8); sumtotal(total1,total2); system("pause"); return 0; } void showvalues(int a,int b,int v) { //muestra//////////////////////// cout<< "los num son "; for(count = a ;count <= b;count++) total1 = total1 + arreglo[count]; cout <<total1<<" "; cout <<endl; } void showvalues2(int c,int d) { ////////////////////////////// cout<< "los num 2 son "; for(count =5 ;count <=8;count++) total2 = total2 + arreglo[count]; cout <<total2<<" "; cout <<endl; } void sumtotal(int e,int f) { ///////////////////////////////// cout<<"la suma de t1 y t2 es "; total= total1 + total2; cout<<total; cout <<endl; }

    Read the article

  • NHibernate update using composite key

    - by Mahesh
    Hi, I have a table defnition as given below: License ClientId Type Total Used ClientId and Type together uniquely identifies a row. I have a mapping file as given below: <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true"> <class name="Acumen.AAM.Domain.Model.License, Acumen.AAM.Domain" lazy="false" table="License"> <id name="ClientId" access="field" column="ClientID" /> <property name="Total" access="field" column="Total"/> <property name="Used" access="field" column="Used"/> <property name="Type" access="field" column="Type"/> </class> </hibernate-mapping> If a client used a license to create a user, I need to update the Used column in the table. As I set ClientId as the id column for this table, I am getting TooManyRowsAffectedException. could you please let me know how to set a composite key at mapping level so that NHibernate can udpate based on ClientId and Type. Something like: Update License SET Used=Used-1 WHERE ClientId='xxx' AND Type=1 Please help. Thanks, Mahesh

    Read the article

  • NSOutlineView/NSTreeController - calculate sum of column

    - by matei
    I have a NSOutlineView bound to a NSTreeController. My data items are a custom class , let's call them "Row", and suppose a Row contains a "name" and a numeric field called "number" . All these "Rows" are found in let's say a "RowContainer" which has a "rows" mutable array holding the parent (level 0) rows. Each row also has a "children" NSMutableArray member which holds it's children. I have this working, and I want to display under the outlineview a textfield with the sum of all the "number" values of the rows. I bound this textfield to a "total" property of the "RowContainer". Now the problem is how or from where to trigger the recalculation of the "total" property, since this involves a recursive walk on the tree of rows, and I always get a "Collection was mutated while being enumerated" error. I've tried making a method "recalculateTotal", and calling it from the "setNumber" method of the "Row" class , but same error occurs. If I put the recalculation logic in the "total" getter, I can't trigger it to do the math. I'm sure the solution is simple but I can't see it

    Read the article

  • XSLT pass node into CDATA JS

    - by davomarti
    I have the following xml <AAA> <BBB>Total</BBB> </AAA> Transforming it with the following xslt using the xsl:copy-of tag, because I want to use the xml to create a xml doc in js. <xsl:template match="/"> <![CDATA[ function myFunc() { xmlStr = ']]><xsl:copy-of select="/"/><![CDATA['; } ]]> </xsl:template> The output looks like this function myFunc() { xmlStr = '<AAA> <BBB>Total</BBB> </AAA>'; } JS doesn't like this because of the missing semicolons ending the lines. How can I fix my xsl to get the below result: function myFunc() { xmlStr = '<AAA><BBB>Total</BBB></AAA>'; } I've tried normalize-space() and translate() but they strip the tags from the xml. Thanks!

    Read the article

  • How do I define a Calculated Measure in MDX based on a Dimension Attribute?

    - by ShaneD
    I would like to create a calculated measure that sums up only a specific subset of records in my fact table based on a dimension attribute. Given: Dimension Date LedgerLineItem {Charge, Payment, Write-Off, Copay, Credit} Measures LedgerAmount Relationships * LedgerLineItem is a degenerate dimension of FactLedger If I break down LedgerAmount by LedgerLineItem.Type I can easily see how much is charged, paid, credit, etc, but when I do not break it down by LedgerLineItem.Type I cannot easily add the credit, paid, credit, etc into a pivot table. I would like to create separate calculated measures that sum only specific type (or multiple types) of ledger facts. An example of the desired output would be: | Year | Charged | Total Paid | Amount - Ledger | | 2008 | $1000 | $600 | -$400 | | 2009 | $2000 | $1500 | -$500 | | Total | $3000 | $2100 | -$900 | I have tried to create the calculated measure a couple of ways and each one works in some circumstances but not in others. Now before anyone says do this in ETL, I have already done it in ETL and it works just fine. What I am trying to do as part of learning to understand MDX better is to figure out how to duplicate what I have done in the ETL in MDX as so far I am unable to do that. Here are two attempts I have made and the problems with them. This works only when ledger type is in the pivot table. It returns the correct amount of the ledger entries (although in this case it is identical to [amount - ledger] but when I try to remove type and just get the sum of all ledger entries it returns unknown. CASE WHEN ([Ledger].[Type].currentMember = [Ledger].[Type].&[Credit]) OR ([Ledger].[Type].currentMember = [Ledger].[Type].&[Paid]) OR ([Ledger].[Type].currentMember = [Ledger].[Type].&[Held Money: Copay]) THEN [Measures].[Amount - ledger] ELSE 0 END This works only when ledger type is not in the pivot table. It always returns the total payment amount, which is incorrect when I am slicing by type as I would only expect to see the credit portion under credit, the paid portion, under paid, $0 under charge, etc. sum({([Ledger].[Type].&[Credit]), ([Ledger].[Type].&[Paid]), ([Ledger].[Type].&[Held Money: Copay])}, [Measures].[Amount - ledger]) Is there any way to make this return the correct numbers regardless of whether Ledger.Type is included in my pivot table or not?

    Read the article

  • x86 .net application with system.OutOfMemoryException

    - by Allen
    Hi,Guys I got OutOfMemoryException after the app running for 1 day, the app totally use 1.5G memory , all consumed by managed heap, gen 2 used 200mb , and LOB used 1.3mb, however the weired thing is, 900mb of space are Free. from perf counter I saw there had number of gen 2 gc collection happened, why GC collector cannot collect those 900mb free space in gen2 and LOB? I'm really appreicate for your help. following info are from windbg: 0:000> !eeheap -gc Number of GC Heaps: 1 generation 0 starts at 0x183153f0 generation 1 starts at 0x182aa834 generation 2 starts at 0x02131000 ephemeral segment allocation context: none segment begin allocated size 02130000 02131000 0312f284 0xffe284(16769668) 07750000 07751000 0874fc5c 0xffec5c(16772188) 09e30000 09e31000 0ae2fc2c 0xffec2c(16772140) 0b230000 0b231000 0c22ffec 0xffefec(16773100) 0c230000 0c231000 0d22f6f0 0xffe6f0(16770800) 0d230000 0d231000 0e22ea10 0xffda10(16767504) 0e230000 0e231000 0f22c1c4 0xffb1c4(16757188) 10390000 10391000 1138ddf4 0xffcdf4(16764404) 154e0000 154e1000 164da90c 0xff990c(16750860) 34aa0000 34aa1000 35a9dbfc 0xffcbfc(16763900) 7aca0000 7aca1000 7bc9edfc 0xffddfc(16768508) 49760000 49761000 4a75ef64 0xffdf64(16768868) 7bca0000 7bca1000 7cc99bac 0xff8bac(16747436) 17a70000 17a71000 183313fc 0x8c03fc(9176060) Large object heap starts at 0x03131000 segment begin allocated size 03130000 03131000 041250c8 0xff40c8(16728264) 08920000 08921000 099102f8 0xfef2f8(16708344) .... .... 4c760000 4c761000 4d71d578 0xfbc578(16500088) 1bb10000 1bb11000 1ca110d0 0xf000d0(15728848) 57760000 57761000 5862d7f8 0xecc7f8(15517688) Total Size: Size: 0x5ab13450 (1521562704) bytes. ------------------------------ GC Heap Size: Size: 0x5ab13450 (1521562704) bytes. 0:000> !dumpheap -stat total 0 objects Statistics: MT Count TotalSize Class Name 73037c78 1 12 System.Configuration.GenericEnumConverter 73036da0 1 12 System.Configuration.InfiniteIntConverter .... .... 69161c3c 35025 6809420 System.Windows.EffectiveValueEntry[] 69164748 54 12471072 MS.Internal.WeakEventTable+EventKey[] 710e2228 9540 190389260 System.Byte[] 710dd2b8 1317031 339257932 System.String 0035a670 6427 902224056 Free Total 3615631 objects

    Read the article

  • Using MongoDB's map/reduce to "group by" two fields

    - by ibz
    I need something slightly more complex than the examples in the MongoDB docs and I can't seem to be able to wrap my head around it. Say I have a collection of objects of the form {date: "2010-10-10", type: "EVENT_TYPE_1", user_id: 123, ...} Now I want to get something similar to a SQL GROUP BY query, grouping over both date and type. That is, I want the number of events of each type in each day. Also, I'd like to make it unique by user_id, ie. if a user has more events in the same day, count it only once. I'm trying to do this with map/reduce. I do db.logs.mapReduce(function() { emit(this.type, 1); }, function(k, vals) { var total = 0; for (var i = 0; i < vals.length; i++) total += vals[i]; return total; }}) which nicely groups by type, but now, how can I group by date at the same time? Seems the key in emit() can't be an array (I thought about doing emit([this.date, this.type], 1)). Also, how can I ensure the per-user uniqueness? I'm just starting with MongoDB and I'm still having trouble grasping the basic concepts. Also, there is not much documentation available out there. Any help from more experienced users is appreciated. Thanks!

    Read the article

  • jqGrid Sort or Search does not work with columns having json dot notation

    - by rsmoorthy
    I have this jqGrid: $("#report").jqGrid( { url: '/py/db?coll=report', datatype: 'json', height: 250, colNames: ['ACN', 'Status', 'Amount'], colModel: [ {name:'acn', sortable:true}, {name:'meta.status', sortable:true}, {name:amount} ], caption: 'Show Report', rownumbers: true, gridview: true, rowNum: 10, rowList: [10,20,30], pager: '#report_pager', viewrecords: true, sortname: 'acn', sortorder: "desc", altRows: true, loadonce: true, mtype: "GET", rowTotal: 1000, jsonReader: { root: "rows", page: "page", total: "total", records: "records", repeatitems: false, id: "acn" } }); Notice that the column 'meta.status' is in JSON dot notation and accordingly the data sent from the server is like this: {"page": "1", "total": "1", "records": "5", "rows": [ {"acn":1,"meta": {"status":"Confirmed"}, "amount": 50}, {"acn":2,"meta": {"status":"Started"}, "amount": 51}, {"acn":3,"meta": {"status":"Stopped"}, "amount": 52}, {"acn":4,"meta": {"status":"Working"}, "amount": 53}, {"acn":5,"meta": {"status":"Started"}, "amount": 54} ] } The problems are of two fold: Sorting does not work on columns with dot notation, here "meta.status". It does not even show the sortable icons on the column header, and nothing happens even if the header is clicked. Sorting does not work, whether loadonce is true or false. If I try Searching (after setting loadonce to true) for the column meta.status (other columns without dot notation is okay), then it throws up a javascript error like this. Any help? Thanks Moorthy

    Read the article

  • Algorithm for optimally choosing actions to perform a task

    - by Jules
    There are two data types: tasks and actions. An action costs a certain time to complete, and a set of tasks this actions consists of. A task has a set of actions, and our job is to choose one of them. So: class Task { Set<Action> choices; } class Action { float time; Set<Task> dependencies; } For example the primary task could be "Get a house". The possible actions for this task: "Buy a house" or "Build a house". The action "Build a house" costs 10 hours and has the dependencies "Get bricks" and "Get cement", etcetera. The total time is the sum of all the times of the actions required to perform. We want to choose actions such that the total time is minimal. Note that the dependencies can be diamond shaped. For example "Get bricks" could require "Get a car" (to transport the bricks) and "Get cement" would also require a car. Even if you do "Get bricks" and "Get cement" you only have to count the time it takes to get a car once. Note also that the dependencies can be circular. For example "Money" - "Job" - "Car" - "Money". This is no problem for us, we simply select all of "Money", "Job" and "Car". The total time is simply the sum of the time of these 3 things. Mathematical description: Let actions be the chosen actions. valid(task) = ?action ? task.choices. (action ? actions ? ?tasks ? action.dependencies. valid(task)) time = sum {action.time | action ? actions} minimize time subject to valid(primaryTask)

    Read the article

  • How to implement web cache: internal fragmentation VS external fragmentation

    - by Summer_More_More_Tea
    Hi there: I come up with this question when play with Firefox web cache: in which approach does the browser cache a response in limited disk space(take my configuration as an example, 50MB is the upper bound)? I think two ways can be employed. One is cache the total response object one by one, but this is inefficient and will introduce external fragmentation, thus the total cache space may not be fully used. The second is take the total space(50MB) as a consecutive file, splitting it into fixed-length slots; incoming response objects will also be treated blocks of data with the same length as the slots. We can fill slots until the whole file is run out of, then some displacement algorithm can be used to swap out the old cached objects. The latter approach will of course bing in internal fragmentation, but in my opinion is easier to implement and maintain than the first strategy. But when I enter Firefox's Cache directory, I find it (maybe) use a different method: a lot of varied-length files reside in that directory and all those files are filled with undisplayable characters. I don't but really want to know what mechanism that a commercial browser, e.g. Firefoix, employed to implement web cache. Regards.

    Read the article

  • SQL Server search filter and order by performance issues

    - by John Leidegren
    We have a table value function that returns a list of people you may access, and we have a relation between a search and a person called search result. What we want to do is that wan't to select all people from the search and present them. The query looks like this SELECT qm.PersonID, p.FullName FROM QueryMembership qm INNER JOIN dbo.GetPersonAccess(1) ON GetPersonAccess.PersonID = qm.PersonID INNER JOIN Person p ON p.PersonID = qm.PersonID WHERE qm.QueryID = 1234 There are only 25 rows with QueryID=1234 but there are almost 5 million rows total in the QueryMembership table. The person table has about 40K people in it. QueryID is not a PK, but it is an index. The query plan tells me 97% of the total cost is spent doing "Key Lookup" witht the seek predicate. QueryMembershipID = Scalar Operator (QueryMembership.QueryMembershipID as QM.QueryMembershipID) Why is the PK in there when it's not used in the query at all? and why is it taking so long time? The number of people total 25, with the index, this should be a table scan for all the QueryMembership rows that have QueryID=1234 and then a JOIN on the 25 people that exists in the table value function. Which btw only have to be evaluated once and completes in less than 1 second.

    Read the article

  • Using PLINQ to calculate and update values within the enclosure does not work

    - by Keith
    I recently needed to do a running total on a report. Where for each group, I order the rows and then calculate the running total based on the previous rows within the group. Aha! I thought, a perfect use case for PLINQ! However, when I wrote up the code, I got some strange behavior. The values I was modifying showed as being modified when stepping through the debugger, but when they were accessed they were always zero. Sample Code: class Item { public int PortfolioID; public int TAAccountID; public DateTime TradeDate; public decimal Shares; public decimal RunningTotal; } List<Item> itemList = new List<Item> { new Item { PortfolioID = 1, TAAccountID = 1, TradeDate = new DateTime(2010, 5, 1), Shares = 5.335m, }, new Item { PortfolioID = 1, TAAccountID = 1, TradeDate = new DateTime(2010, 5, 2), Shares = -2.335m, }, new Item { PortfolioID = 2, TAAccountID = 1, TradeDate = new DateTime(2010, 5, 1), Shares = 7.335m, }, new Item { PortfolioID = 2, TAAccountID = 1, TradeDate = new DateTime(2010, 5, 2), Shares = -3.335m, }, }; var found = (from i in itemList where i.TAAccountID == 1 select new Item { TAAccountID = i.TAAccountID, PortfolioID = i.PortfolioID, Shares = i.Shares, TradeDate = i.TradeDate, RunningTotal = 0 }); found.AsParallel().ForAll(x => { var prevItems = found.Where(i => i.PortfolioID == x.PortfolioID && i.TAAccountID == x.TAAccountID && i.TradeDate <= x.TradeDate); x.RunningTotal = prevItems.Sum(s => s.Shares); }); foreach (Item i in found) { Console.WriteLine("Running total: {0}", i.RunningTotal); } Console.ReadLine(); If I change the select for found to be .ToArray(), then it works fine and I get calculated reuslts. Any ideas what I am doing wrong?

    Read the article

  • convert list of relative widths to pixel widths

    - by mkoryak
    This is a code review question more then anything. I have the following problem: Given a list of relative widths (no unit whatsoever, just all relative to each other), generate a list of pixel widths so that these pixel widths have the same proportions as the original list. input: list of proportions, total pixel width. output: list of pixel widths, where each width is an int, and the sum of these equals the total width. Code: var sizes = "1,2,3,5,7,10".split(","); //initial proportions var totalWidth = 1024; // total pixel width var sizesTotal = 0; for (var i = 0; i < sizes.length; i++) { sizesTotal += parseInt(sizes[i], 10); } if(sizesTotal != 100){ var totalLeft = 100;; for (var i = 0; i < sizes.length; i++) { sizes[i] = Math.floor(parseInt(sizes[i], 10) / sizesTotal * 100); totalLeft -= sizes[i]; } sizes[sizes.lengh - 1] = totalLeft; } totalLeft = totalWidth; for (var i = 0; i < sizes.length; i++) { widths[i] = Math.floor(totalWidth / 100 * sizes[i]) totalLeft -= widths[i]; } widths[sizes.lenght - 1] = totalLeft; //return widths which contains a list of INT pixel sizes

    Read the article

  • Parsing Chunk of Data into Hash of Array With Perl

    - by neversaint
    I have data that looks like this: #info #info2 1:SRX004541 Submitter: UT-MGS, UT-MGS Study: Glossina morsitans transcript sequencing project(SRP000741) Sample: Glossina morsitans(SRS002835) Instrument: Illumina Genome Analyzer Total: 1 run, 8.3M spots, 299.9M bases Run #1: SRR016086, 8330172 spots, 299886192 bases 2:SRX004540 Submitter: UT-MGS Study: Anopheles stephensi transcript sequencing project(SRP000747) Sample: Anopheles stephensi(SRS002864) Instrument: Solexa 1G Genome Analyzer Total: 1 run, 8.4M spots, 401M bases Run #1: SRR017875, 8354743 spots, 401027664 bases 3:SRX002521 Submitter: UT-MGS Study: Massive transcriptional start site mapping of human cells under hypoxic conditions.(SRP000403) Sample: Human DLD-1 tissue culture cell line(SRS001843) Instrument: Solexa 1G Genome Analyzer Total: 6 runs, 27.1M spots, 977M bases Run #1: SRR013356, 4801519 spots, 172854684 bases Run #2: SRR013357, 3603355 spots, 129720780 bases Run #3: SRR013358, 3459692 spots, 124548912 bases Run #4: SRR013360, 5219342 spots, 187896312 bases Run #5: SRR013361, 5140152 spots, 185045472 bases Run #6: SRR013370, 4916054 spots, 176977944 bases What I want to do is to create a hash of array with first line of each chunk as keys and SR## part of lines with "^Run" as its array member: $VAR = { 'SRX004541' => ['SRR016086'], # etc } But why my construct doesn't work. And it must be a better way to do it. use Data::Dumper; my %bighash; my $head = ""; my @temp = (); while ( <> ) { chomp; next if (/^\#/); if ( /^\d{1,2}:(\w+)/ ) { print "$1\n"; $head = $1; } elsif (/^Run \#\d+: (\w+),.*/){ print "\t$1\n"; push @temp, $1; } elsif (/^$/) { push @{$bighash{$head}}, [@temp]; @temp =(); } } print Dumper \%bighash ;

    Read the article

  • Ad distribution problem: an optimal solution?

    - by Mokuchan
    I'm asked to find a 2 approximate solution to this problem: You’re consulting for an e-commerce site that receives a large number of visitors each day. For each visitor i, where i € {1, 2 ..... n}, the site has assigned a value v[i], representing the expected revenue that can be obtained from this customer. Each visitor i is shown one of m possible ads A1, A2 ..... An as they enter the site. The site wants a selection of one ad for each customer so that each ad is seen, overall, by a set of customers of reasonably large total weight. Thus, given a selection of one ad for each customer, we will define the spread of this selection to be the minimum, over j = 1, 2 ..... m, of the total weight of all customers who were shown ad Aj. Example Suppose there are six customers with values 3, 4, 12, 2, 4, 6, and there are m = 3 ads. Then, in this instance, one could achieve a spread of 9 by showing ad A1 to customers 1, 2, 4, ad A2 to customer 3, and ad A3 to customers 5 and 6. The ultimate goal is to find a selection of an ad for each customer that maximizes the spread. Unfortunately, this optimization problem is NP-hard (you don’t have to prove this). So instead give a polynomial-time algorithm that approximates the maximum spread within a factor of 2. The solution I found is the following: Order visitors values in descending order Add the next visitor value (i.e. assign the visitor) to the Ad with the current lowest total value Repeat This solution actually seems to always find the optimal solution, or I simply can't find a counterexample. Can you find it? Is this a non-polinomial solution and I just can't see it?

    Read the article

  • Silverlight 4 XAML Collections

    - by mattduffield
    Hello, I have authored some custom classes that I would like to create using XAML: <Grid Width="300" Height="300"> <l:DashboardTable> <l:DashboardTable.DashboardTableQuery> <dq:DashboardTableQuery ConnectionString="Data Source=bunkerhill;Initial Catalog=emgov_data;User Id=emgovadmin;Password=p@$$word;" Query="select datename(month, cr_tb_DateDue) AS Month, sum(cr_tb_AmountTransaction) AS Total from cr_tb_transactionbill where Year(cr_tb_DateDue) = 2005 and Month(cr_tb_DateDue) IN (1,2,3,4) group by datename(month, cr_tb_DateDue)" > <dq:DashboardTableQuery.DataColumns> <dq:DataColumn ColumnName="Month" ColumnOrder="0" Label="Month" /> <dq:DataColumn ColumnName="Total" ColumnOrder="1" Label="Total" /> </dq:DashboardTableQuery.DataColumns> </dq:DashboardTableQuery> </l:DashboardTable.DashboardTableQuery> </l:DashboardTable> </Grid> The problem is that I get a XamlParseException when I try to run this XAML. I have determined it is when it gets to the dq:DataColumn element. It seems like this is only happening when I have a property that then has a collection and then several items in the collection that I am getting this issue. Has any encountered anything similar? I am try to achieve this all in XAML declaratively.

    Read the article

  • jquery calculation sum two different type of item

    - by st4n
    I'm writing a script like the example shown in the demo where All of the "Total" values (Including the "Grand Total") are Automatically Calculated using the calc () method. at this link: But I have some fields in which to apply the equation qty * price, and others where I want to do other operations .. you can tell me how? thank you very much i try with this, but it is a very stupid code .. and the grandTotal .. not sum the two different fields: function recalc() { $("[id^=total_item]").calc("qty * price", { qty: $("input[name^=qty_item_]"), price: $("[id^=price_item_]") }, function (s){ // return the number as a dollar amount return "$" + s.toFixed(2); }, function ($this){ // sum the total of the $("[id^=total_item]") selector var sum = $this.sum(); $("#grandTotal").text( // round the results to 2 digits "$" + sum.toFixed(2) ); }); $("[id^=total_otheritem]").calc("qty1 / price1", { qty1: $("input[name^=qty_other_]"), price1: $("[id^=price_other_]") }, function (s){ // return the number as a dollar amount return "$" + s.toFixed(2); }, function ($this){ var sum = $this.sum(); $("#grandTotal").text( // round the results to 2 digits "$" + sum.toFixed(2) ); }); }

    Read the article

  • SSRS code variable resetting on new page

    - by edmicman
    In SSRS 2008 I am trying to maintain a SUM of SUMs on a group using custom Code. The reason is that I have a table of data, grouped and returning SUMs of the data. I have a filter on the group to remove lines where group sums are zero. Everything works except I'm running into problems with the group totals - it should be summing the visible group totals but is instead summing the entire dataset. There's tons of articles about how to work around this, usually using custom code. I've made custom functions and variables to maintain a counter: Public Dim GroupMedTotal as Integer Public Dim GrandMedTotal as Integer Public Function CalcMedTotal(ThisValue as Integer) as Integer GroupMedTotal = GroupMedTotal + ThisValue GrandMedTotal = GrandMedTotal + ThisValue Return ThisValue End Function Public Function ReturnMedSubtotal() as Integer Dim ThisValue as Integer = GroupMedTotal GroupMedTotal = 0 Return ThisValue End Function Basically CalcMedTotal is fed a SUM of a group, and maintains a running total of that sum. Then in the group total line I output ReturnMedSubtotal which is supposed to give me the accumulated total and reset it for the next group. This actually works great, EXCEPT - it is resetting the GroupMedTotal value on each page break. I don't have page breaks explicitly set, it's just the natural break in the SSRS viewer. And if I export the results to Excel everything works and looks correctly. If I output Code.GroupMedTotal on each group row, I see it count correctly, and then if a group spans multiple pages on the next page GroupMedTotal is reset and begins counting from zero again. Any help in what's going on or how to work around this? Thanks!

    Read the article

  • MongoDB complex MapReduce of video logs

    - by Justin Hourigan
    I have a dataset from video streaming logs. Each video is identified by a FileGUID. The log entries record the FileGUID, the fragment of the video watched and the bandwidth it was watched at. I would like to create a mapreduce outputting, for each video, a count for fragments both total and for each bandwidth. Ideally it would look like; {"FileGUID":"50acb3a5796634df0e073285", { "1":{"total":76, "0832":34, "1028":42}, "2":{"total":42, "0832":28, "1028":14}, ... } } Is this possible with one mapreduce or is it a multi-step process, or should I use a different method? Here is a sample of the data. { "_id": ObjectId("50acb3a5796634df0e073285"), "IP": "46.7.1.88", "DateTime": ISODate("2012-10-24T22:59:57.0Z"), "FileGUID": "8cdde821fb934a6da7c125a012a26612", "Bandwidth": NumberInt(1028), "Segment": NumberInt(1), "Fragment": NumberInt(237), "Status": NumberInt(200), "Size": NumberInt(576790), "UserAgent": "Mozilla\/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko\/20100101 Firefox\/16.0" } { "_id": ObjectId("50acb3a5796634df0e073284"), "IP": "46.7.1.88", "DateTime": ISODate("2012-10-24T22:59:52.0Z"), "FileGUID": "8cdde821fb934a6da7c125a012a26612", "Bandwidth": NumberInt(1028), "Segment": NumberInt(1), "Fragment": NumberInt(236), "Status": NumberInt(200), "Size": NumberInt(577100), "UserAgent": "Mozilla\/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko\/20100101 Firefox\/16.0" } { "_id": ObjectId("50acb3a5796634df0e073283"), "IP": "46.7.1.88", "DateTime": ISODate("2012-10-24T22:59:47.0Z"), "FileGUID": "8cdde821fb934a6da7c125a012a26612", "Bandwidth": NumberInt(0832), "Segment": NumberInt(1), "Fragment": NumberInt(234), "Status": NumberInt(200), "Size": NumberInt(576664), "UserAgent": "Mozilla\/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko\/20100101 Firefox\/16.0" } { "_id": ObjectId("50acb3a5796634df0e073282"), "IP": "46.7.1.88", "DateTime": ISODate("2012-10-24T22:59:42.0Z"), "FileGUID": "8cdde821fb934a6da7c125a012a26612", "Bandwidth": NumberInt(0832), "Segment": NumberInt(1), "Fragment": NumberInt(233), "Status": NumberInt(200), "Size": NumberInt(575692), "UserAgent": "Mozilla\/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko\/20100101 Firefox\/16.0" }

    Read the article

  • Dynamically including multiple files within php for image descriptions

    - by Steve Jones
    Working on implementing image descriptions to a php run gallery and can't seem to figure out how to call each text file for each individual image. //total number of images $total = 77; //max number of thumbnails per page $max = 9; //what image do we want to start from? $startcount = $_GET["start"]; //if there is not a defined starting image, we start with the first if(empty($startcount)) { $startcount = 0; } //start off the loop at 1 $loop = 1; //start the loop while($loop <= $max) { //for the picture labels $num = $startcount + $loop; if($num > $total) { $num = $num - 1; break; } // Add class="last" to every third list item if(is_int($num / 3)) { $last = ' class="last"'; } else { $last = ""; } //the code for the image echo ' <li'.$last.'><a href="images/portfolio/pic-'.$num.'.jpg" rel="milkbox[gall1]"><img src="images/portfolio/thumbs/pic-'.$num.'-thumb.jpg" width="256" height="138" alt="Thumbnail of image '.$num.'" /></a><div>'.$num.'</div></li>'; I see that I can call the text files by number using '.$num.' (I have 77 individual text files with a phrase in each) but how do I tell it to call the files?

    Read the article

  • PageableListView Not rendering my data as required

    - by Robin
    i am working on wicket, where i am supposed to show my data's under <tr> <td>Name</td> <td>Single Player Score</td> <td>Double Player Score</td> <td>Total Score</td> </tr> <tr wicket:id="data"> <td wicket:id="name"></td> <td wicket:id="singlePlayerScore"></td> <td wicket:id="doublePlayerScore"></td> <td wicket:id="totalScore"></td> </tr> My Player model class is as: Player class with attributes singlePlayerScore, doublePlayerScore(), name with getter and setter and also a list data obtained from database. Data from SQLQuery is as; name score gamemode A 200 singlePlayerMode A 100 doublePLayerMode B 400 singlePlayerMode B 300 doublePLayerMode dataList == player.getScoreList(); My PageableListView is as: final PageableListView listView = new PageableListView("data",dataList,10){ @Override protected void populateItem(Item item){ player = (Player)item.getModelObject(); item.add(Label("name",player.getName())); item.add(Label("singlePlayerScore",player.getName())); item.add(Label("doublePlayerScore",player.getName())); item.add(Label("totalScore",String.valueOf(player.getSinglePlayerScore()+player.getDoublePlayerScore()))); } } My Problem is as: What view i get is as: Name single Player Score Double Player Score Total Score A 0 100 100 A 200 0 200 B 0 300 300 B 400 0 400 How do i achieve below view on my webpage? Name single Player Score Double Player Score Total Score A 200 100 300 B 400 300 700 Please help me as to why is this happening? I guess my list has size four that's one reason why as to it is rendering the view? So what can i do to get as require rendering view?

    Read the article

  • Bings Search API always returns the same 10 results

    - by Dofs
    I am trying to figure Bings Seach API out. I have added the SOAP service to my solution, and I do receive results. The issue, is that the displayed results are always the same, not matter what I have set the request.Web to. When I do the search, it displays 98 results, so it isn't the lack of results. BingService soapClient = new BingService(); string resp = string.Empty; SearchRequest request = new SearchRequest(); request.AppId = ConfigurationManager.AppSettings["BingKey"]; request.Sources = new BingLiveSearchService.SourceType[] { SourceType.Web }; request.Query = query; request.Web = new BingLiveSearchService.WebRequest { Count = 10, Offset = 10 }; var response = soapClient.Search(request); if (response.Web != null && response.Web.Total > 0) { resp += "TOTAL COUNT:"+response.Web.Total +"<br/><br />"; foreach (var item in response.Web.Results) { resp += "<div style='padding-bottom:10px;'>" + item.Title + "</div>"; } }

    Read the article

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