How it would be possible to generate Excell reports from Play Framework v2.x(Scala). I found there's a Play-Excel module but it supports PlayFramework v1.0. Is there anything suitable for v2.x?
In the end I choose to use Spoiwo. Scala Wrapper for Apache POI. It has a neat starting guide. However, doesn't have an example with PlayFramework.
Here's my quick and dirty hack to generate simple report from case class.
def generateReportXLSX(waybillId: Long) = Action{ implicit request =>
val headerStyle =
CellStyle(fillPattern = CellFill.Solid, fillForegroundColor = Color.DarkGrey, fillBackgroundColor = Color.AquaMarine, font = Font(bold = true))
val listItems: List[Item] = Items.findByWaybillId(waybillId)
val listRows = listItems.map{ item =>
Row().withCellValues(item.id.getOrElse(1), item.itemCode, item.senderName.getOrElse(""))
}
val gettingStartedSheet = Sheet(name = "Накладная ")
.withRows(listRows)
.withColumns(
Column(index = 0, style = CellStyle(font = Font(bold = true)), autoSized = true)
)
gettingStartedSheet.saveAsXlsx("/home/user/dumps/"+waybillId+".xlsx")
Ok.sendFile(new File(("/home/user/dumps/"+waybillId+".xlsx")))
}
Related
I am trying to create a dashboard of data for our university, and have run into a problem with how it is presenting. I am using Bokeh and Python to create somewhat interactive graphs. My checkbox group is not updating when I click a box to select the college for the major. I have tried changing several items, but cannot figure out what I am doing wrong.
My code:
# Available college list
available_colleges = list(df['College'].unique())
source_maj = ColumnDataSource(df)
grouped_maj = df.groupby('Major').sum()
source_maj = ColumnDataSource(grouped_maj)
major = source_maj.data['Major'].tolist()
p_maj = figure(x_range=major, width=1100, height=500)
p_maj.xaxis.major_label_orientation = math.pi/4
color_map = factor_cmap(field_name='Major',
palette=Magma11, factors=level)
p_maj.vbar(x='Major', top='AY2018_19', source=source_maj, width=0.2, color=color_map)
p_maj.title.text ='Enrollment by Major'
p_maj.xaxis.axis_label = 'Major'
p_maj.yaxis.axis_label = 'Enrolled Students'
hover = HoverTool()
hover.tooltips = [
("2019-2020", "#AY2019_20"),
("2018-2019", "#AY2018_19"),
("2017-2018", "#AY2017_18")]
hover.mode = 'vline'
callback = CustomJS(args=dict(source=source_maj), code="""
const labels = cb_obj.labels;
const active = cb_obj.active;
const data = source_maj.data;
const sourceLen = data.combined.length;
const combined = Array(sourceLen).fill(undefined);
if (active.length > 0) {
const selectedColumns = labels.filter((val, ind) => active.includes(ind));
for(let i = 0; i < sourceLen; i++) {
let sum = 0;
for(col of selectedColumns){
sum += Major[col][i];
}
combined[i] = sum;
}
}
Major.combined=combined;
source_maj.change.emit();
""")
colleges_selection = CheckboxGroup(labels=available_colleges, active = [0], callback=callback)
controls = WidgetBox(colleges_selection)
p_maj = row(controls, p_maj)
Data is formated in a csv sheet that is being read
What it looks like, but nothing updates
Any help is greatly appreciated.
You'll probably want to watch the output the browser sends to the javascript console; it'll tell you what's going wrong here.
A couple places to start: your arguments to the CustomJS object bring in the python object 'source_maj' and rename it as 'source', but then in your JS code you refer to it as 'source_maj'. Also, your JS code makes reference to 'Major', but this isn't an object that the JS knows about (i.e. it wasn't brought in with the args).
I'm trying to save a print layout as BMP in QGIS through python code, but want to turn of antialiasing and can't seem to figure out how to do it
def saveImage(self, layout, filename="defaultexport", extension=".bmp"):
"""Saves given layout as an image"""
filefolder = get_save_location()
filepath = os.path.join(filefolder, filename + extension)
if not os.path.isdir(filefolder):
os.makedirs(filefolder)
exporter = QgsLayoutExporter(layout)
context = QgsLayoutRenderContext(layout)
context.setFlag(context.FlagAntialiasing, False)
export_settings = exporter.ImageExportSettings()
export_settings.generateWorldFile = False
export_settings.dpi = 25
export_settings.flags = context.FlagAntialiasing
result = exporter.exportToImage(filepath, export_settings)
Is what I have. I have no idea what I'm doing with the QgsLayoutRenderContext, but it's about the only thing that seemed like it might do it. Saving manually and turning of the AA setting in save dialog works fine, but I need to do it through pyqgis
Revisting this project knowing some more Python and PyQt5 stuff this was an easy one
exporter = QgsLayoutExporter(layout)
context = QgsLayoutRenderContext(layout)
context.setFlag(context.FlagAntialiasing, False)
export_settings = exporter.ImageExportSettings()
export_settings.generateWorldFile = False
export_settings.dpi = 25
export_settings.flags = context.flags()
result = exporter.exportToImage(self.filepath, export_settings)
Needed to use context.flags()
I am assigning different data to one dataframe. And I had the following
ValueError: If using all scalar values, you must pass an index
I follow the question post by other Here
But it did not work out.
The following is my code. All you have to do is copy and paste the code to IDE.
import pandas as pd
import numpy as np
#Loading Team performance Data (ExpG (Home away)) For and against
epl_1718 = pd.read_csv("http://www.football-data.co.uk/mmz4281/1718/E0.csv")
epl_1718 = epl_1718[['HomeTeam','AwayTeam','FTHG','FTAG']]
epl_1718 = epl_1718.rename(columns={'FTHG': 'HomeGoals', 'FTAG': 'AwayGoals'})
Home_goal_avg = epl_1718['HomeGoals'].mean()
Away_goal_avg = epl_1718['AwayGoals'].mean()
Home_team_goals = epl_1718.groupby(['HomeTeam'])['HomeGoals'].sum()
Home_count = epl_1718.groupby(['HomeTeam'])['HomeTeam'].count()
Home_team_avg_goal = Home_team_goals/Home_count
Home_team_concede = epl_1718.groupby(['HomeTeam'])['AwayGoals'].sum()
EPL_Home_average_score = epl_1718['HomeGoals'].mean()
EPL_Home_average_conc = epl_1718['HomeGoals'].mean()
Home_team_avg_conc = Home_team_concede/Home_count
Away_team_goals = epl_1718.groupby(['AwayTeam'])['AwayGoals'].sum()
Away_count = epl_1718.groupby(['AwayTeam'])['AwayTeam'].count()
Away_team_avg_goal = Away_team_goals/Away_count
Away_team_concede = epl_1718.groupby(['AwayTeam'])['HomeGoals'].sum()
EPL_Away_average_score = epl_1718['AwayGoals'].mean()
EPL_Away_average_conc = epl_1718['HomeGoals'].mean()
Away_team_avg_conc = Away_team_concede/Away_count
Home_attk_sth = Home_team_avg_goal/EPL_Home_average_score
Home_attk_sth = Home_attk_sth.sort_index().reset_index()
Home_def_sth = Home_team_avg_conc/EPL_Home_average_conc
Home_def_sth = Home_def_sth .sort_index().reset_index()
Away_attk_sth = Away_team_avg_goal/EPL_Away_average_score
Away_attk_sth = Away_attk_sth .sort_index().reset_index()
Away_def_sth = Away_team_avg_conc/EPL_Away_average_conc
Away_def_sth = Away_def_sth.sort_index().reset_index()
Home_def_sth
HomeTeam = epl_1718['HomeTeam'].drop_duplicates().sort_index().reset_index().set_index('HomeTeam')
AwayTeam = epl_1718['AwayTeam'].drop_duplicates().sort_index().reset_index().sort_values(['AwayTeam']).set_index(['AwayTeam'])
#HomeTeam = HomeTeam.sort_index().reset_index()
Team = HomeTeam.append(AwayTeam).drop_duplicates()
Data = pd.DataFrame({"Team":Team,
"Home_attkacking":Home_attk_sth,
"Home_def": Home_def_sth,
"Away_Attacking":Away_attk_sth,
"Away_def":Away_def_sth,
"EPL_Home_avg_score":EPL_Home_average_score,
"EPL_Home_average_conc":EPL_Home_average_conc,
"EPL_Away_average_score":EPL_Away_average_score,
"EPL_Away_average_conc":EPL_Away_average_conc},
columns =['Team','Home_attacking','Home_def','Away_attacking','Away_def',
'EPL_Home_avg_score','EPL_Home_avg_conc','EPL_Away_avg_score','EPL_Away_average_conc'])
In this code, what I am trying to do is to get average goal score per team per game, average goals conceded per team per game.
And then I am calculating other performance factors such as attacking strength, defensive strenght etc.
I have to paste the code as if i use example, creating data frame would work.
Thanks for understanding.
Thanks in advance for the advice too.
The format (or the columns) of final data frame will look like as follow:
Team Home Attacking Home Defensive Away attacking away defensive
and so on as mentioned in the data frame.
It means, there will be only 20 teams under team columns
The shape of dataframe will be ( 20,9)
Regards,
Zep
Here main idea is remove reset_index for Series with index by teams, so variable Team is not necessary and is created as last step by reset_index. Also be carefull with columns names in DataFrame constructor, if there are changed like EPL_Home_average_conc in dictionary and then EPL_Home_avg_conc get NaNs columns:
Home_team_goals = epl_1718.groupby(['HomeTeam'])['HomeGoals'].sum()
Home_count = epl_1718.groupby(['HomeTeam'])['HomeTeam'].count()
Home_team_avg_goal = Home_team_goals/Home_count
Home_team_concede = epl_1718.groupby(['HomeTeam'])['AwayGoals'].sum()
EPL_Home_average_score = epl_1718['HomeGoals'].mean()
EPL_Home_average_conc = epl_1718['HomeGoals'].mean()
Home_team_avg_conc = Home_team_concede/Home_count
Away_team_goals = epl_1718.groupby(['AwayTeam'])['AwayGoals'].sum()
Away_count = epl_1718.groupby(['AwayTeam'])['AwayTeam'].count()
Away_team_avg_goal = Away_team_goals/Away_count
Away_team_concede = epl_1718.groupby(['AwayTeam'])['HomeGoals'].sum()
EPL_Away_average_score = epl_1718['AwayGoals'].mean()
EPL_Away_average_conc = epl_1718['HomeGoals'].mean()
Away_team_avg_conc = Away_team_concede/Away_count
#removed reset_index
Home_attk_sth = Home_team_avg_goal/EPL_Home_average_score
Home_attk_sth = Home_attk_sth.sort_index()
Home_def_sth = Home_team_avg_conc/EPL_Home_average_conc
Home_def_sth = Home_def_sth .sort_index()
Away_attk_sth = Away_team_avg_goal/EPL_Away_average_score
Away_attk_sth = Away_attk_sth .sort_index()
Away_def_sth = Away_team_avg_conc/EPL_Away_average_conc
Away_def_sth = Away_def_sth.sort_index()
Data = pd.DataFrame({"Home_attacking":Home_attk_sth,
"Home_def": Home_def_sth,
"Away_attacking":Away_attk_sth,
"Away_def":Away_def_sth,
"EPL_Home_average_score":EPL_Home_average_score,
"EPL_Home_average_conc":EPL_Home_average_conc,
"EPL_Away_average_score":EPL_Away_average_score,
"EPL_Away_average_conc":EPL_Away_average_conc},
columns =['Home_attacking','Home_def','Away_attacking','Away_def',
'EPL_Home_average_score','EPL_Home_average_conc',
'EPL_Away_average_score','EPL_Away_average_conc'])
#column from index
Data = Data.rename_axis('Team').reset_index()
print (Data)
I have a function to load sounds, but not one for loading images. This is how my image loading is layed out currently:
if os.path.exists("themes/voltorb"):
vgui = pygame.image.load("themes/voltorb/gui.png")
voptions = pygame.image.load("themes/voltorb/options.png")
vachievements = pygame.image.load("themes/voltorb/achievements.png")
voverlay = pygame.image.load("themes/voltorb/overlay.png")
vconfirm = pygame.image.load("themes/voltorb/confirm.png")
vboom = pygame.mixer.Sound("themes/voltorb/boom.mp3")
vcoin = pygame.mixer.Sound("themes/voltorb/coin.mp3")
vtheme = {"gui":vgui,"options":voptions,"achievements":vachievements,"overlay":voverlay,"confirm":vconfirm,"coin":vcoin,"boom":vboom,"music":vmusic}
themedb.update({"v":vtheme})
if os.path.exists("themes/fluttershy"):
fcoin = pygame.mixer.Sound("themes/fluttershy/coin.mp3")
fgui = pygame.image.load("themes/fluttershy/gui.png")
foptions = pygame.image.load("themes/fluttershy/options.png")
fachievements = pygame.image.load("themes/fluttershy/achievements.png")
foverlay = pygame.image.load("themes/fluttershy/overlay.png")
ftheme = {"gui":fgui,"options":foptions,"achievements":fachievements,"overlay":foverlay,"confirm":fconfirm,"coin":vcoin,"boom":vboom,"music":vmusic}
themedb.update({"f":ftheme})
if os.path.exists("themes/mario"):
mgui = pygame.image.load("themes/mario/gui.png")
moptions = pygame.image.load("themes/mario/options.png")
machievements = pygame.image.load("themes/mario/achievements.png")
moverlay = pygame.image.load("themes/mario/overlay.png")
mtheme = {"gui":mgui,"options":moptions,"achievements":machievements,"overlay":moverlay,"confirm":mconfirm,"coin":vcoin,"boom":vboom,"music":vmusic}
themedb.update({"m":mtheme})
if os.path.exists("%appdata%/KWScripts/Voltorb/themes/secret1"):
s1gui = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret1/gui.png")
s1options = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret1/options.png")
s1achievements = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret1/achievements.png")
s1overlay = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret1/overlay.png")
s1theme = {"gui":s1gui,"options":s1options,"achievements":s1achievements,"overlay":s1overlay,"confirm":s1confirm,"coin":vcoin,"boom":vboom,"music":vmusic}
themedb.update({"s1":s1theme})
if os.path.exists("%appdata%/KWScripts/Voltorb/themes/secret2"):
s2gui = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret2/gui.png")
s2options = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret2/options.png")
s2achievements = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret2/achievements.png")
s2overlay = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret2/overlay.png")
s2theme = {"gui":s2gui,"options":s2options,"achievements":s2achievements,"overlay":s2overlay,"confirm":s2confirm,"coin":s2coin,"boom":s2boom,"music":s2music}
themedb.update({"s2":s2theme})
if os.path.exists("%appdata%/KWScripts/Voltorb/themes/secret3"):
s3gui = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret3/gui.png")
s3options = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret3/options.png")
s3achievements = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret3/achievements.png")
s3overlay = pygame.image.load("%appdata%/KWScripts/Voltorb/themes/secret3/overlay.png")
s3theme = {"gui":s3gui,"options":s3options,"achievements":s3achievements,"overlay":s3overlay,"confirm":s3confirm,"coin":s3coin,"boom":s3boom,"music":s3music}
themedb.update({"s3":s3theme})
I'm not sure if there's any easy way to do this, but I have the most difficult way typed already. If anyone has an idea of how to shorten this, then thanks!
Take all your images and put them in a dict, where the key is the variable you were using, and the value is the path:
vimages = {'vgui': "themes/voltorb/gui.png", 'voptions': "themes/voltorb/options.png", 'vachievements': "themes/voltorb/achievements.png"} # and so on...
Then, iterate through vimages, checking for the existence of each individual file, then calling pygame.image.load() on it, and store the result in your already-existing dict (vtheme, in this case).
This way, you don't need to keep writing out pygame.image.load() over and over again.
Given the following code, is there anyway to get Automapper to do this instead of manually setting the properties? I'm trying to avoid having to do a one to one mapping at Mapper.CreateMap, since I;m constantly adding and removing fields from Contract, and at the moment have to remember to update this method with the changes.
private void MapModelToContract(ContractDto model, Contract contract)
{
contract.Id = model.Id;
contract.ContractDetail.BuyerCornhouseName = model.ContractDetailBuyerCornhouseName;
contract.ContractDetail.CnoCornLtdToBuyer = model.ContractDetailCnoCornLtdToBuyer;
contract.ContractDetail.CnoCornPartToCornLtd = model.ContractDetailCnoCornPartToCornLtd;
contract.ContractDetail.CnoSellerCornLtd = model.ContractDetailCnoSellerCornLtd;
contract.ContractDetail.CnoSellerCornPart = model.ContractDetailCnoSellerCornPart;
contract.ContractDetail.Commission = model.ContractDetailCommission;
contract.ContractDetail.ContractPrice = model.ContractDetailContractPrice;
contract.ContractDetail.SalesPriceToCornLtd = model.ContractDetailSalesPriceToCornLtd;
contract.ContractDetail.ContractedQuantity = model.ContractDetailContractedQuantity;
contract.ContractDetail.CostWarehouseToFob = model.ContractDetailCostWarehouseToFob;
contract.ContractDetail.Date = model.ContractDetailDate;
contract.ContractDetail.DeliveryDate = model.ContractDetailDeliveryDate;
contract.ContractDetail.FinalBuyerName = model.ContractDetailFinalBuyerName;
contract.ContractDetail.FinalSalesPrice = model.ContractDetailFinalSalesPrice;
contract.ContractDetail.Grade = model.ContractDetailGrade;
contract.ContractDetail.Notes = model.ContractDetailNotes;
contract.ContractDetail.PayableQuantity = model.ContractDetailPayableQuantity;
contract.ContractDetail.SalesShipmentPeriod = model.ContractDetailSalesShipmentPeriod;
contract.ContractDetail.SellerName = model.ContractDetailSellerName;
contract.ContractDetail.ToBePaidBy = model.ContractDetailToBePaidBy;
contract.ContractDetail.SalesBasis = model.ContractDetailSalesBasis;
contract.ContractDetail.SalesFreightValue = model.ContractDetailSalesFreightValue;
contract.CurrencyContract.Date = model.CurrencyContractDate;
contract.CurrencyContract.ExchangeRate = model.CurrencyContractExchangeRate;
contract.CurrencyContract.Number = model.CurrencyContractNumber;
contract.CurrencyContract.Value = model.CurrencyContractValue;
contract.CurrencyContract.IsAcc = model.CurrencyContractIsAcc;
contract.CurrencyContract.RepaidOn = model.CurrencyContractRepaidOn;
contract.CurrencyContract.RepaymentDate = model.CurrencyContractRepaymentDate;
contract.Discounts.Reason = model.DiscountsReason;
contract.Discounts.Value = model.DiscountsValue;
contract.DocumentControl.GuaranteeLetterReceived = model.DocumentControlGuaranteeLetterReceived;
contract.DocumentControl.PhotosReceived = model.DocumentControlPhotosReceived;
contract.GoodsStatus.ContainerNumber = model.GoodsStatusContainerNumber;
contract.GoodsStatus.EtaPort = model.GoodsStatusEtaPort;
contract.GoodsStatus.ExpectedDeliveryDate = model.GoodsStatusExpectedDeliveryDate;
contract.GoodsStatus.Port = model.GoodsStatusPort;
contract.GoodsStatus.ShippedStatus = model.GoodsStatusShippedStatus;
contract.GoodsStatus.VesselDeadline = model.GoodsStatusVesselDeadline;
contract.GoodsStatus.VesselName = model.GoodsStatusVesselName;
contract.GoodsStatus.HasSellerConfirmedRelease = model.GoodsStatusHasSellerConfirmedRelease;
contract.GoodsStatus.ReceivedShippingInstructions = model.GoodsStatusReceivedShippingInstructions;
contract.GoodsStatus.Notes = model.GoodsStatusNotes;
contract.NotaFiscalCornPart.Date = model.NotaFiscalCornPartDate;
contract.NotaFiscalCornPart.ExchangeRate = model.NotaFiscalCornPartExchangeRate;
contract.NotaFiscalCornPart.Number = model.NotaFiscalCornPartNumber;
contract.NotaFiscalSeller.Date = model.NotaFiscalSellerDate;
contract.NotaFiscalSeller.GoodsReleased = model.NotaFiscalSellerGoodsReleased;
contract.NotaFiscalSeller.Number = model.NotaFiscalSellerNumber;
contract.TransferToSeller.Date = model.TransferToSellerDate;
contract.TransferToSeller.TransferredFrom = model.ContractDetailBuyerCornhouseName;
contract.TransferToSeller.Value = model.TransferToSellerValue;
contract.CommissionLawyer.IsPaid = model.CommissionLawyerIsPaid;
}
The below mapper works for you.
If the Source (ContractDto) and Destination (Contract) have same property names.
Mapper.CreateMap<ContractDto, Contract>(); // Maps if ContractDto & Contract have same property names
If the Source (ContractDto) and Destination (Contract) have diff property names. Then
Mapper.CreateMap<ContractDto, Contract>()
.ForMember(destination => destination.BuyerCornhouseName, options => options.MapFrom(source => source.ContractDetailBuyerCornhouseName))
.ForMember(destination => destination.CnoCornLtdToBuyer, options => options.MapFrom(source => source.ContractDetailCnoCornLtdToBuyer));
// Explicitly you have specify for other properties also