How read separate lines from files? - c++

------------------------------------------------
Artiles for a magazine
------------------------------------------------
There are total 5 articles in the magazine
------------------------------------------------
ID : 3
Description : opis2
Price : 212
Incoming amount : 2
Outgoing amount : 0
Taxes : 0
Total : 424
Date : 20324
------------------------------------------------
ID : 3
Description : 54
Price : 123
Incoming amount : 12
Outgoing amount : 0
Taxes : 0
Total : 1476
Date : 120915
------------------------------------------------
ID : 3
Description : opsi2
Price : 12
Incoming amount : 324
Outgoing amount : 0
Taxes : 0
Total : 3888
Date : 570509
------------------------------------------------
ID : 2
Description : vopi
Price : 2
Incoming amount : 2
Outgoing amount : 0
Taxes : 0
Total : 4
Date : 951230
------------------------------------------------
ID : 1
Description : opis1
Price : 2
Incoming amount : 2
Outgoing amount : 0
Taxes : 0
Total : 4
Date : 101
------------------------------------------------
I have a file called directory.dat with the contents above. What I'm trying to do is the following.
I want to find all articles with the same ID in a given year and do the following : outgoing amount - incoming amount. So, my problem is how can I find all the articles with same ID in a given year (by the user) and do the outgoing amount-incoming amount for them, by working with the file?
I tried something like this:
ifstream directory("directory.dat");
//directory.open("directory.dat");
string line;
string priceLine = "Price : ";
int price;
while(getline(directory, line)){
if(line.find(priceLine) == 0){
cout << atoi(line.substr(priceLine.size()).c_str()) << endl;
}
}
cout << price << endl;
directory.close();
But I am far away from getting on the right track and I need some help to achieve something like this.

You need to define precisely the format of your input (perhaps as a BNF grammar). A single example is not enough. We can't guess if Artiles for a magazine is meaningful or not.
while(getline(directory, line)){
int colonpos = -1;
if (line.find("----")) {
/// check that line has only dashes, then
process_dash_line();
}
else if ((colonpos=line.find(':'))>0) {
std::string name = line.substr(0, colonpos-1);
std::string value = line.substr(colonpos+1);
process_name_value (name, value);
}
}
Also, study (and perhaps adapt) the source code of some free software C++ parsers for JSON (e.g. jsoncpp) and YAML (e.g. yaml-cpp). They will certainly give you some inspiration.
Learn more about C++ standard libraries, e.g. on cppreference.com & cplusplus.com (both sites are easy to read but are imperfect) and of course by reading the C++11 standard, or at least its draft n3337

Related

Calculate the amount of the cost of tickets finalized per material divided by the total amount of the tickets finalized

I have the following need :
Calculate the ratio between the sum of the amounts of tickets with status finalized for each material and the sum of the total amounts of the tickets finalized.
My fact table is like below :
TicketID StatusID MaterialID CategoryID Amount FKDATE
123 3 45 9 150 12/03/2021
124 5 50 4 569 11/03/2021
125 3 78 78 556 14/03/2021
126 -1 -1 -1 -1 12/03/2021
My dimension Status is like below :
StatusID Status
1 Open
2 In Process
3 Finalized
My dimension Material is like below :
MaterialID MaterielLabel
1 Bikes
.. ..
I want to exclude the TicketID with MaterialID = -1.
Try the following :
AmountFinalizedByMaterial:=
VAR AmountFinalizedByMaterialGroup =
CALCULATE (
SUM(yourFactTable[Amount]),
Status[Status] = "Finalized" ,
yourFactTable[MaterialID] <> -1)
VAR TotalAmountFinalized =
CALCULATE (
SUM(yourFactTable[Amount]),
Status[Status] = "Finalized" ,
ALL(Material)
)
RETURN
DIVIDE (
AmountFinalizedByMaterialGroup,
TotalAmountFinalized
)

Why I get this output by print %f - Python 2.7

quick question: why do I get a lot of zeros after the decimal point in the output of this script (value of "total" variable)? (I know how to deal with it and get specific outbut by walk-arounds, but I'm curious why thi iutput looks like this)
Script:
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3,
}
stock = {
"banana" : 6,
"apple" : 0,
"orange" : 32,
"pear" : 15,
}
for key in prices:
print key
print "price: %s" % prices[key]
print "stock: %s" % stock[key]
print
total = 0
for iteration in prices:
total = total+ prices[iteration] * stock[iteration]
print "total price: %f"%total
output:
banana
price: 4
stock: 6
apple
price: 2
stock: 0
orange
price: 1.5
stock: 32
pear
price: 3
stock: 15
total price: 117.000000 #********* why so many zeros?
Because that's the default number of decimal places for the %f formatter.
Add a precision specifier; for example, if you only want to display 2 decimal places, use %.2f:
print "total price: %.2f" % total
and the last line of output then becomes
total price: 117.00
The . followed by a digit in the format specification signals the precision specifier. See the String Formatting Operations documentation:
A conversion specifier contains two or more characters and has the following components, which must occur in this order:
[...]
Precision (optional), given as a '.' (dot) followed by the precision. [...]
Further on in the same documentation, the default for f is documented under footnote #3:
The precision determines the number of digits after the decimal point and defaults to 6.
you must replace %f by %d or by %i if you dont want zeros and if you want 1 zero you can replace it by %s:
>>> print "total price: %d"%total
total price: 117
>>> print "total price: %s"%total
total price: 117.0
>>> print "total price: %f"%total # Like you did
total price: 117.000000

finding avg/min/max for a dataset using mapreduce

i am trying to write a mapreduce sample practice program where in my data set is somthing like this
its about salaries of people in every year in a country/city/state
place year salary($)
america 2014 60,000
france 2010 40,000
india 2012 20,000
australia 2001 50,000
america 2014 65,000
i want output something like this
place year avg min max
america 2014 625000 600000 650000
france 2010 400000 400000 400000
please guide me how can i write a mapreduce program/ any sample program which is already handled such case.
thanks in advance :)
i have tried mapper part
public static class Map extends Mapper{
public void map(LongWritable key, Text value,
Context context)
throws IOException,InterruptedException {
String year=null;
String country =null;
String amount=null;
// this will work even if we receive more than 1 line
Scanner scanner = new Scanner(value.toString());
String line;
String[] tokens;
while (scanner.hasNext()) {
line = scanner.nextLine();
tokens = line.split("\\s+");
country = tokens[0];
year = tokens[1];
amount = (tokens[2]);
context.write(new Text(country), new Text(year));
context.write(new Text(year), new Text(amount));
}
}
}

C++ Data Parsing query

Hello guys i hope you could enlighten me with this issue i am facing!
Initial Output:
The sample text file is below and the format is as follow (Item Desc:Price:Quantity:Date).
STRAW:10:10:11NOV1991
BARLEY:5.10:5:19OCT1923
CHOCOLATE:50:50:11NOV1991
I am required to print out a daily summary report of the total amt of sales on that day. Based on the sample above, the result will be on 11 NOV 1991 the total amt of sales(2 items) will be 60 while on 19OCT1923 the total amt of sales(1 item) will be 5.
Desired Output:
11Nov1991 Total amt of sales:60
19Oct1923 Total amt of sales:5
My question is, how do i generate the code to show only one unique date with the total amount of sales? I have created a loop to check if that a certain year exist for testing purposes but it isn't working. I want it to be able to iterate through a file and check if a certain year exist and if it exist already, the next vector element that has the same year won't be written to a file but instead only the item price will be added. Below is the code i am trying to implement.
ifstream readReport("DailyReport.txt");
ofstream writeDailyReport("EditedDailyReport.txt");
string temp1 = "";
//Read from empty report.txt
while(getline(readReport,temp1))
{
for(int i=0; i < itemDescVec.size(); i++)
{
stringstream streamYearSS;
streamYearSS << itemDescVec[i].dateYear;
string stringYear = streamYearSS.str();
size_t found1 = temp1.find(stringYear);
//If can find year
if (found1 != string::npos )
{
cout << "Can find" << endl;
}
//If cannot find year
else if (found1 == string::npos )
{
cout << "Cannot find" << endl;
writeDailyReport << itemDescVec[i].itemDescription << ":" << itemDescVec[i].unitPrice << ":"
<< itemDescVec[i].quantity << ":" << itemDescVec[i].dateDay << "/" << itemDescVec[i].dateMonth << "/" << itemDescVec[i].dateYear
<< endl;
}
}
}
readReport.close();
writeDailyReport.close();
remove("DailyReport.txt");
rename("EditedDailyReport.txt", "DailyReport.txt");
It would be better to use your own object to store the data - then you can write, for example, salesRecord.quantity (or salesRecord.getQuantity() if you have written a getter) instead of salesrecord.at(2). This is a lot more readable and is better practice than remembering that 2 = quantity (etc.).
Now as to your actual question... I would say something like this:
Iterate over the list. For each item:
Check if the date of the item has already been added to your new list.
If the date does not already exist, simply add the item in its entireity.
If it does already exist, edit the existing item such that previousQuantity += quantityToAdd
On the sorted list
BARLEY:5.10:5:19OCT1923
STRAW:10:10:11NOV1991
CHOCOLATE:50:50:11NOV1991
this would work as follows:
Try to add barley data - nothing for that date so far, so add it:
19OCT1923 - 5 units
Try to add strawberry data - nothing for that date so far, so add it:
19OCT1923 - 5 units
11NOV1991 - 10 units
Try to add chocolate data - 11NOV1991 already exists, so add 50 to the 10 that's already there:
19OCT1923 - 5 units
11NOV1991 - 60 units

How do I take already calculated totals that are in a loop and add them together?

I created this program in Python 2.7.3
I did this in my Computer Science class. He assigned it in two parts. For the first part we had to create a program to calculate a monthly cell phone bill for five customers. The user inputs the number of texts, minutes, and data used. Additionaly, there are overage fees. $10 for every GB of data over the limit, $.4, per minute over the limit, and $.2 per text sent over the limit. 500 is the limit amount of text messages, 750 is the limit amount of minutes, and 2 GB is the limit amount of data for the plan.
For part 2 of the assignment. I have to calculate the total tax collected, total charges (each customer bill added together), total goverment fees collected, total customers who had overages etc.
Right now all I want help on is adding the customer bills all together. As I said earlier, when you run the program it prints the Total bill for 5 customers. I don't know how to assign those seperate totals to a variable, add them together, and then eventually print them as one big variable.
TotalBill = 0
monthly_charge = 69.99
data_plan = 30
minute = 0
tax = 1.08
govfees = 9.12
Finaltext = 0
Finalminute = 0
Finaldata = 0
Finaltax = 0
TotalCust_ovrtext = 0
TotalCust_ovrminute = 0
TotalCust_ovrdata = 0
TotalCharges = 0
for i in range (1,6):
print "Calculate your cell phone bill for this month"
text = input ("Enter texts sent/received ")
minute = input ("Enter minute's used ")
data = input ("Enter Data used ")
if data > 2:
data = (data-2)*10
TotalCust_ovrdata = TotalCust_ovrdata + 1
elif data <=2:
data = 0
if minute > 750:
minute = (minute-750)*.4
TotalCust_ovrminute = TotalCust_ovrminute + 1
elif minute <=750:
minute = 0
if text > 500:
text = (text-500)*.2
TotalCust_ovrtext = TotalCust_ovrtext + 1
elif text <=500:
text = 0
TotalBill = ((monthly_charge + data_plan + text + minute + data) * (tax)) + govfees
print ("Your Total Bill is... " + str(round(TotalBill,2)))
print "The toatal number of Customer's who went over their minute's usage limit is... " ,TotalCust_ovrminute
print "The total number of Customer's who went over their texting limit is... " ,TotalCust_ovrtext
print "The total number of Customer's who went over their data limit is... " ,TotalCust_ovrdata
Some of the variables created are not used in the program. Please overlook them.
As Preet suggested.
create another variable like TotalBill i.e.
AccumulatedBill = 0
Then at the end of your loop put.
AccumulatedBill += TotalBill
This will add each TotalBill to Accumulated. Then simply print out the result at the end.
print "Total for all customers is: %s" %(AccumulatedBill)
Note: you don't normally use uppercase on variables for the first letter of the word. Use either camelCase or underscore_separated.