seq_id string | text string | repo_name string | sub_path string | file_name string | file_ext string | file_size_in_byte int64 | program_lang string | lang string | doc_type string | stars int64 | dataset string | pt string | api list |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
32156093476 | import torch
def xform_transpose(xform):
s = list(range(len(xform.shape)))
s[-1], s[-2] = s[-2], s[-1]
return xform.permute(*s)
def xform_fk_vel(lxform, lpos, lvrt, lvel, parents):
gr, gp, gt, gv = [lxform[..., :1, :, :]], [lpos[..., :1, :]], [lvrt[..., :1, :]], [lvel[..., :1, :]]
for i in range(1, len(parents)):
p = parents[i]
gp.append(gp[p] + torch.matmul(gr[p], lpos[..., i:i + 1, :][..., None])[..., 0])
gr.append(torch.matmul(gr[p], lxform[..., i:i + 1, :, :]))
gt.append(gt[p] + torch.matmul(gr[p], lvrt[..., i:i + 1, :][..., None])[..., 0])
gv.append(gv[p] + torch.matmul(gr[p], lvel[..., i:i + 1, :][..., None])[..., 0] +
torch.cross(gt[p], torch.matmul(gr[p], lpos[..., i:i + 1, :][..., None])[..., 0], dim=-1))
return torch.cat(gr, dim=-3), torch.cat(gp, dim=-2), torch.cat(gt, dim=-2), torch.cat(gv, dim=-2)
def xform_orthogonalize_from_xy(xy, eps=1e-10):
xaxis = xy[..., 0:1, :]
zaxis = torch.cross(xaxis, xy[..., 1:2, :])
yaxis = torch.cross(zaxis, xaxis)
output = torch.cat([
xaxis / (torch.norm(xaxis, 2, dim=-1)[..., None] + eps),
yaxis / (torch.norm(yaxis, 2, dim=-1)[..., None] + eps),
zaxis / (torch.norm(zaxis, 2, dim=-1)[..., None] + eps)
], dim=-2)
return xform_transpose(output)
| ubisoft/ubisoft-laforge-ZeroEGGS | ZEGGS/anim/txform.py | txform.py | py | 1,378 | python | en | code | 331 | github-code | 1 | [
{
"api_name": "torch.matmul",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "torch.matmul",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "torch.matmul",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "torch.matmul",
"line_numbe... |
39560810668 | import copy
from BU.NTS.dataCheck.dataCheck import getNowAccount,warning_rate,isOpen,t_risk_limit_leverage
from param.dict import SuccessMessage,FailMessage
from common import mysqlClient
from common.other import httpCheck as e
from UnitTest.com import LogName
from common.util import truncate, printc, printl, d, Count,LogOut
import BU.NTS.Calculator as cal
log_level = 0
thisCaseNumber = 0
tradeType = 'linearPerpetual';
symbol = 'BTCUSDT'
currency = 'USDT'
pageNum = 1
pageSize = 100
t = mysqlClient.mysql(7)
class Formula():
def __init__(self,NTS_,symbol):
MarginIsolated=0;unRealIsolated=0;MarginCross=0;unReal=0;Isolated={};OpenOrderDic={};PositionDic={}
global NTS
self.NTS = NTS_;NTS = NTS_
self.instrumentList = NTS.instrumentList;Instument=NTS.instrument[symbol[:-4]]
self.TakerFeeRate=Instument[2]
self.CtVal = Instument[1]
self.FundingRate=-0.0018830852
self.MarkPrice = {"BTCUSDT": 16000, "ETHUSDT": 1600};self.Symbol=symbol
self.IndexPrice = {"BTCUSDT": 16000, "ETHUSDT": 1600};
self.CalOpenOrderDic=self.CalOpenOrder(self.instrumentList)
self.CalPositionDic=self.CalPosition(self.instrumentList)
self.Balance=self.Balance()
self.Leverage=self.GetLeverage()
self.WarnX=self.GetWarnX()
if self.CalPositionDic:
self.Equity_Isolated_Long=self.CalPositionDic[self.Symbol]['isolated_long'][1]#逐仓-多仓权益
self.Equity_Isolated_Short = self.CalPositionDic[self.Symbol]['isolated_short'][1] #逐仓-空仓权益
self.PositionQty_Isolated_Long=self.CalPositionDic[self.Symbol]['isolated_long'][5] #逐仓- 多仓 持仓数量
self.PositionQty_Isolated_Short = self.CalPositionDic[self.Symbol]['isolated_short'][5] # 逐仓- 多仓 持仓数量
self.PositionValue_Isolated_Long=self.CalPositionDic[self.Symbol]['isolated_long'][0] #逐仓-多仓 持仓价值
self.PositionValue_Isolated_Short = self.CalPositionDic[self.Symbol]['isolated_short'][0] # 逐仓-多仓 持仓价值
self.PositionValue_Cross_Short = self.CalPositionDic[self.Symbol]['cross_short'][0] # 全仓-空仓 持仓价值
self.PositionValue_Cross_Long = self.CalPositionDic[self.Symbol]['cross_long'][0] # 全仓-多仓 持仓价值
# 掛單接口:
def CalOpenOrder(self,instrumentList):
OpenOrderDic={};FrozenMargin=d(0);DefaultList=[0,0];
for symbol in instrumentList:
OpenOrderDic[symbol]={'isolated_buy':copy.deepcopy(DefaultList),'isolated_sell':copy.deepcopy(DefaultList),'cross_buy':copy.deepcopy(DefaultList),'cross_sell':copy.deepcopy(DefaultList)};
OpenOrderRes = self.NTS.OpenOrders(tradeType=tradeType, pageSize=100);
if e(OpenOrderRes)[0]:
for openOrder in OpenOrderRes['data']['list']:
symbol=openOrder['symbol']
coinValue = d(self.NTS.instrument[symbol[:-4]][1])
Key = openOrder['marginType'] + '_' + openOrder['side']
#分别计算:挂单价值
if isOpen(openOrder['side'], openOrder['positionSide']):
OpenOrderDic[symbol][Key][0] = OpenOrderDic[symbol][Key][0] + d(openOrder['leavesQty']) * d(openOrder['price']) * coinValue
FrozenMargin =FrozenMargin+ cal.FrozenMargin(openOrder['side'], openOrder['price'], openOrder['leavesQty'],self.TakerFeeRate,openOrder['leverage'],self.CtVal)
else:
OpenOrderDic[symbol][Key][1]=OpenOrderDic[symbol][Key][1]+float(openOrder['leavesQty'])
# print(openOrder['symbol'],openOrder['positionSide'],openOrder['leavesQty'])
if OpenOrderRes['data']['totalPage'] > 1:
for i in range(OpenOrderRes['data']['totalPage']):
if i + 2 <= OpenOrderRes['data']['totalPage']:
OpenOrderRes = NTS.openOrders(log_level=log_level, tradeType=tradeType,pageSize=100, pageNum=i + 2);
for openOrder in OpenOrderRes['data']['list']:
symbol = openOrder['symbol']
if isOpen(openOrder['side'], openOrder['positionSide']):
FrozenMargin = FrozenMargin + cal.FrozenMargin(openOrder['side'],openOrder['price'],openOrder['leavesQty'],self.TakerFeeRate,openOrder['leverage'], self.CtVal)
self.FrozenMargin=FrozenMargin
return OpenOrderDic
#持仓接口: 获取持仓价值、维持保证金率
def CalPosition(self,instrumentList):
PositionDic = {};self.PositionMargin_Cross=d(0);self.UnReal_Cross=d(0);self.PositionMargin_Isolated=d(0);self.UnReal_Isolated=d(0);
self.CalPositionMap={};PositionMap={};self.PositionMap=PositionMap
for symbol in instrumentList:
DefaultList=[0,0,0,0,0,0];DefaultDic={};
PositionDic[symbol]={'isolated_long':copy.deepcopy(DefaultList),'isolated_short':copy.deepcopy(DefaultList),'cross_long':copy.deepcopy(DefaultList),'cross_short':copy.deepcopy(DefaultList)}
PositionMap[symbol]={'isolated_long': {},'isolated_short':copy.deepcopy(DefaultDic),'cross_long':copy.deepcopy(DefaultDic),'cross_short':copy.deepcopy(DefaultDic)}
PositionRes = self.NTS.position(log_level=0, tradeType='linearPerpetual')
if e(PositionRes)[0]:
if PositionRes['data'].__len__() > 0:
for i in PositionRes['data']:
Key = i['marginType'] + '_' + i['positionSide'];symbol=i['symbol']
positionMargin = 'posMargin' if 'positionMargin' not in i.keys() else 'positionMargin';
# MarkPrice = d(19500) if symbol == 'BTCUSDT' else d(1800)
positionValue = self.MarkPrice[symbol] * d(i['positionAmt']) * d(self.NTS.instrument[symbol[:-4]][1])
PositionDic[symbol][Key][0]=positionValue
PositionDic[symbol][Key][1]=d(i[positionMargin]) + d(i['unrealisedPnl'])
if self.NTS.source=='API':
PositionDic[symbol][Key][2] = i['maintMarginRatio']
PositionDic[symbol][Key][3] = i['insuranceLevel']
PositionDic[symbol][Key][4] = i['availPos']
PositionDic[symbol][Key][5] = i['positionAmt']
CalUnRealisePnl=cal.UnRealisePnl(i['positionSide'], self.MarkPrice[symbol], i['avgEntryPrice'], i['positionAmt'],self.CtVal)
CalPositionMargin=cal.PositionMargin(self.MarkPrice[symbol], i['positionAmt'],self.CtVal,i['leverage'])
PositionMap[symbol][Key]['CalUnRealisePnl']=CalUnRealisePnl
PositionMap[symbol][Key]['CalPositionMargin'] = CalPositionMargin
PositionMap[symbol][Key]['UnRealisePnl']=i['unrealisedPnl']
PositionMap[symbol][Key]['positionSide']=i['positionSide']
PositionMap[symbol][Key]['symbol'] = i['symbol']
PositionMap[symbol][Key]['markPrice'] =self.MarkPrice[symbol]
PositionMap[symbol][Key]['positionMargin'] = i['positionMargin'] if not self.NTS.source=='web' else i['posMargin']
if self.NTS.source=='web' : PositionMap[symbol][Key]['earningRate'] = i['earningRate']
PositionMap[symbol][Key]['avgEntryPrice_positionAmt_ctVal'] = i['avgEntryPrice']+'_'+i['positionAmt']+'_'+self.CtVal
# self.CalPositionMap[symbol]={}
# self.CalPositionMap[symbol].update({Key:CalUnRealisePnl})
#单独 计算 全仓、逐仓 的 总持仓冻结、总未实现盈亏
if i['marginType']=='cross': self.PositionMargin_Cross+=d(i[positionMargin]);self.UnReal_Cross+=d(i['unrealisedPnl']);
else: self.PositionMargin_Isolated += d(i[positionMargin]);self.UnReal_Isolated+=d(i['unrealisedPnl']);
self.PositionMap=PositionMap
else:print(f'{self.NTS.user_id}持仓查询异常:',e(PositionRes));return False
return PositionDic
# 资金接口
def Balance(self):
BalanceRes=self.NTS.Balance(currency='USDT');
if e(BalanceRes)[0]:
BalanceRes=BalanceRes['data'][0]
self.Balance_Equity=BalanceRes['marginEquity']
self.Balance_Unreal = BalanceRes['profitUnreal'] if self.NTS.source=='API' else 0
self.Balance_Frozen = BalanceRes['marginFrozen']
self.Balance_MarginPosition=BalanceRes['marginPosition']
self.Balance_Available = BalanceRes['marginAvailable']
self.Balance_WithDrawAmount= BalanceRes['maxWithdrawAmount']
else:printc(NTS.source+'资金查询异常',BalanceRes)
#获取风险系数
def GetWarnX(self):
warnX = warning_rate(self.Symbol);warningX = warnX[0][0]
return warningX
#最大划转、可用保证金计算
def MaxTransferOut(self,marginType,log_level=None):
symbol=self.Symbol; result=True
if marginType=='isolated':
# warnX = warning_rate(symbol);warningX = warnX[0][0] #风险系数
MaintMarginRatio=self.CalPositionDic[symbol][marginType+'_long'][2]
Equity=self.CalPositionDic[symbol][marginType+'_long'][1]
PositionAviQty=self.CalPositionDic[symbol][marginType+'_long'][4]
MarkPrice=self.MarkPrice[symbol]
WarnMarginRate=d(self.WarnX)*d(MaintMarginRatio)
printl(log_level,f'marginType={marginType},权益={Equity},WarnMarginRate={WarnMarginRate},FundingRate={self.FundingRate},PositionQty={PositionAviQty},MarkPrice{MarkPrice}')
TransferAmout=cal.TransferAmount(MarginType=marginType,EquityIsolated=Equity,WarnMarginRate=WarnMarginRate,Side='buy',FundingRate=self.FundingRate,TakerFeeRate=self.TakerFeeRate,PositionQty=PositionAviQty,MarkPrice=MarkPrice,Ctval=self.CtVal,log_level=log_level)
printl(log_level,f'{symbol} {marginType} buy 最大可转出',TransferAmout)
else:
self.Amount = getNowAccount(NTS.user_id)
equity=d(self.Amount)+d(self.UnReal_Isolated)+d(self.UnReal_Cross)
# printl(log_level,f'全仓保证金: {self.PositionMargin_Cross}')
# printl(log_level,f'逐仓保证金: {self.PositionMargin_Isolated}')
# printl(log_level, f'逐仓未实现盈亏: {self.UnReal_Isolated}')
# printl(log_level, f'冻结资金: {self.Balance_Frozen}')
AvailMargin=cal.AvailMargin(equity, self.Balance_Frozen, self.PositionMargin_Cross, self.PositionMargin_Isolated + self.UnReal_Isolated, 0)
TransferAmout = cal.TransferAmount(AvailMargin,self.Amount)
if float(AvailMargin)==float(self.Balance_Available): pass #printl(log_level,'可用保证金'+SuccessMessage);Count('公式-可用保证金',1,1,0,0)
else: pass
# printc('公式-可用保证金'+FailMessage,' 预期:',AvailMargin,'实际:',self.Balance_Available);Count('公式-可用保证金',1,1,0,0)
# LogOut('公式-可用保证金'+FailMessage,LogName)
# LogOut(f' 账户权益 {equity} 余额{self.Amount}+ 逐仓未实现盈亏{self.UnReal_Isolated}+ 全仓未实现盈亏{self.UnReal_Cross}',LogName)
# LogOut(f'冻结资金: {self.Balance_Frozen}全仓保证金: {self.PositionMargin_Cross}逐仓保证金: {self.PositionMargin_Isolated} ',LogName)
self.MaxTransferOut_={"Cal_TransferAmout":TransferAmout,"Balance_WithDrawAmount":self.Balance_WithDrawAmount,"Equity":equity,"PositionMargin_Cross":self.PositionMargin_Cross,"PositionMargin_Isolated":self.PositionMargin_Isolated,"UnReal_Isolated":self.UnReal_Isolated,"Balance_Frozen":self.Balance_Frozen}
if float(TransferAmout)==float(self.Balance_WithDrawAmount): printl(log_level,self.NTS.source+'公式-最大可划转'+SuccessMessage);Count(self.NTS.source+'公式-最大可划转',1,1,0,0);
else: printc(NTS.user_id+NTS.source+'公式-最大可划转'+FailMessage,' 预期:',TransferAmout,'实际:',self.Balance_WithDrawAmount);Count('公式-最大可划转',1,0,1,0);LogOut('公式-最大可划转'+FailMessage+str(self.MaxTransferOut_),LogName);result=False
return [TransferAmout,result]
#维持保证金、风险率 计算 - brian
def MaintMaringCal(self,marginType,log_level=None,PositionSide='long'):
O=self.CalOpenOrderDic[self.Symbol]
MaintMargin = d(0)
if marginType=='cross':
for symbol in self.instrumentList:
P = self.CalPositionDic[symbol]
Number=0
for i in P:
if marginType in str(i):
Number+=1
#维持保证金=维持保证金率*数量*面值*标记价
Tem=d(P[i][2])*d(P[i][4])*d(self.CtVal)*self.MarkPrice[symbol]
MaintMargin+=Tem
# print(symbol,i,Tem)
printl(log_level,'总维持保证金',MaintMargin)
Equity=(d(self.Balance_Available) + d(self.PositionMargin_Cross))
RiskRate=d(MaintMargin)/Equity
printl(log_level,'风险率:',RiskRate)
return [MaintMargin, Equity, MaintMargin / Equity]
else:
P = self.CalPositionDic[self.Symbol]
for i in P:
if marginType+'_'+PositionSide in str(i):
MaintMargin=d(P[i][2])*d(P[i][4])*d(self.CtVal)*d(self.MarkPrice[self.Symbol])
Equity=self.PositionMargin_Isolated+self.UnReal_Isolated
printl(log_level,f'维持保证金={MaintMargin},权益={Equity},风险率={MaintMargin/Equity}')
return [MaintMargin,Equity,MaintMargin/Equity]
#冻结保证金 对比 - Case
def FrozenMarginAssert(self,log_level=None):
ModuleName='公式-冻结保证金'
printl(log_level,f'挂单计算的冻结保证金:{self.FrozenMargin}, 资金接口返回的冻结保证金:{self.Balance_Frozen}')
if float(self.FrozenMargin)==float(self.Balance_Frozen):
printl(log_level,ModuleName+SuccessMessage);Count(ModuleName,1,1,0,0);return True
else:
printc(str(NTS.user_id)+ModuleName+FailMessage+f'挂单计算的冻结保证金:{self.FrozenMargin}, 资金接口返回的冻结保证金:{self.Balance_Frozen}')
Count(ModuleName, 1, 0, 1, 0);LogOut(ModuleName+FailMessage+f'挂单计算的冻结保证金:{self.FrozenMargin}, 资金接口返回的冻结保证金:{self.Balance_Frozen}',LogName);return False
# 冻结仓位 对比 - Case Author : Brian
def FrozenPositionAssert(self,log_level=None):
# print(self.CalOpenOrderDic)
# print(self.CalPositionDic)
ModuleName='公式-冻结仓位';CaseResult=True
for symbol in self.CalPositionDic:
for _type in self.CalPositionDic[symbol]:
OpenOrderKey=_type.replace('long','sell').replace('short','buy') #多仓 对应 挂单的平仓卖、空仓对应挂单的平仓买 有点绕
Temp_Postiton=self.CalPositionDic[symbol][_type]
Temp_OpenOrder=self.CalOpenOrderDic[symbol][OpenOrderKey]
if not float(Temp_Postiton[5])-float(Temp_Postiton[4])==float(Temp_OpenOrder[1]):
ErrorMessage=f'{NTS.user_id} {symbol} {_type}冻结仓位不一致 仓位数量{Temp_Postiton[5]} 仓位可平{Temp_Postiton[4]}仓位冻结{float(Temp_Postiton[5])-float(Temp_Postiton[4])} 平仓挂单冻结{Temp_OpenOrder[1]}'
printc(ErrorMessage);LogOut(ErrorMessage,LogName);CaseResult=False
if CaseResult: printl(log_level,NTS.user_id+ModuleName+SuccessMessage);Count(ModuleName,1,1,0,0);
else: Count(ModuleName, 1, 0, 1, 0);
return CaseResult
#获取杠杆
def GetLeverage(self,MarginType=None):
l={}
LeverageRes=self.NTS.leverage_info(tradeType='linearPerpetual', symbol=self.Symbol,marginType=MarginType)
if e(LeverageRes)[0]:
for i in LeverageRes['data']: l[i['marginType']]=i['leverage']
return l
#获取风险限额
def GetRiskLimit(self,MarginType=None):
Leverage=self.Leverage[MarginType]
MarginTypeNumber=2 if MarginType=='cross' else 1
RiskLimit=t_risk_limit_leverage(self.Symbol,Leverage,MarginTypeNumber)
self.RiskLimit=RiskLimit[0][0]
return RiskLimit[0][0]
#获取用户风险额度
def GetRiskAmout(self,MarginType=None,Side=None):
OpenValue=F.CalOpenOrderDic[self.Symbol]
PositionValue = F.CalPositionDic[self.Symbol]
# PositionSide='long' if Side=='buy' else 'short'
if MarginType=='cross':
KeyOpen_Buy = MarginType + '_' + 'buy';KeyPosition_Buy=MarginType+'_'+'long'
KeyOpen_Sell = MarginType + '_' + 'sell';KeyPosition_Sell = MarginType + '_' + 'short'
LongValue=OpenValue[KeyOpen_Buy][0]+PositionValue[KeyPosition_Buy][0] #多仓总价值:持仓+挂单
ShortValue = OpenValue[KeyOpen_Sell][0] + PositionValue[KeyPosition_Sell][0] #空仓总价值:持仓+挂单
RiskAmout=[LongValue,'long',ShortValue,'short'] if LongValue>=ShortValue else [ShortValue,'short',LongValue,'long']
return RiskAmout
def GetMaxOpenQty(self,MarginType=None,Side=None,Price=None):
#获取MarginType、Leverage对应的风险限额
RiskLimit=self.GetRiskLimit(MarginType=MarginType);
if MarginType == 'cross':
Key=['cross_buy','cross_long'] if Side.lower()=='buy' else ['cross_sell','cross_short']
else:
Key = ['isolated_buy', 'isolated_long'] if Side.lower() == 'buy' else ['isolated_sell', 'isolated_short']
#获取MarginType对应的仓位价值、挂单价值
PositionValue=self.CalPositionDic[self.Symbol][Key[1]][0] #仓位价值
OpenValue = self.CalOpenOrderDic[self.Symbol][Key[0]][0] #挂单价值
# print('杠杆,风险额度,持仓价值,挂单价值',self.Leverage[MarginType],RiskLimit,PositionValue,OpenValue)
#用可用 计算的最大可开[资金接口返回的可用]
AvailMaxOpenQty = cal.MaxOpenQty(Side, self.Balance_Available, Price, self.Leverage[MarginType], self.TakerFeeRate, self.CtVal, bid1=0);self.AvailMaxOpenQty = AvailMaxOpenQty
#用风险额度 计算最大可开
if Side=='Buy' :self.RiskLimitOpenQty=(d(RiskLimit)-d(PositionValue)-OpenValue)/d(Price)/d(self.CtVal)
else: self.RiskLimitOpenQty=(d(RiskLimit)-d(PositionValue)-OpenValue)/max(0,d(Price))/d(self.CtVal)
# Mysql数据库中最大下张数量限制
MysqlMaxOpenQtyLimitNumber = cal.t_order_volume_limit(self.Symbol)
#可用计算的最大可开、风险限额最大可开 取小值
#可开多数量 = min { 可开数量x ,(杠杆对应风险限额 - 仓位价值-当前委托价值) / 委托价格 ,最大单笔下单数量限制}
Qty=min(AvailMaxOpenQty,self.RiskLimitOpenQty,MysqlMaxOpenQtyLimitNumber)
#提供计算参数
self.MaxOpenQty={'leverage':self.Leverage[MarginType],'RiskLimit':float(RiskLimit),'PositonValue':float(PositionValue),'OpenValue':float(OpenValue),'AvailMaxOpenQty':AvailMaxOpenQty,'RiskLimitOrderQty':float(self.RiskLimitOrderQty),"Ctval":float(self.CtVal),'TakerFeeRate':float(self.TakerFeeRate)}
#返回最后结果
return [Qty,truncate(Qty,0)]
#持仓 浮动盈亏、浮动盈亏率、持仓保证金 验证 Case
def PositionAssert(self,log_level=None):
AssertResult=True;BlankPositionNumber=0
Module_UnRealisePnl_Formula=self.NTS.source+'公式-未实现盈亏';Assert_UnRealisePnl_Formula=True
Module_PositionMargin_Formula = self.NTS.source+'公式-持仓保证金';Assert_PositionMargin_Formula=True
Module_UnRealisePnlRate_Formula = self.NTS.source+'公式-浮动盈亏率';Assert_UnRealisePnlRate_Formula = True
for symbol in self.PositionMap:
for MarginType_PositionSide in self.PositionMap[symbol]:
if self.PositionMap[symbol][MarginType_PositionSide].__len__()>0:
PositionData=self.PositionMap[symbol][MarginType_PositionSide]
CalUnRealisePnlRate = d(PositionData['CalUnRealisePnl'] / d(PositionData['positionMargin']))
#未实现盈亏 检查
if float(PositionData['CalUnRealisePnl'])==float(PositionData['UnRealisePnl']): pass
else:
printc(f' {symbol}{MarginType_PositionSide}{Module_UnRealisePnl_Formula} {FailMessage} 预期 {PositionData["CalUnRealisePnl"]} 实际 {PositionData["UnRealisePnl"]}');
LogOut(f'{Module_UnRealisePnl_Formula} {FailMessage} {PositionData}',LogName);
Count(Module_UnRealisePnl_Formula,1,0,1,0);Assert_UnRealisePnl_Formula=False
#浮动盈亏率检查,仅支持web端
if self.NTS.source == 'web':
if not float(CalUnRealisePnlRate) == float(PositionData['earningRate']):
printc(f' {symbol}{MarginType_PositionSide}{Module_UnRealisePnlRate_Formula} {FailMessage} 预期 {float(CalUnRealisePnlRate)} 实际 {float(PositionData["earningRate"])}');
LogOut(f'{Module_UnRealisePnlRate_Formula} {FailMessage} 预期 {float(CalUnRealisePnlRate)} 实际 {float(PositionData["earningRate"])}', LogName);
Count(Module_UnRealisePnlRate_Formula, 1, 0, 1, 0);Assert_UnRealisePnlRate_Formula = False
# 持仓保证金检查
if float(PositionData['CalPositionMargin'])==float(PositionData['positionMargin']): pass
else:
printc(f'{symbol}{MarginType_PositionSide}{Module_PositionMargin_Formula} {FailMessage} 预期 {PositionData["CalPositionMargin"]} 实际 {PositionData["positionMargin"]}');
LogOut(f'{Module_PositionMargin_Formula} {FailMessage} {PositionData}',LogName);
Count(Module_PositionMargin_Formula,1,0,1,0);Assert_PositionMargin_Formula=False
if not Assert_UnRealisePnl_Formula or not Assert_PositionMargin_Formula or not Assert_UnRealisePnlRate_Formula:
if Assert_UnRealisePnl_Formula: Count(Module_UnRealisePnl_Formula,1,1,0,0);printl(log_level,f'{Module_UnRealisePnl_Formula} {SuccessMessage}');
if Assert_PositionMargin_Formula: Count(Module_PositionMargin_Formula,1,1,0,0);printl(log_level,f'{Module_PositionMargin_Formula} {SuccessMessage}');
if self.NTS.source=='web' and Assert_UnRealisePnlRate_Formula: Count(Module_UnRealisePnlRate_Formula, 1, 1, 0, 0);printl(log_level,f'{Module_UnRealisePnlRate_Formula} {SuccessMessage}');
return False
else:BlankPositionNumber+=1
#如果无仓位:则公式验证结果为 阻塞
if BlankPositionNumber==self.PositionMap.__len__():
Count(Module_UnRealisePnl_Formula, 1, 0, 0, 1);
Count(Module_PositionMargin_Formula, 1, 0, 0, 1);
if self.NTS.source=='web': Count(Module_UnRealisePnlRate_Formula, 1, 0, 0, 1);
#最终都成功
if Assert_UnRealisePnl_Formula: Count(Module_UnRealisePnl_Formula,1,1,0,0);printl(log_level,f'{Module_UnRealisePnl_Formula} {SuccessMessage}');
if Assert_PositionMargin_Formula: Count(Module_PositionMargin_Formula,1,1,0,0);printl(log_level,f'{Module_PositionMargin_Formula} {SuccessMessage}');
if self.NTS.source=='web' and Assert_UnRealisePnlRate_Formula: Count(Module_UnRealisePnlRate_Formula, 1, 1, 0, 0);printl(log_level,f'{Module_UnRealisePnlRate_Formula} {SuccessMessage}');
return True
#资金 总持仓保证金、权益、验证
def AccountAssert(self,log_level=None):
MarginAll=self.PositionMargin_Cross+self.PositionMargin_Isolated
Module_PositionMargin_Formula = self.NTS.source + '公式-持仓保证金';Assert_PositionMargin_Formula = True
Module_Equity_Formula = self.NTS.source + '公式-账户权益';Assert_Equity_Formula = True
Module_AvilMargin_Formula = self.NTS.source + '公式-可用保证金';Assert_AvilMargin_Formula = True
#验证持仓保证金 ,如果校验失败,输出case失败、日志、统计失败case
if not float(MarginAll) == float(self.Balance_MarginPosition):
printc(f' {self.NTS.user_id}{Module_PositionMargin_Formula} {FailMessage} 预期 {MarginAll} 实际 {self.Balance_MarginPosition}');
LogOut(f'{self.NTS.user_id}{Module_PositionMargin_Formula} {FailMessage} 预期 {MarginAll} 实际 {self.Balance_MarginPosition} ', LogName);
Count(Module_PositionMargin_Formula, 1, 0, 1, 0); Assert_PositionMargin_Formula = False
self.GetEquity()
#验证账户权益 ,如果校验失败,输出case失败、日志、统计失败case
if not float(self.Equity["Equity"]) == float(self.Balance_Equity):
ErrorMessage=f' {self.NTS.user_id}{Module_Equity_Formula} {FailMessage} 预期 {self.Equity["Equity"]} 实际 {self.Balance_Equity}'
printc(ErrorMessage);LogOut(f'{ErrorMessage} {self.Equity} ',LogName);
Count(Module_Equity_Formula, 1, 0, 1, 0); Assert_Equity_Formula = False
# 产品公式:可用 = 账户权益 - 委托保证金 - 全仓持仓保证金 - 逐仓权益 - 划转冻结; 逐仓权益=逐仓保证金+逐仓未实现盈亏
self.AvilMargin = cal.AvailMargin(self.Equity["Equity"], self.Balance_Frozen, self.PositionMargin_Cross, self.PositionMargin_Isolated + self.UnReal_Isolated, 0)
#可用保证金验证
if not float(self.AvilMargin)==float(self.Balance_Available):
ErrorMessage = f' {self.NTS.user_id}{Module_AvilMargin_Formula} {FailMessage} 预期 {self.AvilMargin} 实际 {self.Balance_Available}'
printc(ErrorMessage);LogOut(f'{ErrorMessage} 账户权益={self.Equity["Equity"]}冻结={self.Balance_Frozen} 全仓保证金={self.PositionMargin_Cross}逐仓权益={self.PositionMargin_Isolated + self.UnReal_Isolated} ', LogName);
Count(Module_AvilMargin_Formula, 1, 0, 1, 0);Assert_AvilMargin_Formula = False
#最大可划转 验证
Assert_MaxTransferOut=self.MaxTransferOut('cross',log_level=log_level)[1]
if Assert_PositionMargin_Formula: Count(Module_PositionMargin_Formula,1,1,0,0);printl(log_level,f'{Module_PositionMargin_Formula} {SuccessMessage}');
if Assert_Equity_Formula: Count(Module_Equity_Formula,1,1,0,0);printl(log_level,f'{Module_Equity_Formula} {SuccessMessage}');
if Assert_AvilMargin_Formula: Count(Module_AvilMargin_Formula, 1, 1, 0, 0);printl(log_level,f'{Module_AvilMargin_Formula} {SuccessMessage}');
if not Assert_PositionMargin_Formula or not Assert_Equity_Formula or not Assert_AvilMargin_Formula and not Assert_MaxTransferOut:
return False
#获取账户权益
def GetEquity(self):
UnReal_All=self.UnReal_Cross+self.UnReal_Isolated
# print(self.Amount,self.UnReal_Cross,self.UnReal_Isolated)
self.Amount = getNowAccount(NTS.user_id)
Equity=cal.Equity(self.Amount, UnReal_All)
self.Equity={"Equity":Equity,"Amount":self.Amount,"UnReal_All":UnReal_All,"UnReal_Cross":self.UnReal_Cross,"UnReal_Isolated":self.UnReal_Isolated}
return Equity
#获取预估资金费
def ForecastFunding(self,marginType,log_level=None):
if marginType=='cross':
for symbol in self.instrumentList:
crossPos = self.CalPositionDic[symbol]
funding = 0
totalFunding=0
for tmp in crossPos:
funding = (crossPos[tmp]['cross_long'][5] - crossPos[tmp]['cross_short'][5]) * self.FundingRate
totalFunding += funding
printl(log_level, f'{tmp}的预估资金费={funding}')
return
else:
isolatedfunding = {}
for symbol in self.instrumentList:
isolatedPos = self.CalPositionDic[symbol]
for tmp in isolatedPos:
funding = (isolatedPos[tmp]['isolated_long'][5] - isolatedPos[tmp]['cross_short'][5]) * self.FundingRate
isolatedfunding[tmp]['funding']=funding
return isolatedfunding
#获取最高价格限制
def LimitOrderPriceLimit(self,OrderPrice,OrderQty,Ctval):
MarkPrice=self.MarkPrice[self.Symbol]
IndexPrice=self.IndexPrice[self.Symbol]
T=False
if OrderPrice*OrderQty*Ctval>50000:
MarkPriceRate = 0.05;IndexPriceRate = 0.08;T=True # 临时写死,需要从db查询获取
else:
MarkPriceRate = 0.08;IndexPriceRate = 0.1;T=False # 临时写死,需要从db查询获取
MaxBuyPrice=min( d(MarkPrice)*(d(1+MarkPriceRate)),d(IndexPrice)*d(1+IndexPriceRate) )
MinSellPrice = min(d(MarkPrice) * (d(1 - MarkPriceRate)), d(IndexPrice) * d(1 - IndexPriceRate))
return [MaxBuyPrice,MinSellPrice,T]
def GetMarkPrice(MarkPrice=None,OrderRange=None,Side='buy'):
P=1 if Side=='buy' else -1
MarketPrice=d(MarkPrice)*(d(1)+d(OrderRange)*d(0.03)*d(P))
return MarketPrice
if __name__ == '__main__':
from BU.NTS.WebOrder import n_order
Symbol='BTCUSDT'
# NTS = NtsApiOrder(6, user_id='97201979')
NTS = n_order(5, user_id='97201979')
MaxTransferOut=Formula(NTS,Symbol).MaxTransferOut(marginType='isolated',log_level=0) #最大转出金额 计算
# print(MaxTransferOut)
# F=Formula(NTS, Symbol)
# time.sleep(10000)
# print(F.CalOpenOrderDic) #挂单价值
# print(F.CalPositionDic) # 持仓相关
# 🀆🀆🀆🀆🀆★★★★★Formula Case - 3 ★★★★★🀆🀆🀆🀆🀆
# F.FrozenMarginAssert(log_level=0) # 1- 挂单冻结金额结果 验证
# F.PositionAssert(log_level= 0) #2-持仓验证
# F.AccountAssert(log_level= 0) #3-资金
# Count(summary=1, log_level=2)
# print('最高买入价\最低卖出价:',F.LimitOrderPriceLimit(19000,200,0.01))
# print('市价:',GetMarkPrice(19500,0.9,'sell'))
# time.sleep(10000)
# print(F.CalOpenOrderDic) #挂单价值
# print(F.CalPositionDic) #仓位价值、保证金+未实现盈亏、维持保证金率、风险等级、可用仓位
# Formula(NTS, Symbol).MaintMaringCal(marginType='cross',log_level=2) #维持保证金计算
# Formula(NTS, Symbol).MaintMaringCal(marginType='isolated',log_level=2)
# print('挂单冻结',f'{F.FrozenMargin}') #打印持仓冻结
# F.GetRiskLimit(MarginType='isolated'); #获取风险限额(全仓、逐仓)
# print(F.Leverage)
# print('风险限额 ',f'{F.RiskLimit}') #打印风险限额
# F.GetRiskAmout(MarginType='cross',Side='buy')
# MaxQty=F.GetMaxOpenQty(MarginType='cross',Side='buy',Price=16000)
# print(MaxQty)
# print(F.MaxOpenQty)
# time.sleep(10000) | wuzhiding1989/newqkex | BU/NTS/dataCheck/Formula.py | Formula.py | py | 31,378 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "common.mysqlClient.mysql",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "common.mysqlClient",
"line_number": 17,
"usage_type": "name"
},
{
"api_name": "common.util.d",
"line_number": 47,
"usage_type": "call"
},
{
"api_name": "copy.deepco... |
28957556961 | from django.urls import path
from .views import PostList, PostSearch, CreatePost, EditPost, UserPostDetail, DeletePost
urlpatterns = [
path('posts/', PostList.as_view()),
path('search/', PostSearch.as_view()),
path('user/create/', CreatePost.as_view(), name="create_post"),
path('user/edit/posts/<int:pk>',
UserPostDetail.as_view(), name="user_post_detail"),
path('user/delete/posts/<int:pk>', DeletePost.as_view(), name="delete_post")
]
| prakash472/DjangoRestFrameworkBasics | blogs/urls.py | urls.py | py | 468 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "django.urls.path",
"line_number": 4,
"usage_type": "call"
},
{
"api_name": "views.PostList.as_view",
"line_number": 4,
"usage_type": "call"
},
{
"api_name": "views.PostList",
"line_number": 4,
"usage_type": "name"
},
{
"api_name": "django.urls.path"... |
6095050503 | '''
created on 09 June 2019
@author: Gergely
'''
import random
def run_game(env, policy, display=True, should_return=True):
env.reset()
episode = []
done = False
while not done:
s = env.env.s
if display:
env.render()
timestep = [s]
action = policy[s]
state, reward, done, info = env.step(action)
timestep.append(action)
timestep.append(reward)
episode.append(timestep)
if should_return:
return episode
def argmaxQ(Q, s):
'''
what the fuck
:param Q:
:param s:
:return:
'''
Q_list = list(map(lambda x: x[1], Q[s].items()))
indices = [i for i, x in enumerate(Q_list) if x == max(Q_list)]
max_Q = random.choice(indices)
return max_Q
def greedy_policy(Q):
policy = {}
for state in Q:
policy[state] = argmaxQ(Q, state)
return policy
def field_list(env):
l = []
for row in list(map(lambda x: list([str(y)[-2] for y in x]), list(env.env.desc))):
for field in row:
l.append(field)
return l
def create_state_action_dictionary(env, policy):
Q = {}
fields = field_list(env)
for key in policy.keys():
if fields[key] in ['F', 'S']:
Q[key] = {a: 0.0 for a in range(0, env.action_space.n)}
else:
Q[key] = {a: 0.0 for a in range(0, env.action_space.n)}
return Q
def test_policy(policy, env):
wins = 0
r = 10000
for i in range(r):
w = run_game(env, policy, display=False)
print(w)
if w[-1][-1] == 1:
wins += 1
return wins / r
def create_random_policy(env):
policy = {}
for key in range(env.observation_space.n):
p = {}
for action in range(0, env.action_space.n):
p[action] = 1 / env.action_space.n
policy[key] = p
return policy
def sarsa(env, episodes=100, step_size=0.01, epsilon=0.01):
policy = create_random_policy(env)
Q = create_state_action_dictionary(env, policy)
for episode in range(episodes):
env.reset()
S = env.env.s
A = greedy_policy(Q)[S]
finished = False
total = 0.0
while not finished:
S_prime, reward, finished, _ = env.step(A)
total += reward
A_prime = greedy_policy(Q)[S_prime]
Q[S][A] = Q[S][A] + step_size * (reward + epsilon * Q[S_prime][A_prime] - Q[S][A])
S = S_prime
A = A_prime
print("episode", episode, "terminated with reward", total)
return greedy_policy(Q), Q
import gym
environment = gym.make('FrozenLake8x8-v0')
pol, Q = sarsa(environment, episodes=1000, step_size=0.2, epsilon=0.2)
print(test_policy(pol, environment))
| imimali/ReinforcementLearningHeroes | td/sarsa.py | sarsa.py | py | 2,768 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "random.choice",
"line_number": 40,
"usage_type": "call"
},
{
"api_name": "gym.make",
"line_number": 115,
"usage_type": "call"
}
] |
14191657465 | # -*- coding: utf-8 -*-
from numpy.testing import assert_array_almost_equal
from pmdarima.preprocessing import LogEndogTransformer
from pmdarima.preprocessing import BoxCoxEndogTransformer
def test_same():
y = [1, 2, 3]
trans = BoxCoxEndogTransformer(lmbda=0)
log_trans = LogEndogTransformer()
y_t, _ = trans.fit_transform(y)
log_y_t, _ = log_trans.fit_transform(y)
assert_array_almost_equal(log_y_t, y_t)
def test_invertible():
y = [1, 2, 3]
trans = LogEndogTransformer()
y_t, _ = trans.fit_transform(y)
y_prime, _ = trans.inverse_transform(y_t)
assert_array_almost_equal(y, y_prime)
| jose-dom/bitcoin_forecasting | env/lib/python3.9/site-packages/pmdarima/preprocessing/endog/tests/test_log.py | test_log.py | py | 658 | python | en | code | 10 | github-code | 1 | [
{
"api_name": "pmdarima.preprocessing.BoxCoxEndogTransformer",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "pmdarima.preprocessing.LogEndogTransformer",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "numpy.testing.assert_array_almost_equal",
"line_numb... |
39332262964 | import os
import webbrowser
import shapely
from folium import Map, Marker, CircleMarker
from folium.plugins import MarkerCluster
from folium.features import PolygonMarker
from utility_functions import get_state_contours, get_state_fullname
class SpatialPlotter:
'''
A class helps visualize commonly used spatial elements: locations, countours and points.
Args:
central_point (list): the central point (lat and lon coordinate) for the canvass.
Note: users can pass a list of points and we will use the mean value as central point
reverse (boolean): if true, the position of lat and lon will be reversed.
'''
def __init__(self, central_point, reverse=False):
if reverse:
central_point = self._reverse_lat_lon(central_point)
self._build_canvass(central_point)
print('-'*20)
print('Latitude is assumed to be the first column')
print('if your data has longitude first. set reverse=True')
def _build_canvass(self, locations):
lat_sum = 0; lon_sum = 0
for row in locations:
lat_sum = lat_sum + row[0]
lon_sum = lon_sum + row[1]
average_lat = lat_sum/len(locations)
average_lon = lon_sum/len(locations)
center = [average_lat, average_lon]
self.canvass = Map(location=center, zoom_start=6)
def _reverse_lat_lon(self, list_of_coords):
'''
allow users to flip the order of latitude and longitude in the list
Conventionally, use latitude as the first argument unless specified otherwise
'''
flipped_locations = []
for coord in list_of_coords:
new_loc = list(reversed(coord[0:2])) #only reverse lat and lon
new_loc.extend(coord[2:])
flipped_locations.append(new_loc)
return flipped_locations
def _pandas_to_list(self, locations):
'''
if input is dataframe, this function will convert the input to list
'''
try:
locations = locations.values.tolist()
except:
if isinstance(locations, list):
pass
else:
raise TypeError('Acceptable input types: list and dataframe')
return locations
def add_point(self, points):
'''
Add location markers on the canvass
Args:
points: the points to be added. We assume the first two dimension are locational information.
The orders has to be latitude, longitude
'''
points = self._pandas_to_list(points)
for point in points:
Marker(location=point[0:2]).add_to(self.canvass)
return self
def add_point_clustered(self, points):
'''
Add location markers, but will automatically make cluster if there is too many.
Args:
points: the points to be added. We assume the first two dimension are locational information
'''
points = self._pandas_to_list(points)
marker_cluster = MarkerCluster(icons="dd").add_to(self.canvass)
for point in points:
Marker(location = point[0:2]).add_to(marker_cluster)
return self
def add_contour(self, contour='SC'):
'''
Add the contour information on the canvass
Args:
contour: allow three types of information:
1.Statenames: like SC, NC or north carolina
2.shapely polygon type
3.list of coords
'''
print('-'*20)
print('allow two input types: 1. eg. DC, SC 2. a list of coordinates')
if isinstance(contour, str):
polygon = get_state_contours(contour)[-1]
make_coords = True
elif isinstance(contour, shapely.geometry.polygon.Polygon):
polygon = contour
make_coords = True
elif isinstance(contour, list):
make_coords = False
else:
raise TypeError('only support str, list and polygon type')
if make_coords:
longitudes, latitudes = polygon.exterior.coords.xy
list_of_coords = list(zip(latitudes, longitudes))
PolygonMarker(list_of_coords, color='blue', fill_opacity=0.2, weight=1).add_to(self.canvass)
return self
def add_value(self, values, multiplier=4):
values = self._pandas_to_list(values)
for record in values:
value = record[2]; location_info = record[0:2]
color = "#ff0000" if value >=0 else "#000000" # pos and neg have different colors
CircleMarker(location=location_info,
radius=multiplier*abs(value),
alpha=0.5,
fill=True,
fill_color=color,
color=color).add_to(self.canvass)
return self
def plot(self, open_in_browser=True, filename=None):
if filename is None:
filename = 'map_test.html'
output_path = os.path.join(os.getcwd(), filename)
self.canvass.save(output_path)
print('-'*20)
print(f'the map has been saved to {filename}')
if filename == 'map_test.html':
print('to change to a different name, assign a name to filename')
print('when calling plot() function')
if open_in_browser:
webbrowser.open('file://' + os.path.realpath(output_path))
if __name__ == '__main__':
#the test based on list input
s = SpatialPlotter([[34, -80]])
s.add_point([[33.9, -80], [33.8, -80], [33.2, -80]])\
.add_contour('North Carolina')\
.add_value([[33.9, -80, 1], [34.9, -80, 20]])\
.plot()
# #the test case based on dataframe input
# from SampleDataLoader import load_rainfall_data
# test = load_rainfall_data('monthly')
# new_map = SpatialPlotter([[34, -80]])\
# .add_point(test[['LATITUDE', 'LONGITUDE']])\
# .plot(filename='map_test2.html')
| HaigangLiu/spatial-temporal-py | visualize_spatial_info.py | visualize_spatial_info.py | py | 6,009 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "folium.Map",
"line_number": 33,
"usage_type": "call"
},
{
"api_name": "folium.Marker",
"line_number": 69,
"usage_type": "call"
},
{
"api_name": "folium.plugins.MarkerCluster",
"line_number": 79,
"usage_type": "call"
},
{
"api_name": "folium.Marker",... |
19830801226 | import serial
import time
import calendar
connected = False
ser = serial.Serial("COM3", 9600)
ser.close()
ser.open()
while not connected:
serin = ser.read()
connected = True
#ser.write("1")
#while ser.read() == '1':
# ser.read()
while True:
string = "T" + str(calendar.timegm(time.localtime())) + "\n"
ser.write(string)
time.sleep(60*5)
ser.close()
| IRQBreaker/arduino_info_display | sync.py | sync.py | py | 368 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "serial.Serial",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "calendar.timegm",
"line_number": 22,
"usage_type": "call"
},
{
"api_name": "time.localtime",
"line_number": 22,
"usage_type": "call"
},
{
"api_name": "time.sleep",
"line_nu... |
40147521188 | # -*- coding: utf-8 -*
# author: unknowwhite@outlook.com
# wechat: Ben_Xiaobai
# from os import add_dll_directory
import sys
# from threading import Event
# from traceback import print_exception
sys.path.append("./")
sys.setrecursionlimit(10000000)
from configs import admin,kafka
import time
from component.public_func import show_my_memory
from component.db_func import show_project,select_properties,insert_update_access_control_list
import json
import traceback
from configs.export import write_to_log
class access_control:
def __init__(self,project=None):
# self.ip_group = {}
# self.ip = {}
# self.distinct_id = {}
self.projects = project if project else {}
# self.customized = {}
self.start_time = int(time.time())
self.check_mem_start = int(time.time())
self.my_memory = 0
self.term_times = {'distinct_id':1,'add_on_key':admin.access_control_per_add_on_key,'ip':admin.access_control_distinct_id_per_ip,'ip_group':admin.access_control_distinct_id_per_ip*admin.access_control_ip_per_ip_group,'ip_group_extend':admin.access_control_distinct_id_per_ip*admin.access_control_ip_per_ip_group*admin.access_control_ip_group_per_ip_group_extend}
self.type_int={'ip':60,'ip_group':61,'distinct_id':62,'add_on_key':63,'ip_group_extend':80}
def check_mem(self):
#每30秒检查一次内存占用量
if int(time.time()-self.check_mem_start) <= 30 and self.projects != {}:
return self.my_memory
else:
self.my_memory = int(show_my_memory())
self.check_mem_start = int(time.time())
return self.my_memory
def refresh_threshold_list(self):
self.threshold_list = {}
project_list = show_project()[0]
for project in project_list:
if project[0] not in self.threshold_list:
self.threshold_list[project[0]] = {}
if project[4]:
self.threshold_list[project[0]]['default_sum'] = project[4]
if project[5]:
self.threshold_list[project[0]]['default_event'] = project[5]
event_threshold_list = select_properties(project=project[0])[0]
for item in event_threshold_list:
if item[0] not in self.threshold_list[project[0]]:
self.threshold_list[project[0]][item[0]] = item[1]
# print(self.threshold_list)
def insert_data(self,project,key,type_str,event,pv,hour,date):
insert_update_access_control_list(project=project,key=key,type_int=self.type_int[type_str],event=event,pv=pv,date=date,hour=hour)
def check_threshold(self,project,event):
if project:
if event == 'all':
if 'all' in self.threshold_list[project]:
limit = self.threshold_list[project]['all']
elif 'default_sum' in self.threshold_list[project]:
limit = self.threshold_list[project]['all']['default_sum']
else:
limit = admin.access_control_sum_count
elif event != '' or event != ' ':
if projects_project_event in self.threshold_list[projects_project]:
limit = self.threshold_list[projects_project][projects_project_event]
elif 'default_event' in self.threshold_list[projects_project]:
limit = self.threshold_list[projects_project]['default_event']
else:
limit = admin.access_control_event_default
def etl(self):
self.refresh_threshold_list()
date = time.strftime("%Y-%m-%d", time.localtime())
hour = int(time.strftime("%H", time.localtime()))
for projects_project in self.projects:
if projects_project in self.threshold_list:
for projects_project_event in self.projects[projects_project]:
if self.projects[projects_project][projects_project_event] == 'all' :
#如果event是all的触发量。如果没有则使用全局总量
if 'all' in self.threshold_list[projects_project]:
limit = self.threshold_list[projects_project]['all']
elif 'default_sum' in self.threshold_list[projects_project]:
limit = self.threshold_list[projects_project]['all']['default_sum']
else:
limit = admin.access_control_sum_count
elif self.projects[projects_project][projects_project_event] != '' :
#event不是all的触发量。如果没有,则使用项目阈值,如果再没有,则使用全局事件量
if projects_project_event in self.threshold_list[projects_project]:
limit = self.threshold_list[projects_project][projects_project_event]
elif 'default_event' in self.threshold_list[projects_project]:
limit = self.threshold_list[projects_project]['default_event']
else:
limit = admin.access_control_event_default
for term in self.projects[projects_project][projects_project_event]:
#比对项目与限制值
for content in self.projects[projects_project][projects_project_event][term]:
if self.projects[projects_project][projects_project_event][term][content] >= limit*self.term_times[term]*admin.access_control_max_window/3600:
self.insert_data(project=projects_project,key=content,type_str=term,event=projects_project_event,pv=self.projects[projects_project][projects_project_event][term][content],hour=hour,date=date)
elif projects_project:
for projects_project_event in self.projects[projects_project]:
if self.projects[projects_project][projects_project_event] == 'all' :
limit = admin.access_control_sum_count
else:
limit = admin.access_control_event_default
for term in self.projects[projects_project][projects_project_event]:
#比对项目与限制值
for content in self.projects[projects_project][projects_project_event][term]:
if self.projects[projects_project][projects_project_event][term][content] >= limit*self.term_times[term]*admin.access_control_max_window/3600:
self.insert_data(project=projects_project,key=content,type_str=term,event=projects_project_event,pv=self.projects[projects_project][projects_project_event][term][content],hour=hour,date=date)
self.projects = {}
self.start_time = int(time.time())
self.my_memory = int(show_my_memory())
def update_data(self,project,event,term,content):
if term not in self.projects[project]['all']:
self.projects[project]['all'][term] = {}
self.projects[project]['all'][term][content] = self.projects[project]['all'][term][content] + 1 if content in self.projects[project]['all'][term] else 1
if event:
if term not in self.projects[project][event]:
self.projects[project][event][term] = {}
self.projects[project][event][term][content] = self.projects[project][event][term][content] + 1 if content in self.projects[project][event][term] else 1
def commit(self,project=None,event=None,ip_commit=None,distinct_id_commit=None,add_on_key_commit=None):
if ip_commit:
ip_group_commit = '.'.join(ip_commit.split('.')[0:3])
ip_group_extend_commit = '.'.join(ip_commit.split('.')[0:2])
self.update_data(project=project,event=event,term='ip',content=ip_commit)
self.update_data(project=project,event=event,term='ip_group',content=ip_group_commit)
self.update_data(project=project,event=event,term='ip_group_extend',content=ip_group_extend_commit)
if distinct_id_commit:
self.update_data(project=project,event=event,term='distinct_id',content=distinct_id_commit)
if add_on_key_commit:
self.update_data(project=project,event=event,term='add_on_key',content=add_on_key_commit)
def traffic(self,project=None,event=None,ip_commit=None,distinct_id_commit=None,add_on_key_commit=None):
if project and project not in self.projects:
self.projects[project] = {}
if 'all' not in self.projects[project]:
self.projects[project]['all'] = {'ip_group':{},'ip':{},'distinct_id':{},'add_on_key':{}}
if event not in self.projects[project]:
self.projects[project][event] = {'ip_group':{},'ip':{},'distinct_id':{},'add_on_key':{}}
if int(time.time())-self.start_time >= admin.access_control_max_window or self.check_mem() >= admin.access_control_max_memory:
write_to_log(filename='access_control', defname='traffic', result='开始清理:'+str(self.check_mem()))
self.etl()
write_to_log(filename='access_control', defname='traffic', result='完成清理:'+str(self.check_mem()))
self.traffic(project=project,event=event,ip_commit=ip_commit,distinct_id_commit=distinct_id_commit,add_on_key_commit=add_on_key_commit)
else:
self.commit(project=project,event=event,ip_commit=ip_commit,distinct_id_commit=distinct_id_commit,add_on_key_commit=add_on_key_commit)
# print('commit')
if __name__ == "__main__":
if admin.access_control_commit_mode =='access_control':
from component.access_control import access_control
from component.kafka_op import get_message_from_kafka
ac_access_control = access_control()
results = get_message_from_kafka(group_id=kafka.client_group_id+'_'+admin.access_control_kafka_client_group_id,client_id=kafka.client_id+'_'+admin.access_control_kafka_client_client_id)
for item in results :
group = json.loads(item.value.decode('utf-8'))['group'] if "group" in json.loads(item.value.decode('utf-8')) else None
data = json.loads(item.value.decode('utf-8'))['data']
offset = item.offset
if group == 'event_track':
try:
ac_access_control.traffic(project=data['project'],event=data['data_decode']['event'] if 'event' in data['data_decode'] else None,ip_commit=data['ip'],distinct_id_commit=data['data_decode']['distinct_id'],add_on_key_commit=data['data_decode']['properties'][admin.access_control_add_on_key] if admin.access_control_add_on_key in data['data_decode']['properties'] else None)
except Exception:
error = traceback.format_exc()
write_to_log(filename='access_control', defname='main', result=error) | white-shiro-bai/ghost_sa | component/access_control.py | access_control.py | py | 10,985 | python | en | code | 256 | github-code | 1 | [
{
"api_name": "sys.path.append",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "sys.path",
"line_number": 8,
"usage_type": "attribute"
},
{
"api_name": "sys.setrecursionlimit",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "time.time",
"lin... |
26399582069 | from translate import Translator
translator= Translator(to_lang="pt")
try:
with open('C:/Users/LENOVO/Desktop/Translator/tarans.txt',mode = 'r') as my_file:
text= my_file.read()
translation = translator.translate(text)
print(translation)
with open('C:/Users/LENOVO/Desktop/Translator/tarans-ja.txt',mode='w' ) as my_file2:
my_file2.write(translation)
except FileNotFoundError as err:
print('check your path silly!') | sonalambadesonal/background-genrator | transscript.py | transscript.py | py | 428 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "translate.Translator",
"line_number": 2,
"usage_type": "call"
}
] |
12836997597 | #!/usr/bin/env python
import sys
import os
import django
import pytz
from datetime import datetime
print("I am alive!.")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pim.settings")
django.setup()
from web.models import ProductData
#Some mappings for readability
EanCode=0
ProductDescription=1
NutritionDescription=2
IngredientsDescription=3
ProductName=4
CreationDate=5
LastmodifiedDate=6
tz = pytz.timezone("Europe/Stockholm")
testy = datetime.strptime("2007-10-27 12:24:12", "%Y-%m-%d %H:%M:%S")
print(testy)
lineset = open('temp/CoreProductData_stage180915.csv',encoding='utf-8').readlines()
headerrow =lineset.pop(0)
for line in lineset:
print('')
print(line)
csv_row = line.split(';')
_pd = ProductData(
gtin=csv_row[EanCode],
marketing_message=csv_row[ProductDescription].strip('"'),
nutrition_description=csv_row[NutritionDescription].strip('"'),
ingredient_description=csv_row[IngredientsDescription].strip('"'),
name=csv_row[ProductName],
creation_date=tz.localize(datetime.strptime(csv_row[CreationDate].strip('"'), "%Y-%m-%d %H:%M:%S")),
last_modified=tz.localize(datetime.strptime(csv_row[LastmodifiedDate].strip('\n').strip('"'), "%Y-%m-%d %H:%M:%S"))
)
if _pd.marketing_message == "NULL":
_pd.marketing_message = str()
if _pd.nutrition_description == "NULL":
_pd.nutrition_description = str()
if _pd.ingredient_description == "NULL":
_pd.ingredient_description = str()
try:
_pd.save()
except Exception as e:
print(e)
pass
| hackcasa/zappa_final | import_coreproductdata.py | import_coreproductdata.py | py | 1,623 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "os.environ.setdefault",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "os.environ",
"line_number": 12,
"usage_type": "attribute"
},
{
"api_name": "django.setup",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "pytz.timezone",
... |
20046232564 | from io import BytesIO
import multiprocessing
import streamlit as st
from XOR_file_enc_threading import XOR_encryption, XOR_decryption
# streamlit run app.py 2>NUL
st.title('XOR Cipher')
st.header('FILE ENCRYPTION USING XOR CIPHER')
st.write("""
File encryption using the XOR cipher is a method of securing the contents of a file by applying a simple encryption algorithm known as the XOR (exclusive OR) cipher. The XOR cipher is a symmetric encryption algorithm that operates on binary data, where each byte (or bit) in the file is bitwise XORed with a key, typically a sequence of bytes (or bits).
The XOR operation works by comparing the corresponding bits of two operands (in this case, the file data and the encryption key), and producing an output bit that is set to 1 if the two input bits are different (i.e., one is 0 and the other is 1), and 0 if the input bits are the same (i.e., both 0 or both 1). This operation is performed on each byte (or bit) of the file data, using the corresponding byte (or bit) of the encryption key, which is repeated cyclically to match the length of the file.
To encrypt a file using XOR cipher, each byte in the file is bitwise XORed with a corresponding byte from the encryption key. This process is reversible, meaning that the original file can be decrypted by applying the same XOR operation using the same encryption key. However, the security of the XOR cipher is relatively weak, as it is susceptible to various attacks, such as frequency analysis and known-plaintext attacks, and is not recommended for strong encryption requirements.
""")
st.write('---')
# Widgets
st.header('Inputs')
select_option = st.selectbox('Pick one', ['Encrypt', 'Decrypt'])
# Create a file uploader widget
if select_option:
if select_option == 'Encrypt':
uploaded_file = st.file_uploader("Choose a file", type=None)
elif select_option == 'Decrypt':
uploaded_file = st.file_uploader("Choose a file", type=['.enc'])
else:
pass
btn_disabled = True
Has_file = False
Has_key = False
Except_file =".enc"
# Check if a file has been uploaded
file_name = ""
if uploaded_file is not None:
file_contents = uploaded_file.read()
file_name = uploaded_file.name
st.write(f"Filename: {file_name}")
st.write(f"File size: {len(file_contents)} bytes")
Has_file = True
key = st.text_input("KEY: ")
if key != "":
Has_key = True
if Has_key and Has_file:
btn_disabled = False
btn_submit = st.button(f'{select_option}', disabled = btn_disabled)
if select_option:
if btn_submit:
file_output =""
st.write(f"Filename: {file_name}")
st.write(f"key {key}")
if select_option == "Encrypt":
file = XOR_encryption(file_contents, key)
file_output = file_name+".enc"
if select_option == "Decrypt":
file = XOR_decryption(file_contents, key)
file_output = "decrypted_"+file_name[:-4]
print(f"Processing by {multiprocessing.cpu_count()} CPUs...")
# Convert bytearray to BytesIO object
file = BytesIO(file)
# Set the file name
file_name_output = file_output
# Create a download button
st.download_button(label='Download File', data=file, file_name=file_name_output, mime='application/octet-stream')
# phrase = st.text_input("FILE: ")
# shift_dir = st.selectbox("Shift direction: ", ('Forward', 'Backward'))
# shift_no = st.number_input("Shift Amount: ", min_value=1)
| githubgithub101/project | app.py | app.py | py | 3,488 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "streamlit.title",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "streamlit.header",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "streamlit.write",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "streamlit.write",
... |
20169614876 | import logging
import sqlite3
import __init__ # noqa pylint: disable=W0611
from time import sleep
logger = logging.getLogger(__name__)
class Inventory:
def __init__(self): # noqa
logger.info("Connecting to database")
self.connection = sqlite3.connect("products.db")
self.connection.set_trace_callback(logger.debug)
logger.debug("Getting cursor")
self.cursor = self.connection.cursor()
self.init_table()
@property
def columncount(self):
return 4 # this needs to be updated when init_table is changed
@property
def rowcount(self):
self.execute("SELECT COUNT(id) FROM inventory")
return self.cursor.fetchone()[0]
def get_ids(self):
self.execute("SELECT id FROM inventory ORDER BY id")
return [i[0] for i in self.cursor.fetchall()]
def get_name_from_id(self, id):
self.execute("SELECT name FROM inventory WHERE id = :id", {"id": id})
return self.cursor.fetchone()[0]
def get_price_from_id(self, id):
self.execute("SELECT price FROM inventory WHERE id = :id", {"id": id})
return self.cursor.fetchone()[0]
def get_amount_from_id(self, id):
self.execute("SELECT amount FROM inventory WHERE id = :id", {"id": id})
return self.cursor.fetchone()[0]
def init_table(self):
# if you are changing this, do not forget to update rowcount
logger.debug("Ensuring table layout is correct")
self.execute_commit(
"""
CREATE TABLE IF NOT EXISTS inventory (
id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
name VARCHAR(30) NOT NULL,
amount INTEGER DEFAULT 0,
price FLOAT DEFAULT NULL,
CHECK (name != ''),
CHECK (amount >= 0),
CHECK (price >= 0)
)
"""
)
def execute_commit(self, command, values=None):
self.execute(command, values)
self.commit()
def get_id_name_pairs(self):
self.execute("SELECT id, name FROM inventory ORDER BY id")
return self.cursor.fetchall()
def execute(self, command, values=None):
if values is None:
values = {}
logger.debug(
"Executing command '%s' with values '%s'",
self.clean_command(command),
values,
)
self.cursor.execute(command, values)
affected_rows = self.cursor.rowcount
if affected_rows > -1:
logger.debug("Affected rows: %s", affected_rows)
print("Affected items:", affected_rows)
def commit(self):
logger.debug("Committing transaction")
self.connection.commit()
def close(self):
logger.info("Closing database connection")
self.connection.close()
def clean_command(self, command):
lines = command.splitlines()
ret = ""
for line in lines:
line = line.strip().replace("\n", "")
line += " " if line.endswith(",") else ""
ret += line
return ret
def new_item(self, name, price, amount = None):
logger.info("Creating new item '%s' with price '%s'", name, price)
command = """INSERT INTO inventory (name, price, amount) VALUES (:name, :price, :amount)"""
values = {"name": name, "price": price, "amount": amount}
self.execute_commit(command, values)
return self.cursor.lastrowid
def get_id_from_name(self, name):
text = "get_id_from_name is DEPRECATED and will always return 0, hopefully crashing the program. It was removed to allow for duplicate product names"
logger.critical(text)
print(text)
return 0
def display_item(self, id):
if id is None:
print("No corresponding item")
return
self.execute(
"SELECT id, name, price, amount FROM inventory WHERE id = :id ORDER BY id",
{"id": id},
)
id, name, price, amount = self.cursor.fetchone()
if price is None:
price = "-"
print("{:<10}{:<30}{:<13}{}".format(id, name, price, amount))
def display_header(self):
print("id name price amount")
def modify_item(self, id, name, price):
logger.info("Item '%s' now has name '%s' and price '%s'", id, name, price)
self.execute_commit(
"UPDATE inventory SET name = :name, price = :price WHERE id = :id",
{"name": name, "price": price, "id": id},
)
def set_price(self, id, price):
self.execute_commit(
"UPDATE inventory SET price = :price WHERE id = :id",
{"price": price, "id": id},
)
def set_name(self, id, name):
self.execute_commit(
"UPDATE inventory SET name = :name WHERE id = :id", {"name": name, "id": id}
)
def set_amount(self, id, amount):
self.execute_commit(
"UPDATE inventory SET amount = :amount WHERE id = :id",
{"amount": amount, "id": id},
)
def sell_item(self, id, amount):
self.change_amount(id, -amount)
def buy_item(self, id, amount):
self.change_amount(id, amount)
def change_amount(self, id, amount):
self.execute("SELECT amount FROM inventory WHERE id = :id", {"id": id})
old_amount = self.cursor.fetchone()[0]
new_amount = old_amount + amount
assert new_amount >= 0
logger.info(
"Item '%s' now has amount '%s' from amount '%s'", id, new_amount, old_amount
)
self.execute_commit(
"UPDATE inventory SET amount = :amount WHERE id = :id",
{"amount": new_amount, "id": id},
)
def list_all(self):
self.display_header()
self.execute("SELECT id FROM inventory ORDER BY id")
ids = []
id = self.cursor.fetchone()
while id:
ids.append(id[0])
id = self.cursor.fetchone()
for id in ids:
self.display_item(id)
if ids == []:
print("No corresponding items found")
def delete(self, id):
logger.info("Deleting item '%s'", id)
self.execute_commit("DELETE FROM inventory WHERE id = :id", {"id": id})
def query(self, query):
logger.warning("Using query is unsafe!")
logger.warning("Got query '%s'", query)
logger.warning("This query may not be safe!")
logger.warning("This allows the user to execute arbitrary SQL operations!")
self.execute_commit(query)
ids = []
id = self.cursor.fetchone()
while id:
ids.append(id[0])
id = self.cursor.fetchone()
if ids == []:
print("No items in inventory.")
else:
self.display_header()
for id in ids:
self.display_item(id) | logistic-bot/product | main.py | main.py | py | 6,962 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "logging.getLogger",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "sqlite3.connect",
"line_number": 13,
"usage_type": "call"
}
] |
28426222784 | import cv2
import numpy as np
import time
import imutils
from pyimagesearch.panorama import Stitcher
left =cv2.VideoCapture("http://192.168.43.1:8080/video")
right =cv2.VideoCapture("http://192.168.43.180:8080/video")
while True:
start = time.time()
left_check, left_frame = left.read()
right_check, right_frame = right.read()
# stitching code below this
# load the two images and resize them to have a width of 400 pixels
# (for faster processing)
imageA = left_frame
imageB = right_frame
imageA = imutils.resize(imageA, width=400)
imageB = imutils.resize(imageB, width=400)
# stitch the images together to create a panorama
stitcher = Stitcher()
(result, vis) = stitcher.stitch([imageA, imageB], showMatches=True)
cv2.imshow("Image A", imageA)
cv2.imshow("Image B", imageB)
cv2.imshow("Result", result)
end = time.time()
print(end - start)
#time.sleep(1)
key = cv2.waitKey(1)
if(key==ord('q')):
break
left.release()
right.release()
cv2.destroyAllWindows()
| prince001996/Vision | feed and stitch.py | feed and stitch.py | py | 1,076 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "cv2.VideoCapture",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "cv2.VideoCapture",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "time.time",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "imutils.resize",
"line_... |
25431182159 | from collections import deque
import sys
input = sys.stdin.readline
dx = [0,1,-1,0]
dy = [1,0,0,-1]
def bfs(hx, hy, ex, ey):
queue = deque()
queue.append([hx,hy,0])
visited = [[[-1]*m for _ in range(n)] for __ in range(2)]
visited[0][hy][hx] = 0
while queue:
x,y,use = queue.popleft()
if x == ex and y == ey:
return visited[use][y][x]
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if nx < 0 or ny < 0 or nx >= m or ny >= n:
continue
if not board[ny][nx] and visited[use][ny][nx] == -1:
queue.append([nx, ny, use])
visited[use][ny][nx] = visited[use][y][x] + 1
# 보드가 1이고, 아직 부수지 않았고, 방문하지 않았다면
elif use == 0 and visited[use+1][ny][nx] == -1:
queue.append([nx,ny, use+1])
visited[use+1][ny][nx] = visited[use][y][x] + 1
return -1
n,m = map(int,input().split())
hx,hy = map(int,input().split())
ex,ey = map(int,input().split())
board = [list(map(int,input().split())) for _ in range(n)]
print(bfs(hy-1,hx-1,ey-1,ex-1)) | reddevilmidzy/baekjoonsolve | 백준/Gold/14923. 미로 탈출/미로 탈출.py | 미로 탈출.py | py | 1,231 | python | en | code | 3 | github-code | 1 | [
{
"api_name": "sys.stdin",
"line_number": 3,
"usage_type": "attribute"
},
{
"api_name": "collections.deque",
"line_number": 10,
"usage_type": "call"
}
] |
72920705315 | from django.conf import settings
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http.response import HttpResponseRedirect
from django.urls.base import reverse
from django.views.generic.edit import ProcessFormView
from edc_appointment.models.appointment import Appointment
from edc_constants.constants import YES
from edc_lab.models import Consignee
from edc_lab.models.model_mixins import RequisitionModelMixin
from edc_label.job_result import JobResult
from edc_label.printers_mixin import PrintersMixin
from edc_metadata.constants import REQUIRED, KEYED
from edc_metadata.models import RequisitionMetadata
from ..requisition_report import RequisitionReport
from ..requisition_labels import RequisitionLabels
class RequisitionPrintActionsView(LoginRequiredMixin, PrintersMixin, ProcessFormView):
job_result_cls = JobResult
requisition_report_cls = RequisitionReport
requisition_labels_cls = RequisitionLabels
success_url = settings.DASHBOARD_URL_NAMES.get('subject_dashboard_url')
print_selected_button = 'print_selected_labels'
print_all_button = 'print_all_labels'
print_requisition = 'print_requisition'
checkbox_name = 'selected_panel_names'
def __init__(self, **kwargs):
self._appointment = None
self._selected_panel_names = []
self._requisition_metadata = None
self._requisition_model_cls = None
super().__init__(**kwargs)
def post(self, request, *args, **kwargs):
response = None
if self.selected_panel_names:
if self.request.POST.get('submit') in [
self.print_all_button, self.print_selected_button]:
self.print_labels_action()
elif self.request.POST.get('submit_print_requisition'):
self.consignee = Consignee.objects.get(
pk=self.request.POST.get('submit_print_requisition'))
response = self.render_manifest_to_response_action()
if not response:
subject_identifier = request.POST.get('subject_identifier')
success_url = reverse(self.success_url, kwargs=dict(
subject_identifier=subject_identifier,
appointment=str(self.appointment.pk)))
response = HttpResponseRedirect(redirect_to=f'{success_url}')
return response
def print_labels_action(self):
labels = self.requisition_labels_cls(
requisition_metadata=self.requisition_metadata.filter(
panel_name__in=self.selected_panel_names),
panel_names=self.selected_panel_names,
appointment=self.appointment,
user=self.request.user)
if labels.zpl_data:
job_id = self.clinic_label_printer.stream_print(
zpl_data=labels.zpl_data)
job_result = self.job_result_cls(
name=labels.label_template_name, copies=1, job_ids=[job_id],
printer=self.clinic_label_printer)
messages.success(self.request, job_result.message)
if labels.requisitions_not_printed:
panels = ', '.join(
[str(r.panel_object) for r in labels.requisitions_not_printed])
messages.warning(
self.request,
f'Some selected labels were not printed. See {panels}.')
def render_manifest_to_response_action(self):
panel_names = [r.panel.name for r in self.verified_requisitions]
if panel_names:
requisition_report = self.requisition_report_cls(
appointment=self.appointment,
selected_panel_names=panel_names,
consignee=self.consignee,
request=self.request)
response = requisition_report.render()
else:
messages.error(
self.request, 'Nothing to do. No "verified" requisitions selected.')
response = None
return response
@property
def requisition_metadata(self):
"""Returns a queryset of keyed or required RequisitionMetadata for this
appointment.
"""
if not self._requisition_metadata:
appointment = Appointment.objects.get(
pk=self.request.POST.get('appointment'))
subject_identifier = self.request.POST.get('subject_identifier')
opts = dict(
subject_identifier=subject_identifier,
visit_schedule_name=appointment.visit_schedule_name,
schedule_name=appointment.schedule_name,
visit_code=appointment.visit_code,
visit_code_sequence=appointment.visit_code_sequence)
self._requisition_metadata = RequisitionMetadata.objects.filter(
entry_status__in=[KEYED, REQUIRED], **opts)
return self._requisition_metadata
@property
def selected_panel_names(self):
"""Returns a list of panel names selected on the page.
Returns all on the page if "print all" is submitted.
"""
if not self._selected_panel_names:
if self.request.POST.get('submit') == self.print_all_button:
for metadata in self.requisition_metadata:
self._selected_panel_names.append(metadata.panel_name)
else:
self._selected_panel_names = self.request.POST.getlist(
self.checkbox_name) or []
return self._selected_panel_names
@property
def appointment(self):
if not self._appointment:
self._appointment = Appointment.objects.get(
pk=self.request.POST.get('appointment'))
return self._appointment
@property
def requisition_model_cls(self):
if not self._requisition_model_cls:
for v in self.appointment.visit_model_cls().__dict__.values():
try:
model_cls = getattr(getattr(v, 'rel'), 'related_model')
except AttributeError:
pass
else:
if issubclass(model_cls, RequisitionModelMixin):
self._requisition_model_cls = model_cls
return self._requisition_model_cls
@property
def verified_requisitions(self):
"""Returns a list of "verified" requisition model instances related
to this appointment.
"""
verified_requisitions = []
for k, v in self.appointment.visit_model_cls().__dict__.items():
try:
model_cls = getattr(getattr(v, 'rel'), 'related_model')
except AttributeError:
pass
else:
if issubclass(model_cls, RequisitionModelMixin):
verified_requisitions.extend(
list(getattr(self.appointment.visit, k).filter(
clinic_verified=YES)))
return verified_requisitions
| botswana-harvard/edc-subject-dashboard | edc_subject_dashboard/views/requisition_print_actions_view.py | requisition_print_actions_view.py | py | 6,976 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "django.contrib.auth.mixins.LoginRequiredMixin",
"line_number": 20,
"usage_type": "name"
},
{
"api_name": "edc_label.printers_mixin.PrintersMixin",
"line_number": 20,
"usage_type": "name"
},
{
"api_name": "django.views.generic.edit.ProcessFormView",
"line_number... |
2340154996 | from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
tasks = []
class Task:
def __init__(self, description):
self.description = description
self.completed = False
@app.route('/')
def index():
return render_template('index.html', tasks=tasks)
@app.route('/add_task', methods=['POST'])
def add_task():
task_description = request.form.get('task')
if task_description:
task = Task(task_description)
tasks.append(task)
return redirect(url_for('index'))
@app.route('/delete_task/<int:task_index>')
def delete_task(task_index):
if 0 <= task_index < len(tasks):
tasks.pop(task_index)
return redirect(url_for('index'))
@app.route('/toggle_task/<int:task_index>')
def toggle_task(task_index):
if 0 <= task_index < len(tasks):
tasks[task_index].completed = not tasks[task_index].completed
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)
| Thymester/Todo-Site | app.py | app.py | py | 1,030 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "flask.Flask",
"line_number": 3,
"usage_type": "call"
},
{
"api_name": "flask.render_template",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "flask.request.form.get",
"line_number": 18,
"usage_type": "call"
},
{
"api_name": "flask.request... |
10004379077 | """
Cedric Pereira, Steven Hurkett, Zack Bowles-Lapointe
December 6 2023
Weather App - User Interaction
"""
import sqlite3
import json
from datetime import datetime
from scrape_weather import WeatherScraper
from db_operations import DBOperations
from plot_operations import PlotOperations
class WeatherProcessor:
"""
Represents the Weather Processor where user feedback is given.
"""
def __init__(self):
self.conn = sqlite3.connect('weather.db')
self.cursor = self.conn.cursor()
def weather_menu(self):
"""
This is the menu for the weather processor.
"""
print("Weather Data")
print("1. Download Full Weather Data.")
print("2. Update Weather Data.")
print("3. Show BoxPlot")
print("4. Show LinePlot")
print("5. Exit")
def full_pull(self):
"""
This does a full pull from todays date to the earliest date.
"""
print("Getting fresh data...")
today = datetime.now().date()
text_file = "test.txt"
url = f'https://climate.weather.gc.ca/climate_data/daily_data_e.html?timeframe=2&StationID=27174&EndYear=1996&EndMonth=10&StartYear={today.year}&StartMonth={today.month}&Year={today.year}&Month={today.month}&Day={1}'
scraper = WeatherScraper(url)
scraper.scrape_data()
operations = DBOperations("weather.db")
operations.initialize_db()
operations.purge_data()
with open(text_file, "r") as text_data:
json_data = json.load(text_data)
operations.save_data(json_data)
for date in operations.fetch_data():
print(f"Sample Date: {date[0]}, Location: {date[1]}, Min Temp: {date[2]}, Max Temp: {date[3]}, Average Temp: {date[4]}")
print("Full download completed")
def update_weather(self):
"""
This is used to update the weather data without scraping it all again.
"""
print("Updating weather data, please wait...")
today = datetime.now().date()
self.cursor.execute("SELECT sample_date FROM weather ORDER BY DATE(sample_date) DESC LIMIT 1")
last_update_string = self.cursor.fetchone()[0]
last_month_raw = last_update_string[5:7]
last_month = last_month_raw.rstrip('-')
last_year = last_update_string[0:4]
text_file = "test.txt"
url = f'https://climate.weather.gc.ca/climate_data/daily_data_e.html?timeframe=2&StationID=27174&EndYear={last_year}&EndMonth={last_month}&StartYear={today.year}&StartMonth={today.month}&Year={today.year}&Month={today.month}&Day={1}'
scraper = WeatherScraper(url)
scraper.scrape_data()
operations = DBOperations("weather.db")
operations.initialize_db()
with open(text_file, "r") as text_data:
json_data = json.load(text_data)
operations.save_data(json_data)
for date in operations.fetch_data():
print(f"Sample Date: {date[0]}, Location: {date[1]}, Min Temp: {date[2]}, Max Temp: {date[3]}, Average Temp: {date[4]}")
print("Weather data updated.")
def box_plot(self):
"""
This initiates and sends the variables for the box plot.
"""
self.cursor.execute("SELECT sample_date FROM weather ORDER BY DATE(sample_date) ASC LIMIT 1")
first_year = int(str(self.cursor.fetchone()[0])[0:4])
self.cursor.execute("SELECT sample_date FROM weather ORDER BY DATE(sample_date) DESC LIMIT 1")
last_year = int(str(self.cursor.fetchone()[0])[0:4])
while True:
try:
start_year = int(input(f"Enter a start year between {first_year} and {last_year}: "))
if first_year <= start_year <= last_year:
break
else:
print(f"Please enter a year between {first_year} and {last_year}.")
except ValueError:
print("Error: Enter a valid integer.")
while True:
try:
end_year = int(input(f"Enter a start year between {first_year} and {last_year}: "))
if first_year <= end_year <= last_year:
break
else:
print(f"Please enter a year between {first_year} and {last_year}.")
except ValueError:
print("Error: Enter a valid integer.")
data = []
current_year = start_year
while current_year <= end_year:
self.cursor.execute(f"SELECT * FROM weather where sample_date LIKE '{current_year}-%-%'")
data.append(self.cursor.fetchall())
current_year+=1
plot = PlotOperations()
plot.create_boxplot(data, start_year, end_year)
def line_plot(self):
"""
line plot selects and calls up a line plot.
"""
self.cursor.execute("SELECT sample_date FROM weather ORDER BY DATE(sample_date) ASC LIMIT 1")
first_year = int(str(self.cursor.fetchone()[0])[0:4])
self.cursor.execute("SELECT sample_date FROM weather ORDER BY DATE(sample_date) DESC LIMIT 1")
last_year = int(str(self.cursor.fetchone()[0])[0:4])
while True:
try:
year = int(input(f"Enter a year between {first_year} and {last_year}: "))
if first_year <= year <= last_year:
break
else:
print(f"Please enter a year between {first_year} and {last_year}.")
except ValueError:
print("Error: Enter a valid integer.")
while True:
try:
month = int(input(f"Enter a month between 1 and 12: "))
if 1 <= month <= 12:
break
else:
print(f"Please enter a month between 1 and 12.")
except ValueError:
print("Error: Enter a valid integer.")
db = DBOperations("weather.db")
query = f"SELECT * FROM weather WHERE sample_date LIKE '{year}-{month}-%'"
self.cursor.execute(query)
data_list = self.cursor.fetchall()
if not data_list:
print(f"No data available for {month}/{year}.")
return
plotter = PlotOperations()
plotter.create_lineplot(data_list, month, year)
def user_choice(self, choice):
"""
This handles the users choice in the dialogue.
"""
if choice == 1:
self.full_pull()
elif choice == 2:
self.update_weather()
elif choice == 3:
self.box_plot()
elif choice == 4:
self.line_plot()
elif choice == 5:
self.conn.close()
exit()
else:
print("Invalid selection, try again.")
def process(self):
"""
This initiates the weather menu when called.
"""
self.weather_menu()
try:
user_selection = int(input("Enter an option(1-5): "))
self.user_choice(user_selection)
except ValueError:
print("Invalid selection, try again.")
if __name__ == "__main__":
weather_processor = WeatherProcessor()
weather_processor.process()
| Steeeeeeeve/PythonWeather | weather_processor.py | weather_processor.py | py | 7,254 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "sqlite3.connect",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "datetime.datetime.now",
"line_number": 39,
"usage_type": "call"
},
{
"api_name": "datetime.datetime",
"line_number": 39,
"usage_type": "name"
},
{
"api_name": "scrape_weathe... |
21620611456 | # -*- coding: utf-8 -*-
import scrapy
from power_market.items import CurrentItem
from power_market.items import PdfItem
class EvnSpider(scrapy.Spider):
name = 'EVN'
allowed_domains = ['en.evn.com.vn']
start_urls = ['https://en.evn.com.vn/c3/gioi-thieu-l/Annual-Report-6-13.aspx']
base_url = "https://en.evn.com.vn"
table_url = "https://en.evn.com.vn/c3/gioi-thieu-f/Projects-6-14.aspx"
count = 1
def parse(self, response):
yield scrapy.Request(self.table_url,callback=self.table_grab) # 先抓取网页表格
urls = response.xpath('//div[@class="blog-page page_list"]//@href').getall()
urls = list(map(lambda x: response.urljoin(x),urls))
for url in urls:
if "Annual" in url:
yield scrapy.Request(url,callback=self.pdf_grab) # 筛选含有pdf的链接并执行下载回调
def pdf_grab(self,response):
urls = response.xpath('//div[@id="ContentPlaceHolder1_ctl00_159_content_news"]//@href').getall()
urls = list(map(lambda x: response.urljoin(x),urls))
for pdf_url in urls:
if ".pdf" in pdf_url: # 筛选还有.pdf的链接
filename = str(pdf_url[-10:])
item = PdfItem(filename=filename,pdf_url=pdf_url)
self.count = self.count+1 # 下载计数+1
yield item
def table_grab(self,response):
title = response.xpath('//span[@id="ContentPlaceHolder1_ctl00_1391_ltlTitle"]/text()').get() # 标题
filename = "".join(title) + ".json"
tables = response.xpath('//div[@class="blog margin-bottom-40 content-detail"]//tbody/tr') # 表格
#keys = [] # 放到一个list序列中
values = ''
for table in tables:
tds = table.xpath('td')
for td in tds:
values = values + "".join(td.xpath('p/text()').get()) + ','
values = values + ';'
#keys.append(tds[0].xpath('p/text()').get()) # 列键
#values.append(tds[1].xpath('p/text()').get()) #列值
item = CurrentItem(rename=filename,content=values)
yield item | realAYAYA/power_market | power_market/spiders/EVN.py | EVN.py | py | 2,139 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "scrapy.Spider",
"line_number": 7,
"usage_type": "attribute"
},
{
"api_name": "scrapy.Request",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "scrapy.Request",
"line_number": 23,
"usage_type": "call"
},
{
"api_name": "power_market.items.Pd... |
22895278898 | # This is a sample Python script.
import yfinance as yf
import pandas as pd
import numpy as np
import math as math
def get_stock_info(name):
# Use a breakpoint in the code line below to debug your script.
stock = yf.Ticker(name)
return stock.history(period="1y")
def get_change(current, previous):
if current == previous:
return 0
try:
return (abs(current - previous) / previous) * 100.0
except ZeroDivisionError:
return float('inf')
# Press the green button in the gutter to run the script.
def calculate_dollar_cost_with_min_average_new(df_stock_info, amount, is_dividant):
total_amount = 0
total_shares = 0
days_count = 0
days_uninvested = 0
days_not_invested = 0
df_stock_info.index = np.arange(1, len(df) + 1)
weekly_budget = amount * 5
divident = 0
total_dividant = 0
count =1
five_day_stock = 0
five_day_amount = 0
for index, row in df_stock_info.iterrows():
closed = round(row['Close'],2)
five_day_avg = row['5_day_avg']
if row['Dividends'] != 0 and is_dividant:
divident += (total_shares * row['Dividends'])
total_dividant += divident
share2 = divident / closed
count+=1
total_shares += share2
if math.isnan(row['5_day_avg']):
share = amount / closed
total_amount += amount
total_shares += share
five_day_stock += share
five_day_amount += amount
days_count += 1
weekly_budget -= amount
days_uninvested = 0
continue
if index % 5 == 0:
if weekly_budget > 0:
share = (weekly_budget) / closed
total_amount += (weekly_budget)
total_shares += share
days_count += (weekly_budget/amount)
days_uninvested = 0
five_day_stock = 0
five_day_amount = 0
weekly_budget = amount * 5
our_five_day_avg = 0
if five_day_stock != 0:
our_five_day_avg = five_day_amount / five_day_stock
if closed > (our_five_day_avg * 1.12):
days_uninvested += 1
days_not_invested+= 1
continue
elif weekly_budget > 0:
share = amount / closed
total_amount += amount
total_shares += share
five_day_stock += share
five_day_amount += amount
weekly_budget -= amount
days_count += 1
if closed < our_five_day_avg * 0.8 and weekly_budget > 0:
share = (weekly_budget) / closed
total_amount += (weekly_budget)
total_shares += share
days_count += (weekly_budget/amount)
weekly_budget = 0
days_uninvested = 0
print("total_dividant", round(total_dividant, 2))
print("total_amount", round(total_amount, 2))
print("total_shares", round(total_shares, 2))
print("days_count", days_count)
print("days_not_invested", days_not_invested)
print("Price per share ", total_amount / total_shares)
print("==========================")
return total_amount, total_shares, days_count
# Press the green button in the gutter to run the script.
def calculate_dollar_cost_with_min_average2(df_stock_info, amount):
total_amount = 0
total_shares = 0
days_count = 0
monthly_budget = amount * 20
days_uninvested = 0
df_stock_info.index = np.arange(1, len(df) + 1)
for index, row in df_stock_info.iterrows():
closed = row['Close']
five_day_avg = row['5_day_avg']
if index == 1:
share = amount / closed
total_amount += amount
monthly_budget -= amount
total_shares += share
days_count+=1
#print(row['Date'])
continue
if index % 20 == 0 and monthly_budget > 0:
share = monthly_budget / closed
total_amount += monthly_budget
monthly_budget -= monthly_budget
total_shares += share
days_count += 1
#print(row['Date'])
continue
if index % 20 == 0:
monthly_budget = amount * 20
if days_uninvested == 5:
share = (amount * days_uninvested) / closed
total_amount += (amount * days_uninvested)
total_shares += share
monthly_budget -= (amount * days_uninvested)
days_uninvested = 0
days_count += 5
if math.isnan(row['5_day_avg']):
share = amount / closed
total_amount += amount
monthly_budget -= amount
total_shares += share
days_count += 1
continue
if closed > (row['5_day_avg']):
days_uninvested += 1
continue
if closed < (row['5_day_avg']) and monthly_budget > 0:
if days_uninvested == 0:
days_uninvested = 1
share = (amount*days_uninvested) / closed
total_amount += (amount*days_uninvested)
total_shares += share
monthly_budget-= (amount*days_uninvested)
days_count += days_uninvested
days_uninvested = 0
print("total_amount", round(total_amount, 2))
print("total_shares", round(total_shares, 2))
print("days_count", days_count)
print("Price per share ", (total_amount) / total_shares)
print("==========================")
return total_amount, total_shares, days_count
# Press the green button in the gutter to run the script.
def calculate_dollar_cost(df_stock_info, amount):
total_amount = 0
total_shares = 0
days_count = 0
total_dividant = 0
divident = 0
for index, row in df_stock_info.iterrows():
closed = row['Close']
share = amount / closed
total_amount += amount
total_shares += share
if row['Dividends'] != 0:
divident += (total_shares * row['Dividends'])
total_dividant += divident
days_count += 1
print("total_dividant", round(total_dividant,2))
print("total_amount", round(total_amount,2))
print("total_shares", round(total_shares,2))
print("days_count", days_count)
print("Price per share ", total_amount/total_shares)
print("==========================")
return total_amount, total_shares, days_count
# Press the green button in the gutter to run the script.
def calculate_dollar_cost_with_min_average(df_stock_info, amount):
total_amount = 0
total_shares = 0
days_count = 0
total_dividant = 0
divident = 0
days_uninvested = 0
monthly_budget = amount*20
for index, row in df_stock_info.iterrows():
closed = row['Close']
if days_count == 0:
share = amount / closed
total_amount += amount
monthly_budget -= amount
total_shares += share
days_uninvested +=1
else:
if days_uninvested == 20:
share = (amount*20) / closed
total_amount += amount*20
monthly_budget -= (amount*20)
total_shares += share
days_uninvested = 1
monthly_budget = amount * 20
else:
average_cost = total_amount/total_shares
if closed < (average_cost * 1.02):
share = (amount*days_uninvested) / closed
total_amount += (amount*days_uninvested)
total_shares += share
days_uninvested = 1
if closed <= average_cost:
share = amount / closed
total_amount += amount
monthly_budget -= amount
total_shares += share
days_uninvested = 1
if closed > average_cost * 1.02:
days_uninvested += 1
if days_count % 20 == 0:
if monthly_budget > 0 :
share = (monthly_budget) / closed
total_amount += (monthly_budget)
total_shares += share
days_uninvested = 1
monthly_budget = amount*20
if row['Dividends'] != 0:
divident += (total_shares * row['Dividends'])
total_dividant += divident
days_count += 1
print("uninvested amount ", round(monthly_budget, 2))
print("total_dividant", round(total_dividant,2))
print("total_amount", round(total_amount,2))
print("total_shares", round(total_shares,2))
print("days_count", days_count)
print("Price per share ", total_amount/total_shares)
print("final total amount ", round(monthly_budget + total_amount, 2))
print("==========================")
return total_amount, total_shares, days_count
def calculate_consecutive_low(df_stock_info, amount, dailyInvest):
price_2_days_back = 0
price_1_days_back = 0
amount_invested = 0
total_shares = 0
days_count = 0
collective_amount = 0
for index in range(len(df_stock_info)):
closed = df_stock_info.loc[index, 'Open']
if closed < price_1_days_back < price_2_days_back:
days_count += 1
share = (collective_amount + dailyInvest) / closed
amount_invested += (collective_amount + dailyInvest)
total_shares += share
collective_amount = 0
price_2_days_back = 0
price_1_days_back = 0
else:
share = dailyInvest / closed
collective_amount += (amount - dailyInvest)
amount_invested += dailyInvest
total_shares += share
days_count += 1
price_2_days_back = price_1_days_back
price_1_days_back = closed
print("total_amount for two low", amount_invested)
print("total_shares for two low", total_shares)
print("days_count for two low", days_count)
print("Price per share ", amount_invested/total_shares )
print("==========================")
return amount_invested, total_shares, days_count
def divident_reinvestment(df_stock_info, amount):
total_amount = 0
total_shares = 0
days_count = 0
total_dividant = 0
divident = 0
for index, row in df_stock_info.iterrows():
closed = row['Close']
share = amount / closed
total_amount += amount
total_shares += share
if row['Dividends'] != 0:
divident += (total_shares * row['Dividends'])
total_dividant += divident
share2 = divident / closed
#total_amount += divident
total_shares += share2
days_count += 1
print("total_dividant", round(total_dividant,2))
print("total_amount divident_reinvestment", round(total_amount,2))
print("total_shares divident_reinvestment", round(total_shares,2))
print("days_count divident_reinvestment", days_count)
print("Price per share ", total_amount/total_shares )
return total_amount, total_shares, days_count
def calculate_profit(total_amount_invested, total_shares, closed_price):
profit = round(closed_price * total_shares - total_amount_invested,2)
percent_change_amount = get_change(closed_price * total_shares, total_amount_invested)
print("profit ", profit)
print("percent_change_amount ", percent_change_amount)
print("============== ")
return profit, get_change(closed_price * total_shares, total_amount_invested )
def get_change(current, previous):
if current == previous:
return 0
try:
return (abs(current - previous) / previous) * 100.0
except ZeroDivisionError:
return float('inf')
Input_column = {
"ID": int,
"Name": str,
"Address": str
}
if __name__ == '__main__':
df_stock_info = get_stock_info('VTI')
amount = 5
#print(df_stock_info.columns)
print(df_stock_info)
# Convert the dictionary into DataFrame
pd.set_option("display.max_rows", None, "display.max_columns", None)
df = pd.DataFrame(df_stock_info, columns=['Open', 'High', 'Low', 'Close', 'Volume', 'Dividends', 'Stock Splits'])
df['5_day_avg'] = round(df.Close.rolling(window=5).mean(), 2)
df['closed_p_change'] = df.Close.pct_change(periods=1)
max_value = df.closed_p_change.max()
min_value = df.closed_p_change.min()
mean_value = df.closed_p_change.mean()
print(f"max value {max_value}")
print(f"min value {min_value}")
print(f"mean value {mean_value}")
#df.to_csv("vti_10y.csv")
print("last price")
print(df['Close'].iloc[-1])
#print("calculate_dollar_cost ")
#total_amount_invested, total_shares, days_count = calculate_dollar_cost(df, amount)
#profit, percent_change = calculate_profit(total_amount_invested, total_shares, df['Close'].iloc[-1])
#print("calculate_dollar_cost_with_min_average ")
#total_amount_invested, total_shares, days_count = calculate_dollar_cost_with_min_average_new(df, amount, True)
#profit, percent_change = calculate_profit(total_amount_invested, total_shares, df['Close'].iloc[-1])
print("============== ")
print("divident_reinvestment")
print("============== ")
total_amount, total_shares, days_count = divident_reinvestment(df, amount)
print("============== ")
profit1, percent_change2 = calculate_profit(total_amount, total_shares, df['Close'].iloc[-1])
#print("percent_change direct ", get_change(df['Close'].iloc[-1], df['Close'].iloc[0]))
#print("percent_change ", percent_change)
#print("percent_change ", percent_change2)
#print("calculate_consecutive_low ")
#total_amount_invested, total_shares, days_count = calculate_consecutive_low(df, 15, 0)
#print("difference ", round(profit1 - profit, 2)) | DIGVIJAYMALI/initStockPro | main.py | main.py | py | 13,911 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "yfinance.Ticker",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "numpy.arange",
"line_number": 27,
"usage_type": "call"
},
{
"api_name": "math.isnan",
"line_number": 46,
"usage_type": "call"
},
{
"api_name": "numpy.arange",
"line_numbe... |
24881402559 | import queue
import shlex
import ssl
import subprocess
import sys
import time
from abc import ABC, abstractmethod
from shutil import copyfileobj
from threading import Thread
from typing import Tuple, Union
from urllib.error import URLError
from urllib.request import urlopen
from downloader.constants import K_DOWNLOADER_RETRIES, K_DOWNLOADER_SIZE_MB_LIMIT, \
K_DOWNLOADER_PROCESS_LIMIT, K_DOWNLOADER_TIMEOUT, K_CURL_SSL, K_DEBUG, FILE_MiSTer_new, FILE_MiSTer, \
FILE_MiSTer_old, K_DOWNLOADER_OLD_IMPLEMENTATION, K_DOWNLOADER_THREADS_LIMIT
from downloader.logger import DebugOnlyLoggerDecorator
from downloader.other import calculate_url
from downloader.target_path_repository import TargetPathRepository
class FileDownloaderFactory(ABC):
@abstractmethod
def create(self, config, parallel_update, silent=False, hash_check=True):
"""Created a Parallel or Serial File Downloader"""
def make_file_downloader_factory(file_system_factory, local_repository, waiter, logger):
return _FileDownloaderFactoryImpl(file_system_factory, local_repository, waiter, logger)
class _FileDownloaderFactoryImpl(FileDownloaderFactory):
def __init__(self, file_system_factory, local_repository, waiter, logger):
self._file_system_factory = file_system_factory
self._local_repository = local_repository
self._waiter = waiter
self._logger = logger
def create(self, config, parallel_update, silent=False, hash_check=True):
logger = DebugOnlyLoggerDecorator(self._logger) if silent else self._logger
file_system = self._file_system_factory.create_for_config(config)
target_path_repository = TargetPathRepository(config, file_system)
if config[K_DOWNLOADER_OLD_IMPLEMENTATION]:
self._logger.print('Using old downloader implementation...')
if parallel_update:
return _CurlCustomParallelDownloader(config, file_system, self._local_repository, logger, hash_check, target_path_repository)
else:
return _CurlSerialDownloader(config, file_system, self._local_repository, logger, hash_check, target_path_repository)
else:
thread_limit = config[K_DOWNLOADER_THREADS_LIMIT] if parallel_update else 1
low_level_factory = _LowLevelMultiThreadingFileDownloaderFactory(thread_limit, config, self._waiter, logger)
return HighLevelFileDownloader(hash_check, config, file_system, target_path_repository, low_level_factory, logger)
class FileDownloader(ABC):
@abstractmethod
def queue_file(self, file_description, file_path):
"""queues a file for downloading it later"""
@abstractmethod
def set_base_files_url(self, base_files_url):
"""sets the base_files_url from a database"""
@abstractmethod
def mark_unpacked_zip(self, zip_id, base_zips_url):
"""indicates that a zip is being used, useful for reporting"""
@abstractmethod
def download_files(self, first_run):
"""download all the queued files"""
@abstractmethod
def errors(self):
"""all files with errors"""
@abstractmethod
def correctly_downloaded_files(self):
"""all correctly downloaded files"""
@abstractmethod
def needs_reboot(self):
"""returns true if a file that needs reboot has been downloaded"""
class LowLevelFileDownloader(ABC):
def fetch(self, files_to_download, paths):
""""files_to_download is a dictionary with file_path as keys and file_description as values"""
def network_errors(self):
"""returns errors that happened during download_files"""
def downloaded_files(self):
"""returns files downloaded during download_files"""
class LowLevelFileDownloaderFactory(ABC):
def create_low_level_file_downloader(self, high_level):
""""returns instance of LowLevelFileDownloader"""
class DownloadValidator(ABC):
def validate_download(self, file_path: str, file_hash: str) -> Tuple[int, Union[str, Tuple[str, str]]]:
"""Validates that the downloaded file is correctly installed and moves it if necessary. Returned int is 1 if validation was correct."""
class HighLevelFileDownloader(FileDownloader, DownloadValidator):
def __init__(self, hash_check, config, file_system, target_path_repository, low_level_file_downloader_factory, logger):
self._hash_check = hash_check
self._file_system = file_system
self._target_path_repository = target_path_repository
self._config = config
self._low_level_file_downloader_factory = low_level_file_downloader_factory
self._logger = logger
self._run_files = []
self._queued_files = {}
self._base_files_url = None
self._unpacked_zips = {}
self._needs_reboot = False
self._errors = []
self._correct_files = []
def queue_file(self, file_description, file_path):
self._queued_files[file_path] = file_description
def set_base_files_url(self, base_files_url):
self._base_files_url = base_files_url
def mark_unpacked_zip(self, zip_id, base_zips_url):
self._unpacked_zips[zip_id] = base_zips_url
def download_files(self, _):
for _ in range(self._config[K_DOWNLOADER_RETRIES] + 1):
self._errors = self._download_try()
if len(self._errors):
continue
break
if self._file_system.is_file(FILE_MiSTer_new):
self._logger.print('')
self._logger.print('Copying new MiSTer binary:')
if self._file_system.is_file(FILE_MiSTer):
self._file_system.move(FILE_MiSTer, FILE_MiSTer_old)
self._file_system.move(FILE_MiSTer_new, FILE_MiSTer)
if self._file_system.is_file(FILE_MiSTer):
self._logger.print('New MiSTer binary copied.')
else:
# This error message should never happen.
# If it happens it would be an unexpected case where file_system is not moving files correctly
self._logger.print('CRITICAL ERROR!!! Could not restore the MiSTer binary!')
self._logger.print('Please manually rename the file MiSTer.new as MiSTer')
self._logger.print('Your system won\'nt be able to boot until you do so!')
sys.exit(1)
def _download_try(self):
if len(self._queued_files) == 0:
self._logger.print("Nothing new to download from given sources.")
return []
self._logger.print("Downloading %d files:" % len(self._queued_files))
low_level = self._low_level_file_downloader_factory.create_low_level_file_downloader(self)
files_to_download = []
skip_files = []
for file_path, file_description in self._queued_files.items():
if self._hash_check and self._file_system.is_file(file_path):
path_hash = self._file_system.hash(file_path)
if path_hash == file_description['hash']:
if 'zip_id' in file_description and file_description['zip_id'] in self._unpacked_zips:
self._logger.print('Unpacked: %s' % file_path)
else:
self._logger.print('No changes: %s' % file_path) # @TODO This scenario might be redundant now, since it's also checked in the Online Importer
skip_files.append(file_path)
continue
else:
self._logger.debug('%s: %s != %s' % (file_path, file_description['hash'], path_hash))
if 'url' not in file_description:
file_description['url'] = calculate_url(self._base_files_url, file_path)
self._file_system.make_dirs_parent(file_path)
target_path = self._target_path_repository.create_target(file_path, file_description)
files_to_download.append((file_path, self._file_system.download_target_path(target_path)))
self._run_files.append(file_path)
for file_path in skip_files:
self._correct_files.append(file_path)
self._queued_files.pop(file_path)
low_level.fetch(files_to_download, self._queued_files)
self._check_downloaded_files(low_level.downloaded_files())
return low_level.network_errors()
def validate_download(self, file_path: str, file_hash: str) -> Tuple[int, Union[str, Tuple[str, str]]]:
target_path = self._target_path_repository.access_target(file_path)
if not self._file_system.is_file(target_path):
return 2, (file_path, 'Missing %s' % file_path)
path_hash = self._file_system.hash(target_path)
if self._hash_check and path_hash != file_hash:
self._target_path_repository.clean_target(file_path)
return 2, (file_path, 'Bad hash on %s (%s != %s)' % (file_path, file_hash, path_hash))
self._target_path_repository.finish_target(file_path)
self._logger.debug('+', end='', flush=True)
return 1, file_path
def _check_downloaded_files(self, files):
for path in files:
self._correct_files.append(path)
if self._queued_files[path].get('reboot', False):
self._needs_reboot = True
self._queued_files.pop(path)
def errors(self):
return self._errors
def correctly_downloaded_files(self):
return self._correct_files
def needs_reboot(self):
return self._needs_reboot
def run_files(self):
return self._run_files
def context_from_curl_ssl(curl_ssl):
context = ssl.create_default_context()
if curl_ssl.startswith('--cacert '):
cacert_file = curl_ssl[len('--cacert '):]
context.load_verify_locations(cacert_file)
elif curl_ssl == '--insecure':
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
return context
class _LowLevelMultiThreadingFileDownloaderFactory(LowLevelFileDownloaderFactory):
def __init__(self, threads_limit, config, waiter, logger):
self._threads_limit = threads_limit
self._config = config
self._waiter = waiter
self._logger = logger
def create_low_level_file_downloader(self, download_validator):
return _LowLevelMultiThreadingFileDownloader(self._threads_limit, self._config, context_from_curl_ssl(self._config[K_CURL_SSL]), self._waiter, self._logger, download_validator)
class _LowLevelMultiThreadingFileDownloader(LowLevelFileDownloader):
def __init__(self, threads_limit, config, context, waiter, logger, download_validator):
self._threads_limit = threads_limit
self._config = config
self._context = context
self._waiter = waiter
self._logger = logger
self._download_validator = download_validator
self._network_errors = _DownloadErrors(self._logger)
self._downloaded_files = []
self._pending_notifications = []
self._endl_pending = False
def fetch(self, files_to_download, descriptions):
job_queue = queue.Queue()
notify_queue = queue.Queue()
for path, target in files_to_download:
job_queue.put((descriptions[path]['url'], path, target), False)
threads = [Thread(target=self._thread_worker, args=(job_queue, notify_queue)) for _ in range(min(self._threads_limit, len(files_to_download)))]
for thread in threads:
thread.start()
remaining_notifications = len(files_to_download) * 2
while remaining_notifications > 0:
remaining_notifications -= self._read_notifications(descriptions, notify_queue, True)
self._waiter.sleep(1)
job_queue.join()
for thread in threads:
thread.join()
self._read_notifications(descriptions, notify_queue, False)
self._logger.print()
def _read_notifications(self, descriptions, notify_queue, in_progress):
new_files = False
read_notifications = 0
while not notify_queue.empty():
state, path = notify_queue.get(False)
notify_queue.task_done()
if state == 0:
if self._endl_pending:
self._endl_pending = False
self._logger.print()
self._logger.print(path, flush=True)
new_files = True
elif state == 1:
self._pending_notifications.append(self._download_validator.validate_download(path, descriptions[path]['hash']))
else:
self._pending_notifications.append((state, path))
read_notifications += 1
if new_files:
return read_notifications
if len(self._pending_notifications) > 0:
for state, pack in self._pending_notifications:
if state == 1:
path = pack
self._downloaded_files.append(path)
self._logger.print('.', end='', flush=True)
else:
path, message = pack
self._network_errors.add_debug_report(path, message)
self._logger.print('~', end='', flush=True)
elif in_progress:
self._logger.print('*', end='', flush=True)
self._endl_pending = in_progress
self._pending_notifications.clear()
return read_notifications
def network_errors(self):
return self._network_errors.list()
def downloaded_files(self):
return self._downloaded_files
def _thread_worker(self, job_queue, notify_queue):
while not job_queue.empty():
url, path, target = job_queue.get(False)
notify_queue.put((0, path), False)
try:
with urlopen(url, timeout=self._config[K_DOWNLOADER_TIMEOUT], context=self._context) as in_stream, open(target, 'wb') as out_file:
if in_stream.status == 200:
copyfileobj(in_stream, out_file)
notify_queue.put((1, path), False)
else:
notify_queue.put((2, (path, 'Bad http status! %s: %s' % (path, in_stream.status))), False)
except URLError as e:
notify_queue.put((2, (path, 'HTTP error! %s: %s' % (path, e.reason))), False)
except ConnectionResetError as e:
notify_queue.put((2, (path, 'Connection reset error! %s: %s' % (path, str(e)))), False)
except Exception as e:
notify_queue.put((2, (path, 'Exception during download! %s: %s' % (path, str(e)))), False)
job_queue.task_done()
class CurlDownloaderAbstract(FileDownloader):
def __init__(self, config, file_system, local_repository, logger, hash_check, temp_files_registry):
self._config = config
self._file_system = file_system
self._logger = logger
self._local_repository = local_repository
self._hash_check = hash_check
self._temp_files_registry = temp_files_registry
self._curl_list = {}
self._errors = _DownloadErrors(logger)
self._http_oks = _HttpOks()
self._correct_downloads = []
self._needs_reboot = False
self._base_files_url = None
self._unpacked_zips = dict()
def queue_file(self, file_description, file_path):
self._curl_list[file_path] = file_description
def set_base_files_url(self, base_files_url):
self._base_files_url = base_files_url
def mark_unpacked_zip(self, zip_id, base_zips_url):
self._unpacked_zips[zip_id] = base_zips_url
def download_files(self, first_run):
self._download_files_internal(first_run)
if self._file_system.is_file(FILE_MiSTer_new):
self._logger.print()
self._logger.print('Copying new MiSTer binary:')
if self._file_system.is_file(FILE_MiSTer):
self._file_system.move(FILE_MiSTer, FILE_MiSTer_old)
self._file_system.move(FILE_MiSTer_new, FILE_MiSTer)
if self._file_system.is_file(FILE_MiSTer):
self._logger.print('New MiSTer binary copied.')
else:
# This error message should never happen.
# If it happens it would be an unexpected case where file_system is not moving files correctly
self._logger.print('CRITICAL ERROR!!! Could not restore the MiSTer binary!')
self._logger.print('Please manually rename the file MiSTer.new as MiSTer')
self._logger.print('Your system won\'nt be able to boot until you do so!')
sys.exit(1)
def _download_files_internal(self, first_run):
if len(self._curl_list) == 0:
self._logger.print("Nothing new to download from given sources.")
return
self._logger.print("Downloading %d files:" % len(self._curl_list))
for path in sorted(self._curl_list):
description = self._curl_list[path]
if self._hash_check and self._file_system.is_file(path):
path_hash = self._file_system.hash(path)
if path_hash == description['hash']:
if 'zip_id' in description and description['zip_id'] in self._unpacked_zips:
self._logger.print('Unpacked: %s' % path)
else:
self._logger.print('No changes: %s' % path) # @TODO This scenario might be redundant now, since it's also checked in the Online Importer
self._correct_downloads.append(path)
continue
else:
self._logger.debug('%s: %s != %s' % (path, description['hash'], path_hash))
if first_run:
if 'delete' in description:
for _ in description['delete']: # @TODO This is Deprecated
self._file_system.delete_previous(path)
break
elif 'delete_previous' in description and description['delete_previous']:
self._file_system.delete_previous(path)
self._download(path, description)
self._wait()
self._check_hashes()
for retry in range(self._config[K_DOWNLOADER_RETRIES]):
if self._errors.none():
return
for path in self._errors.consume():
self._download(path, self._curl_list[path])
self._wait()
self._check_hashes()
def _check_hashes(self):
if self._http_oks.none():
return
self._logger.print()
self._logger.print('Checking hashes...')
for path in self._http_oks.consume():
if not self._file_system.is_file(self._temp_files_registry.access_target(path)):
self._errors.add_debug_report(path, 'Missing %s' % path)
continue
path_hash = self._file_system.hash(self._temp_files_registry.access_target(path))
if self._hash_check and path_hash != self._curl_list[path]['hash']:
self._errors.add_debug_report(path, 'Bad hash on %s (%s != %s)' % (path, self._curl_list[path]['hash'], path_hash))
self._temp_files_registry.clean_target(path)
continue
self._temp_files_registry.finish_target(path)
self._logger.print('+', end='', flush=True)
self._correct_downloads.append(path)
if self._curl_list[path].get('reboot', False):
self._needs_reboot = True
self._logger.print()
def _download(self, path, description):
if 'zip_path' in description:
raise FileDownloaderError('zip_path is not a valid field for the file "%s", please contain the DB maintainer' % path)
self._logger.print(path)
self._file_system.make_dirs_parent(path)
if 'url' not in description:
description['url'] = calculate_url(self._base_files_url, path)
target_path = self._temp_files_registry.create_target(path, description)
if self._config[K_DEBUG] and target_path.startswith('/tmp/') and not description['url'].startswith('http'):
self._file_system.copy(description['url'], target_path)
self._run(description, 'echo > /dev/null', path)
return
self._run(description, self._command(target_path, description['url']), path)
def _command(self, target_path, url):
return 'curl %s --show-error --fail --location -o "%s" "%s"' % (self._config[K_CURL_SSL], target_path, url)
def errors(self):
return self._errors.list()
def correctly_downloaded_files(self):
return self._correct_downloads
def needs_reboot(self):
return self._needs_reboot
@abstractmethod
def _wait(self):
""""waits until all downloads are completed"""
@abstractmethod
def _run(self, description, command, path):
""""starts the downloading process"""
class _CurlCustomParallelDownloader(CurlDownloaderAbstract):
def __init__(self, config, file_system, local_repository, logger, hash_check, temp_file_registry):
super().__init__(config, file_system, local_repository, logger, hash_check, temp_file_registry)
self._processes = []
self._files = []
self._acc_size = 0
def _run(self, description, command, file):
self._acc_size = self._acc_size + description['size']
result = subprocess.Popen(shlex.split(command), shell=False, stderr=subprocess.DEVNULL,
stdout=subprocess.DEVNULL)
self._processes.append(result)
self._files.append(file)
more_accumulated_size_than_limit = self._acc_size > (1000 * 1000 * self._config[K_DOWNLOADER_SIZE_MB_LIMIT])
more_processes_than_limit = len(self._processes) > self._config[K_DOWNLOADER_PROCESS_LIMIT]
if more_accumulated_size_than_limit or more_processes_than_limit:
self._wait()
def _wait(self):
count = 0
start = time.time()
while count < len(self._processes):
some_completed = False
for i, p in enumerate(self._processes):
if p is None:
continue
result = p.poll()
if result is not None:
self._processes[i] = None
some_completed = True
count = count + 1
start = time.time()
self._logger.print('.', end='', flush=True)
if result == 0:
self._http_oks.add(self._files[i])
else:
self._errors.add_debug_report(self._files[i], 'Bad http code! %s: %s' % (result, self._files[i]))
end = time.time()
if (end - start) > self._config[K_DOWNLOADER_TIMEOUT]:
for i, p in enumerate(self._processes):
if p is None:
continue
self._errors.add_debug_report(self._files[i], 'Timeout! %s' % self._files[i])
break
time.sleep(1)
if not some_completed:
self._logger.print('*', end='', flush=True)
self._logger.print(flush=True)
self._processes = []
self._files = []
self._acc_size = 0
class _CurlSerialDownloader(CurlDownloaderAbstract):
def __init__(self, config, file_system, local_repository, logger, hash_check, temp_file_registry):
super().__init__(config, file_system, local_repository, logger, hash_check, temp_file_registry)
def _run(self, description, command, file):
result = subprocess.run(shlex.split(command), shell=False, stderr=subprocess.STDOUT)
if result.returncode == 0:
self._http_oks.add(file)
else:
self._errors.add_print_report(file, 'Bad http code! %s: %s' % (result.returncode, file))
self._logger.print()
def _wait(self):
pass
class _DownloadErrors:
def __init__(self, logger):
self._logger = logger
self._errors = []
def add_debug_report(self, path, message):
self._logger.print('~', end='', flush=True)
self._logger.debug(message, flush=True)
self._errors.append(path)
def add_print_report(self, path, message):
self._logger.print(message, flush=True)
self._errors.append(path)
def none(self):
return len(self._errors) == 0
def consume(self):
errors = self._errors
self._errors = []
return errors
def list(self):
return self._errors
class _HttpOks:
def __init__(self):
self._oks = []
def add(self, path):
self._oks.append(path)
def consume(self):
oks = self._oks
self._oks = []
return oks
def none(self):
return len(self._oks) == 0
class FileDownloaderError(Exception):
pass
| theypsilon-test/downloader | src/downloader/file_downloader.py | file_downloader.py | py | 25,141 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "abc.ABC",
"line_number": 22,
"usage_type": "name"
},
{
"api_name": "abc.abstractmethod",
"line_number": 23,
"usage_type": "name"
},
{
"api_name": "downloader.logger.DebugOnlyLoggerDecorator",
"line_number": 40,
"usage_type": "call"
},
{
"api_name": ... |
38681288341 | import numpy as np
import sklearn.metrics
import matplotlib.pyplot as plt
import tqdm
def prcurve_from_similarity_matrix(GT_MAP, SIM_MAP, nintervals, visualize = False):
GTP = np.sum(GT_MAP)
alt_GTP = np.sum(np.sum(GT_MAP,axis=1) > 0)
precisions = []
recalls = []
alt_precisions = []
alt_recalls = []
#min_dist = np.min(SIM_MAP)
max_sim = np.max(SIM_MAP)
min_sim = np.min(SIM_MAP)
start = max_sim#2*min_dist
step = (max_sim - min_sim) / nintervals#(1+start) / nintervals#(2-start)/nintervals
def get_threshold(i):
return start - step * (i+1)
prev_alt_TP = np.zeros((GT_MAP.shape[0]))
print("Generating PR curve ...")
for i in tqdm.tqdm(range(nintervals+1)):
threshold = get_threshold(i)
MASK = SIM_MAP >= threshold
TP = np.sum(GT_MAP * MASK)
FP = np.sum((1-GT_MAP)*MASK)
precision = TP/(TP+FP)
recall = TP/GTP
precisions.append(precision)
recalls.append(recall)
alt_FP = np.logical_and(np.sum((1-GT_MAP)*MASK,axis=1) > 0, np.logical_not(prev_alt_TP)) # nqueryx1, rows with at least one false positive
alt_TP = np.logical_and(np.sum(GT_MAP * MASK,axis = 1) > 0,np.logical_not(alt_FP)) # nqueryx1, rows with at least one true positive and no false positives
prev_alt_TP = np.logical_or(prev_alt_TP,alt_TP)
alt_TP = np.sum(alt_TP)
alt_FP = np.sum(alt_FP)
alt_precision = alt_TP/(alt_TP+alt_FP)
alt_recall = alt_TP/alt_GTP
alt_precisions.append(alt_precision)
alt_recalls.append(alt_recall)
print("Done")
nintervals = nintervals + 1
recalls = np.array(recalls)
precisions = np.array(precisions)
auc = sklearn.metrics.auc(recalls, precisions)
print("Area under curve: ",auc)
alt_recalls = np.array(alt_recalls)
alt_precisions = np.array(alt_precisions)
alt_auc = sklearn.metrics.auc(alt_recalls, alt_precisions)
print("Area under curve (alt): ",alt_auc)
f1_scores = 2*(precisions * recalls)/(precisions+recalls+1e-6)
optimal_threshold_index = np.argmax(f1_scores)
optimal_threshold = get_threshold(optimal_threshold_index)
print("optimal threshold: ",optimal_threshold)
print("Precision at optimal threshold: ", precisions[optimal_threshold_index])
print("Recall at optimal threshold: ", recalls[optimal_threshold_index])
alt_f1_scores = 2*(alt_precisions * alt_recalls)/(alt_precisions+alt_recalls+1e-6)
alt_optimal_threshold_index = np.argmax(alt_f1_scores)
alt_optimal_threshold = get_threshold(alt_optimal_threshold_index)
print("optimal threshold (alt): ",alt_optimal_threshold)
print("Precision at optimal threshold (alt): ", alt_precisions[alt_optimal_threshold_index])
print("Recall at optimal threshold (alt): ", alt_recalls[alt_optimal_threshold_index])
max_recall_100 = 0
max_recall_99 = 0
max_recall_95 = 0
for p,r in zip(precisions, recalls):
if p >= 0.95:
max_recall_95 = max(max_recall_95, r)
if p >= 0.99:
max_recall_99 = max(max_recall_99, r)
if p >= 1.:
max_recall_100 = max(max_recall_100, r)
print("R@100P:", max_recall_100)
print("R@99P:", max_recall_99)
print("R@95P:", max_recall_95)
max_recall_100 = 0
max_recall_99 = 0
max_recall_95 = 0
for p,r in zip(alt_precisions, alt_recalls):
if p >= 0.95:
max_recall_95 = max(max_recall_95, r)
if p >= 0.99:
max_recall_99 = max(max_recall_99, r)
if p >= 1.:
max_recall_100 = max(max_recall_100, r)
print("R@100P (alt):", max_recall_100)
print("R@99P (alt):", max_recall_99)
print("R@95P (alt):", max_recall_95)
if visualize:
_, axs = plt.subplots(1,2)
axs[0].plot(recalls, precisions , marker='o')
axs[0].axvline(recalls[optimal_threshold_index], color='r')
axs[0].set(xlabel="recall", ylabel="precision")
axs[0].title.set_text("PR Curve")
axs[1].plot(list(range(nintervals)), precisions, color = 'b')
axs[1].plot(list(range(nintervals)), recalls, color = 'g')
axs[1].plot(list(range(nintervals)), f1_scores, color = 'k')
axs[1].axvline(optimal_threshold_index, color='r')
axs[1].set(xlabel="threshold", ylabel="precision - recall")
axs[1].title.set_text("Precision (b) and recall (g) curves")
plt.show()
_, axs = plt.subplots(1,2)
axs[0].plot(alt_recalls, alt_precisions , marker='o')
axs[0].axvline(alt_recalls[alt_optimal_threshold_index], color='r')
axs[0].set(xlabel="recall", ylabel="precision")
axs[0].title.set_text("PR Curve")
axs[1].plot(list(range(nintervals)), alt_precisions, color = 'b')
axs[1].plot(list(range(nintervals)), alt_recalls, color = 'g')
axs[1].plot(list(range(nintervals)), alt_f1_scores, color = 'k')
axs[1].axvline(alt_optimal_threshold_index, color='r')
axs[1].set(xlabel="threshold", ylabel="precision - recall")
axs[1].title.set_text("Precision (b) and recall (g) curves")
plt.show()
return alt_precisions[alt_optimal_threshold_index], alt_auc, alt_optimal_threshold, [get_threshold(i) for i in range(nintervals)]
| ivano-donadi/sdpr | lib/utils/eval_utils.py | eval_utils.py | py | 5,345 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "numpy.sum",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "numpy.sum",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "numpy.max",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "numpy.min",
"line_number": 15,
"u... |
23620492131 | import SuperClass as sc
import tkinter as tk
from PIL import Image,ImageTk
class Entity(sc.SpaceInvader):
def __init__(self):
sc.SpaceInvader.__init__(self)
self.canvas.bind("<Configure>", self.update)
self.vie = 1
self.sprite = Image.open("media/image/male_sprite_model.png")
self.anim = [[2,3,4,3,2,1,0,1], [2,3,4,3,2,1,0,1], [1,2,3,5,6,7], [1,2,3,5,6,7]]
self.direction = 1
self.animation = 0
self.cropingSrpite() #definie self.cropSprite
self.position = (10, 10)
self.canvas.after(self.tac, self.tic)
def cropingSrpite(self, direction = None, animation = None):#haut direction 0, bas direction 1, droite direction 2, gauche direction 3
if direction == None:
direction = self.direction
else:
self.direction = direction
if animation == None:
animation = self.animation
else:
self.animation = animation
self.cropSprite = self.sprite.crop((32*self.anim[direction][animation], 64*direction, 32*(self.anim[direction][animation]+1), 64*(direction+1)))
self.update()
def update(self, e=None):
#self.canvas.delete("all")
"""
redimentionne l'image
"""
#resize
self.resizeSprite= self.cropSprite.resize((self.vw(10)+1,2*self.vw(10)+1), Image.ANTIALIAS)#+1 car on ne doit pas resize par 0
self.tkResizeSprite = ImageTk.PhotoImage(self.resizeSprite)
self.canvas.create_image(self.vw(50),self.vh(50), image = self.tkResizeSprite)
def tic(self):
if self.animation+1 < len(self.anim[self.direction]):
self.animation += 1
else:
self.animation = 0
self.canvas.after(self.tac, self.tic)
self.cropingSrpite()
class Joueur(Entity):
def __init__(self):
Entity.__init__(self)
self.canvas.bind_all("<Key>", self.moving)
def moving(self, e):
if e.char == "z":
self.cropingSrpite(0,0)
elif e.char == "s":
self.cropingSrpite(1,0)
elif e.char == "d":
self.cropingSrpite(2,0)
elif e.char == "q":
self.cropingSrpite(3,0)
else:
print(e.char)
| 12dorian12/projet_Space_Invader | Entity.py | Entity.py | py | 2,295 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "SuperClass.SpaceInvader",
"line_number": 5,
"usage_type": "attribute"
},
{
"api_name": "SuperClass.SpaceInvader.__init__",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "SuperClass.SpaceInvader",
"line_number": 7,
"usage_type": "attribute"
},
... |
33382878650 | # This code is based on the following example:
# https://discordpy.readthedocs.io/en/stable/quickstart.html#a-minimal-bot
import discord
from discord.ext import commands
import os
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
client_id = os.getenv('SPOTIPY_CLIENT_ID')
client_secret = os.getenv('SPOTIPY_CLIENT_SECRET')
bot_token = os.getenv('BOT_TOKEN')
intents = discord.Intents.default() # Create an instance of Intents
intents.typing = False # Disable typing events, if desired
intents.presences = False # Disable presence events, if desired
bot = commands.Bot(command_prefix='/', intents=intents)
client = discord.Client(intents=intents)
logic_uri = 'https://open.spotify.com/artist/4xRYI6VqpkE3UwrDrAZL8L?si=sqOCFbjFRx6jpHaWogSVrg'
client_credentials_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret)
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
results = sp.artist_albums(logic_uri, album_type='album')
albums = results['items']
while results['next']:
results = sp.next(results)
albums.extend(results['items'])
for album in albums:
print(album['name'])
id_list = []
tracks = sp.album_tracks('https://open.spotify.com/album/7viNUmZZ8ztn2UB4XB3jIL?si=CoKXRho2SOuD5FByREFw9A')
# if 'items' in tracks:
# for track in tracks['items']:
# id_list.append(tracks['id'])
# else:
# print("No tracks found for the given album ID.")
# print(tracks['uri'])
# @bot.event
# async def on_ready():
# print(f'Bot connected as {bot.user.name}')
sp.start_playback(device_id=None, uris= ['spotify:artist:6l3HvQ5sa6mXTsMTB19rO5'], offset=None)
# client.run(os.getenv(bot_token)) | jjneutron/BAST.bot | main.py | main.py | py | 1,699 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "os.getenv",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "os.getenv",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "os.getenv",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "discord.Intents.default",
"line_num... |
22418667308 | from enum import Enum
class InsertType(Enum):
"""Type of inserted in google suite."""
TEXT = "text"
TABLE = "table"
GRAPH = "graph"
IMAGE = "image"
class ScopeType(Enum):
"""Type of scopes for google suite.
PRESENTATION_EDITABLE: Allows read/write access to the user's presentations and their properties.
PRESENTATION_READONLY: Allows read-only access to the user's presentations and their properties.
SHEETS_EDITABLE: Allows read/write access to the user's sheets and their properties.
SHEETS_READONLY: Allows read-only access to the user's sheets and their properties.
DRIVE_FILES: Per-file access to files created or opened by the app.
DRIVE_READONLY: Allows read-only access to the user's file metadata and file content.
DRIVE: Full, permissive scope to access all of a user's files.
Request this scope only when it is strictly necessary.
"""
PRESENTATION_EDITABLE = ["https://www.googleapis.com/auth/presentations"]
PRESENTATION_READONLY = ["https://www.googleapis.com/auth/presentations.readonly"]
SHEETS_EDITABLE = ["https://www.googleapis.com/auth/spreadsheets"]
SHEETS_READONLY = ["https://www.googleapis.com/auth/spreadsheets.readonly"]
DRIVE_FILES = ["https://www.googleapis.com/auth/drive.file"]
DRIVE_READONLY = ["https://www.googleapis.com/auth/drive.readonly"]
DRIVE = ["https://www.googleapis.com/auth/drive"]
class CredentialType(Enum):
"""Type of credential."""
API_KEYS = "api_keys"
OAUTH = "oauth"
SERVICE_ACCOUNT = "service_account"
class SlideLayout(Enum):
"""Type of slide layout"""
BLANK = "BLANK"
CAPTION_ONLY = "CAPTION_ONLY"
TITLE = "TITLE"
TITLE_AND_BODY = "TITLE_AND_BODY"
TITLE_AND_TWO_COLUMNS = "TITLE_AND_TWO_COLUMNS"
TITLE_ONLY = "TITLE_ONLY"
SECTION_HEADER = "SECTION_HEADER"
SECTION_TITLE_AND_DESCRIPTION = "SECTION_TITLE_AND_DESCRIPTION"
ONE_COLUMN_TEXT = "ONE_COLUMN_TEXT"
MAIN_POINT = "MAIN_POINT"
BIG_NUMBER = "BIG_NUMBER"
| ktro2828/py2gsuite | py2gsuite/utils/types.py | types.py | py | 2,031 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "enum.Enum",
"line_number": 4,
"usage_type": "name"
},
{
"api_name": "enum.Enum",
"line_number": 13,
"usage_type": "name"
},
{
"api_name": "enum.Enum",
"line_number": 35,
"usage_type": "name"
},
{
"api_name": "enum.Enum",
"line_number": 43,
"... |
17626284356 | import os
import pandas as pd
import numpy as np
import pickle
import json
from uuid import uuid4
from time import time
from importlib import import_module
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import make_scorer
from params import Params
# input files
train_feat_path = os.path.join(os.getenv('DATA_PATH'), os.getenv('TRAIN_FEATURES_FILENAME'))
train_labels_path = os.path.join(os.getenv('DATA_PATH'), os.getenv('TRAIN_LABELS_FILENAME'))
# output files
model_path = os.path.join(os.getenv('MODEL_PATH'), os.getenv('MODEL_FILENAME'))
best_params_path = os.path.join(os.getenv('MODEL_PATH'), os.getenv('BEST_PARAMS_FILENAME'))
metrics_path = os.path.join(os.getenv('MODEL_PATH'), os.getenv('METRICS_FILENAME'))
def load_data():
"""
Loads train set
:return: X_train, y_train
"""
print("Loading dataset...")
X_train = pd.read_csv(train_feat_path, low_memory=True).set_index('form_id')
y_train = pd.read_csv(train_labels_path, low_memory=True).set_index('form_id')
return X_train, y_train
def load_pipeline():
"""
Loads training pipeline
:return: Pipeline, scorer
"""
Scaler = getattr(
import_module(
Params.SCALER_ORIGIN
),
Params.SCALER_NAME
)
Model = getattr(
import_module(
Params.ALGO_ORIGIN
),
Params.ALGO_NAME
)
scorer = make_scorer(
getattr(
import_module(
Params.METRIC_ORIGIN
),
Params.METRIC_NAME
)
)
return Pipeline([('scaler', Scaler()), ('model', Model())]), scorer
if __name__ == "__main__":
time_init = time()
print("Starting training stage...")
X_train, y_train = load_data()
n_samples, n_features = X_train.shape
print("Train set:")
print(f"-> {n_samples} samples")
print(f"-> {n_features} features")
pipeline, scorer = load_pipeline()
model = GridSearchCV(pipeline,
param_grid=eval(Params.PARAMS_GRID),
cv=Params.CV,
scoring=scorer,
verbose=1)
print("Performing grid search...")
print("Pipeline:", [name for name, _ in pipeline.steps])
print("Parameters:")
print(eval(Params.PARAMS_GRID))
t0 = time()
model.fit(X_train, y_train.values.ravel())
print(f"Done in {round((time() - t0), 3)} seconds")
print()
model_id = str(uuid4())
best_parameters = model.best_estimator_.get_params()
best_score = model.best_score_
print(f"Trained model ID: {model_id}")
print(f"Best score on {Params.METRIC_NAME}: {best_score}")
print("Best parameters set:")
best_params_dict = {"model_id": model_id}
for param_name in sorted(best_parameters.keys()):
if '__' in param_name:
best_params_dict[param_name.split('__')[1]] = best_parameters[param_name]
print("\t%s: %r" % (param_name.split('__')[1], best_parameters[param_name]))
with open(model_path, 'wb') as outfile:
versioned_model = {
"model": model,
"model_id": model_id,
"feats_idx": Params.RELEVANT_FEATS_IDX}
pickle.dump(versioned_model, outfile)
with open(best_params_path, 'w') as outfile:
json.dump(best_params_dict, outfile)
metrics = {
"model_id": model_id,
"train": {
Params.METRIC_NAME: best_score,
"support": X_train.shape[0],
}
}
with open(metrics_path, 'w') as outfile:
json.dump(metrics, outfile)
print(f"Training stage finished in {round(time() - time_init, 2)} seconds")
| MurreyCode/completion_rate_case_study | pipeline/src/search_n_train.py | search_n_train.py | py | 3,720 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "os.path.join",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 16,
"usage_type": "attribute"
},
{
"api_name": "os.getenv",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "os.path.join",
"line_number":... |
14266536126 | import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
def calculate_hit_rate(left_out_dict, user_ids_lst, top_20_recommended_ids):
'''
Claculate hit rate for top 20 using left-one-out set
'''
hit_rate = 0
total_users = len(user_ids_lst)
for user, ids_lst in zip(user_ids_lst, top_20_recommended_ids):
if left_out_dict[user] in ids_lst:
hit_rate += 1
return hit_rate/total_users
def aggregare_vectors(people_lst, artists_vectors_df):
'''
return mean of the vectors from people_lst
'''
vector_matrix = np.array(artists_vectors_df[artists_vectors_df['person_id'].isin(set(people_lst))]['vector'])
if len(vector_matrix) > 1:
return np.mean(vector_matrix, axis=0)
else:
if len(vector_matrix) == 1:
return vector_matrix[0]
else:
return vector_matrix
def topN_similar_by_vector(artists_vectors_df, aggr_vector, N = 20):
'''
predict top-N similar artists to the vector aggr_vector
'''
sim = cosine_similarity(aggr_vector.reshape(1,-1), list(artists_vectors_df['vector']))[0]
df = artists_vectors_df.copy()
df['score'] = sim
df = df.sort_values(by = ['score'], ascending = False)
sim_artists = df['person_id'][:N]
sim_scores = df['score'][:N]
return list(sim_artists), list(sim_scores)
def recommend_by_user(model, left_out_row, user_code_dict, code_person_dict, user_artist_matrix, N=20):
'''
Recommend the top N items, removing the users own liked items from
the results (implicit library do it automatically)
'''
user_id = left_out_row['user_id']
user_code = user_code_dict[user_id]
rec = model.recommend(user_code, user_artist_matrix, N=N)
rec_persons = [code_person_dict[code] for (code,score) in rec]
return rec_persons
def recommend_by_average(test_df_row, artists_vectors_df, N=20):
'''
Custom recommender. Recommend most similar vectors from item factors (vectors)
using cosine similarity
'''
persons_lst = test_df_row['persons_lst']
aggr_v = aggregare_vectors(persons_lst, artists_vectors_df)
N = len(set(persons_lst))+N
if len(aggr_v)!=0:
artists, scores = topN_similar_by_vector(artists_vectors_df, aggr_v, N=N)
artists_new = []
for ar in artists:
if ar not in set(persons_lst):
artists_new.append(ar)
return(artists_new[:20])
else:
return([])
| ShalyginaA/30Music-artist-recommendation | utils/CF_recommender_utils.py | CF_recommender_utils.py | py | 2,547 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "numpy.array",
"line_number": 21,
"usage_type": "call"
},
{
"api_name": "numpy.mean",
"line_number": 23,
"usage_type": "call"
},
{
"api_name": "sklearn.metrics.pairwise.cosine_similarity",
"line_number": 35,
"usage_type": "call"
}
] |
15623826738 | from rest_framework import serializers
from books.models import Book, Book_Review
from users.models import CustomUser
class CustomUserModelSerializer(serializers.ModelSerializer):
class Meta:
model = CustomUser
fields = ('username', 'first_name', 'last_name', 'email')
class BookModelSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('id', 'title', 'description', 'cover_img', 'isbn', 'created')
class BookReviewSerializer(serializers.ModelSerializer):
user = CustomUserModelSerializer(read_only=True)
book = BookModelSerializer(read_only=True)
book_id = serializers.IntegerField(write_only=True)
user_id = serializers.IntegerField(write_only=True)
class Meta:
model = Book_Review
fields = ('id', 'body', 'user','stars_given', 'book', 'created', 'user_id', 'book_id') | ubaydulloh1/goodreads | api/serializers.py | serializers.py | py | 897 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "rest_framework.serializers.ModelSerializer",
"line_number": 5,
"usage_type": "attribute"
},
{
"api_name": "rest_framework.serializers",
"line_number": 5,
"usage_type": "name"
},
{
"api_name": "users.models.CustomUser",
"line_number": 7,
"usage_type": "name"... |
19511514367 | """
Created on Oct 19, 2017
@author: ionut
"""
import sqlite3
def get_config():
"""Return dict of key-value from config table"""
conn = sqlite3.connect("openexcavator.db")
cursor = conn.cursor()
cursor.execute("SELECT key,value FROM config")
config = {}
rows = cursor.fetchall()
for row in rows:
config[row[0]] = row[1]
conn.close()
return config
def set_config(data):
"""
Store configuration using key-value pairs in config table
:param data: dict of key-value pairs
"""
conn = sqlite3.connect("openexcavator.db")
cursor = conn.cursor()
config = get_config()
for key, value in config.items():
if data[key] is None:
continue
if str(value) != str(data[key]):
cursor.execute("UPDATE config SET value=? WHERE key=?", (data[key], key))
conn.commit()
conn.close()
def create_structure():
"""Create database and config table if it does not exist"""
conn = sqlite3.connect("openexcavator.db")
cursor = conn.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS config(id INTEGER PRIMARY KEY AUTOINCREMENT,
key TEXT, value TEXT,CONSTRAINT config_unique_key UNIQUE(key))""")
conn.commit()
conn.close()
def populate_config():
"""Populate configuration table with default values"""
conn = sqlite3.connect("openexcavator.db")
query = "INSERT INTO config(key, value) VALUES(?, ?)"
data = [
("wifi_ssid", ""),
("wifi_psk", ""),
("gps_host", "127.0.0.1"),
("gps_port", "9000"),
("imu_host", "127.0.0.1"),
("imu_port", "7000"),
("start_altitude", "700"),
("stop_altitude", "800"),
("antenna_height", "10"),
("safety_depth", "690"),
("safety_height", "810"),
("output_port", "3000"),
("path", """{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "antenna height": 2.000000, "lateral rms": 0.003500, "name": "Point SW", "projected mean": "-112.703825456 52.3176660209 799.042152941", "rms": "0.00126915901344 0.0032847809571 0.00523463521128", "sample count": 17.000000, "solution status": "FLOAT" }, "geometry": { "type": "Point", "coordinates": [ -112.704198, 52.317718, 799.042152941176596 ] } },
{ "type": "Feature", "properties": { "antenna height": 2.000000, "lateral rms": 0.000100, "name": "Point 2", "projected mean": "-112.703831819 52.3176664518 799.3206125", "rms": "0.000142642689639 -3.20164952526e-11 0.000164207555928", "sample count": 8.000000, "solution status": "FIX" }, "geometry": { "type": "Point", "coordinates": [ -112.703082, 52.317827, 799.320612499999925 ] } }
]
}""")
]
cursor = conn.cursor()
for item in data:
try:
cursor.execute(query, item)
conn.commit()
except sqlite3.IntegrityError as exc:
print("cannot insert items %s: %s" % (item[0], exc))
conn.close()
if __name__ == "__main__":
create_structure()
populate_config()
| BWiebe1/openexcavator | openexcavator/database.py | database.py | py | 3,315 | python | en | code | 4 | github-code | 1 | [
{
"api_name": "sqlite3.connect",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "sqlite3.connect",
"line_number": 28,
"usage_type": "call"
},
{
"api_name": "sqlite3.connect",
"line_number": 42,
"usage_type": "call"
},
{
"api_name": "sqlite3.connect",
... |
30576627522 | import pygame
class Obstacle:
def __init__(self,x,y,width,height):
self.x = x
self.y = y
self.width = width
self.height = height
def collision(self,dot):
#Assume a class called dot with positions x and y
if (dot.pos.x > self.x) and (dot.pos.x < self.x + self.width) and (dot.pos.y > self.y) and (dot.pos.y < self.y + self.height):
return True
return False
def show(self,screen):
surface = pygame.Surface((self.width,self.height))
surface = surface.convert()
# pygame.draw.rect(surface, (233,43,56), pygame.Rect(30, 30, 60, 60))
surface.fill((233,43,56))
screen.blit(surface,(self.x,self.y)) | MoMus2000/Genetic-Algorithm | Obstacles.py | Obstacles.py | py | 624 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "pygame.Surface",
"line_number": 17,
"usage_type": "call"
}
] |
72101922274 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 28 13:35:15 2022
@author: andres
"""
#El procesamiento de la información fue realizado en python y las estimaciiones en R
#Librerias utilizadas para el preprocesamiento
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from sklearn.preprocessing import MinMaxScaler
#%%
#Variables
#Control
#En este parte se separar las variables según el uso que se les daran (Control, separacion e índices)
otras = { 'DIAREAL':'DIAREAL', 'MESREAL':'MESREAL', 'IDENPA':'IDENPA'}
control = {'Gobierno_Opocicion':'PERPART',
'Edad':'REEDAD', 'Educacion_Entrevistado': 'REEDUC.1',
'Educacion_padres': 'REEDUC.2', 'Nivel_Socioeconomico (Entrevistado)':'S26',
'Estudios_padres_2': 'S11', 'Estudio_entrevistado':'S10',
'Raza(Negro)': 'S6', 'Edad_2':'EDAD', 'SEXO':'SEXO', 'LUZ': 'P31NI',
'Clase_Sub': 'S1', 'Ocupación':'S14A', 'Ocupación activos':'S15',
'Estado_Civil':'S23', 'Beneficiario': 'S25', 'Migracion_Cambio_1_2a_0_1':'S16', 'ponde':'WT',
'Principal_ingreso':'S8'
}
extras = ['S21', 'S12'] # Bienes, redes sociales
#Gobierno
gobierno = {'Confianza_Fuerzas_Armadas':'P15STGBSC.A','Confianza_Policía':'P15STGBSC.B',
'Confianza_Iglesia':'P15STGBSC.C','Confianza_Congreso':'P15STGBSC.D',
'Confianza_Gobierno':'P15STGBSC.E','Confianza_Poder_Judicial':'P15STGBSC.F',
'Confianza_Partidos_Políticos':'P15STGBSC.G','Confianza_Electoral':'P15STGBSC.H',
'Confianza_Bancos':'P16NC.F',
'Aprobación_gobierno_presidente(nombre)':'P20STGBSC',
}
#Economia
economia = {'Situacion_Economica':'P6STGBSC', 'Situacion_Economia_Futura':'P8STIC',
'Confianza_interpersonal': 'P11STGBS', 'Satisfaccion_funcionamiento_economia':'P13STGBS.B',
'Integracion_politca_sino':'P39ST.B',
'Nac_menor_inter_mayor':'P52N.C'}
#%%
# En las partes de las funciones, se encuentran diferentes funcion que se basaron en la segmentacion
# para el pais, la fecha y el cambio en la denominacion de algúnas preguntas.
#Fuciones
def Transform_date(df):
df.reset_index(inplace =True, drop =True)
df['Fecha_lar'] = int()
for i in range(df.shape[0]):
day = df.at[i, 'DIAREAL']
mes = df.at[i, 'MESREAL']
año = 18
dte = '{}-{}-{}'.format(day, mes, año)
df.at[i, 'Fecha_lar'] = datetime.strptime(dte, '%d-%m-%y')
def PaisNum(df):
df['IDENPA_num'] = int()
for i in range(df.shape[0]):
if df.at[i, 'IDENPA'] == 170:
df.at[i, 'IDENPA_num'] = 1
elif df.at[i, 'IDENPA'] == 218:
df.at[i, 'IDENPA_num'] = 2
elif df.at[i, 'IDENPA'] == 862:
df.at[i, 'IDENPA_num'] = 3
elif df.at[i, 'IDENPA'] == 604:
df.at[i, 'IDENPA_num'] = 4
def FechaNum(dfx):
#Nueva estructura del codigo:
u = list(gobierno.values()) + list(economia.values()) + list(control.values())+list(otras.values())
dta = data[u]
Transform_date(dta)
valores = dta['Fecha_lar'].value_counts()
valores = valores.reset_index()
valores.sort_values('index',inplace =True)
valores = valores.reset_index(drop = True)
valores = valores.reset_index(drop = False)
dfx['Fecha_num'] = int()
for i in range(valores.shape[0]):
for j in range(dfx.shape[0]):
if dfx.at[j, 'Fecha_lar'] == valores.at[i, 'index']:
dfx.at[j,'Fecha_num'] = valores.at[i,'level_0']
def Dummy(df):
df['T_C'] = int()
df['B_A'] = int()
df['hombre'] = int()
df['mujer'] = int()
df['SEXO'].replace(2, 0, inplace= True)
df['Estrato'] = int()
df['S25'].replace(2,0, inplace =True)
fecha_importante = fecha_importante = '03-07-18'
p = datetime.strptime(fecha_importante, '%d-%m-%y')
for i in range(df.shape[0]):
if df.at[i, 'Fecha_lar'] >= p:
df.at[i, 'B_A'] = 1
else:
df.at[i, 'B_A'] = 0
if df.at[i, 'IDENPA_num'] == 1:
df.at[i, 'T_C'] = 1
else:
df.at[i, 'T_C'] = 0
if df.at[i,'SEXO'] == 1:
df.at[i, 'hombre'] = 1
df.at[i, 'mujer'] = 0
else:
df.at[i, 'hombre'] = 0
df.at[i, 'mujer'] = 1
if df.at[i, 'S1'] >3: #Esto depende de la variable que se utilice S1. Subjetiva S26 Contestada por el encuestados
df.at[i, 'Estrato'] = 1
else:
df.at[i, 'Estrato'] = 0
def Educ(df):
df['prima'] = np.where(df['REEDUC.1'] ==1,1, 0)
df['sec'] = np.where(df['REEDUC.1'] ==2,1, 0)
df['Sup'] = np.where(df['REEDUC.1'] ==3,1, 0)
def Nulos(df):
for i in df.columns:
print('Col: {} / Num Nan: {}'.format(i, df[i].isnull().sum()))
#%%
data = pd.read_csv('data_baro.csv')
#Segmentacion de los datos con las nuevas variables
nombres = list(control.keys()) + list(gobierno.keys()) + list(economia.keys()) + list(otras.keys())
#%%
#Con la finalidad de estimar el impacto utilizando las preguntas por separado,
#se realizaron una base de datos por pregunta. La segmentacion se evidencia en el
#bloque de codigo de abajo.
#Tener una base de datos por preguntas.
lista = []
cols = list(gobierno.values()) + list(economia.values()) + list(control.values())
for i in cols:
cols2 = np.append(np.array(list(otras.values())),i)
cols2 = cols2
d = pd.DataFrame(data[cols2])
d = d[(d.IDENPA == 218) | (d.IDENPA == 170) | (d.IDENPA == 604) | (d.IDENPA == 862)]
# scaler = MinMaxScaler().fit(pd.DataFrame(d[i]))
# d[i] = pd.DataFrame(scaler.transform(pd.DataFrame(d[i])), columns = [i])
for j in d.columns:
#Remplazar por pregunta
d[j] = d[j].replace([-1, -2, -3, -4], [None, None, None, None])
d.dropna(inplace =True, how = 'any')
d.reset_index(drop=True, inplace=True)
if i == 'SEXO' or i == 'P20STGBSC':
d[i].replace(2, 0, inplace= True)
if i not in np.array(list(control.values())):
d[i] = (d[i] - d[i].min()) / (d[i].max() - d[i].min())
Transform_date(d)
dt = d.groupby(['Fecha_lar', 'IDENPA']).mean()
dt = pd.DataFrame(dt[i])
lista.append(d)
for i in range(len(lista)):
if i >= 24:
break
if i == 0:
prueba = lista[0].merge(lista[1], how='left',left_index=True, right_index=True)
prueba = prueba.merge(lista[i+2], how='left',left_index=True, right_index=True)
prueba.reset_index(inplace = True)
FechaNum(prueba)
PaisNum(prueba)
Dummy(prueba)
prueba = prueba[(prueba.Fecha_num >=8) &(prueba.Fecha_num <=30)]
prueba.to_excel('Base_Datos_01042022.xlsx')
#%%
#Bloque donde se evidencia la base de datos por pregunta
lista = []
cols = list(gobierno.values()) + list(economia.values())
for i in cols:
cols2 = np.append(np.array(list(otras.values())+list(control.values())),i)
cols2 = cols2
d = pd.DataFrame(data[cols2])
d = d[(d.IDENPA == 170) | (d.IDENPA == 604)]
# scaler = MinMaxScaler().fit(pd.DataFrame(d[i]))
# d[i] = pd.DataFrame(scaler.transform(pd.DataFrame(d[i])), columns = [i])
for j in d.columns:
#Remplazar por pregunta
d[j] = d[j].replace([-1, -2, -3, -4], [None, None, None, None])
d.dropna(inplace =True, how = 'any')
d.reset_index(drop=True, inplace=True)
if i not in list(control.values()):
d[i] = (d[i] - d[i].min()) / (d[i].max() - d[i].min())
Transform_date(d)
PaisNum(d)
FechaNum(d)
p = datetime.strptime('03-07-18', '%d-%m-%y')
d = d[(d.Fecha_lar >= p - timedelta(days=4)) & (d.Fecha_lar <= p + timedelta(days=5))]
d.reset_index(drop=True, inplace =True)
Dummy(d)
d.to_excel('./Bases_Dif_n1/{}.xlsx'.format(i))
lista.append(d)
#%%
#Buscando realizar le balance de las medias, se creo una base de datos para
#estimar las medias de diferentes variables demograficas (Control) para
#todos los individuos de la muestra.
#Crear una base de datos unicamente para realizar la medicion de las medias
import math
medias = data[(data.IDENPA == 604) | (data.IDENPA == 170)]# |(data.IDENPA == 218) ]#data[(data.IDENPA == 218) | (data.IDENPA == 170) | (data.IDENPA == 604) | (data.IDENPA == 862)]
medias = medias[list(control.values())+list(otras.values())]
for j in medias.columns:
medias[j] = medias[j].replace([-1, -2, -3, -4], [None, None, None, None])
medias['Id'] = np.where(medias['IDENPA'] !=170, 'Control', 'Tratment')
medias['SEXO'].replace(2,0, inplace =True)
# medias['P31NI'] = np.log2(medias['P31NI'])
medias['S23'].replace([2,3], [0,0], inplace = True)
medias['S14A'].replace([2,3,4,5,6,7], [1,1,0,0,0,0], inplace =True)
medias['S25'].replace(2,0, inplace = True)
medias['S16'].replace([2], [0], inplace = True)
medias['S8'].replace(2,0, inplace = True)
Educ(medias)
medias.to_excel('Prueba_Medias.xlsx')
for i in medias.columns:
print('Col: {} / Num Nan: {}'.format(i, medias[i].isnull().sum()))
#%%
#Indice con las pregumtas que fueron significativas
#Utilizando las variables que obtuvieron una significancia estadistica,
#se realizaron los indices sin tener en cuenta variables de control
#Primero las de gobierno, y luego economia
preguntas = {'Aprobacion(.)': 'P20STGBSC' ,'Confianza_Partidos(**)':'P15STGBSC.G',
'Confianza_PoderJ(*)':'P15STGBSC.F', 'Confianza_FuerzasA(*)':'P15STGBSC.A'
#'Aprobacion(.)': 'P20STGBSC',
}
p_e= {'Situacion_eco_actual':'P6STGBSC', 'Situacion_futura':'P8STIC', 'Satisfaccion_Eco':'P13STGBS.B'}
def IndicePrep(dicc):
indice = data[(data.IDENPA == 604) | (data.IDENPA == 170)]
indice = indice[list(control.values())+list(otras.values())+list(dicc.values())]
for j in indice.columns:
#Remplazar por pregunta
if j in list(dicc.values()):
indice[j] = indice[j].replace([-1, -2, -3, -4], [None, None, None, None])
indice.dropna(inplace =True, how = 'any')
indice.reset_index(drop=True, inplace=True)
indice[j] = (indice[j] - indice[j].min()) / (indice[j].max() - indice[j].min())
return indice
indice_gov = IndicePrep(preguntas)
indice_gov['Gov'] = int()
indice_gov['Gov'] = (indice_gov['P20STGBSC']+ indice_gov['P15STGBSC.G']+ indice_gov['P15STGBSC.F']+ indice_gov['P15STGBSC.A'])/4
Transform_date(indice_gov)
FechaNum(indice_gov)
PaisNum(indice_gov)
Dummy(indice_gov)
Educ(indice_gov)
indice_gov = indice_gov[( indice_gov.Fecha_num>=15)&( indice_gov.Fecha_num<=26)]
indice_gov['Id'] = np.where(indice_gov['IDENPA'] !=170, 'Control', 'Tratment')
indice_gov['S23'].replace([2,3], [0,0], inplace = True)
indice_gov['S14A'].replace([2,3,4,5,6,7], [1,1,0,0,0,0], inplace =True)
indice_gov['S25'].replace(2,0, inplace = True)
indice_gov['S16'].replace([2], [0], inplace = True)
indice_gov['S8'].replace(2,0, inplace = True)
indice_gov.to_excel('indice_gov.xlsx')
indice_eco = IndicePrep(p_e)
indice_eco['Eco'] = (indice_eco['P6STGBSC']+ indice_eco['P8STIC']+ indice_eco['P13STGBS.B'])/3
Transform_date(indice_eco)
FechaNum(indice_eco)
PaisNum(indice_eco)
Dummy(indice_eco)
indice_eco= indice_eco[( indice_eco.Fecha_num>=15)&( indice_eco.Fecha_num<=26)]
indice_eco.to_excel('indice_eco.xlsx')
#%%
#Se realiza el mismo proceso de arriba pero teniendo en cuenta las variables de control
#Ahora una base de datos con los respectivos controles (Correr solo si se va a estimar la regresion con las variables de control)
control = {
'Nivel_Socioeconomico (Entrevistado)':'S26',
'Estudios_padres_2': 'S11', 'Estudio_entrevistado':'S10',
'Raza(Negro)': 'S6', 'Edad_2':'EDAD', 'SEXO':'SEXO',
'Clase_Sub': 'S1', 'Ocupación':'S14A',
'Estado_Civil':'S23', 'Edu_seg':'REEDUC.1', 'Beneficiario':'S25', 'Principal_Ingreso':'S8'
}
preguntas = {'Aprobacion(.)': 'P20STGBSC' ,'Confianza_Partidos(**)':'P15STGBSC.G',
'Confianza_PoderJ(*)':'P15STGBSC.F', 'Confianza_FuerzasA(*)':'P15STGBSC.A'
#'Aprobacion(.)': 'P20STGBSC',
}
p_e= {'Situacion_eco_actual':'P6STGBSC', 'Situacion_futura':'P8STIC', 'Satisfaccion_Eco':'P13STGBS.B'}
# bienes_col = {'Casa propia':'S21.A', 'Computador':'S21.B', 'Lavarropas':'S21.C', 'Teléfono Red Fija':'S21.E',
# 'Teléfono celular/móvil':'S21.F', 'Auto':'S21.G', 'Agua caliente':'S21.I', ' Alcantarillado/Cloacas':'S21.J',
# 'Al menos una comida caliente al día':'S21.K', 'Agua potable':'S21.L', ' Smartphone':'S21.M',
# 'Conexión a Internet en el hogar':'S21.N', 'Conexión a Internet en el hogar':'S21.O', 'Calefaccion':'S21.P'}
def IndicePrep(dicc):
indice = data[(data.IDENPA == 604) | (data.IDENPA == 170)]
indice = indice[list(control.values())+list(otras.values())+list(dicc.values())]
base = list(dicc.values()) + list(control.values())
for j in indice.columns:
#Remplazar por pregunta
if j in base:
indice[j] = indice[j].replace([-1, -2, -3, -4], [None, None, None, None])
indice.dropna(inplace =True, how = 'any')
indice.reset_index(drop=True, inplace=True)
if j in list(dicc.values()):
indice[j] = (indice[j] - indice[j].min()) / (indice[j].max() - indice[j].min())
indice['S23'].replace([2,3], [0,0], inplace = True)
indice['S14A'].replace([2,3,4,5,6,7], [1,1,0,0,0,0], inplace =True)
return indice
indice_gov = IndicePrep(preguntas)
indice_gov['Gov'] = int()
indice_gov['Gov'] = (indice_gov['P20STGBSC']+ indice_gov['P15STGBSC.G']+ indice_gov['P15STGBSC.F']+ indice_gov['P15STGBSC.A'])/4
Transform_date(indice_gov)
FechaNum(indice_gov)
PaisNum(indice_gov)
Dummy(indice_gov)
indice_gov = indice_gov[( indice_gov.Fecha_num>=16)&( indice_gov.Fecha_num<=26)]
Educ(indice_gov)
indice_gov.to_excel('indice_gov_co.xlsx')
indice_eco = IndicePrep(p_e)
indice_eco['Eco'] = (indice_eco['P6STGBSC']+ indice_eco['P8STIC']+ indice_eco['P13STGBS.B'])/3
Transform_date(indice_eco)
FechaNum(indice_eco)
PaisNum(indice_eco)
Dummy(indice_eco)
indice_eco= indice_eco[( indice_eco.Fecha_num>=16)&( indice_eco.Fecha_num<=26)]
Educ(indice_eco)
indice_eco.to_excel('indice_eco_co.xlsx')
# medias['S23'].replace([2,3], [0,0], inplace = True)
# medias['S14A'].replace([2,3,4,5,6,7], [1,1,0,0,0,0], inplace =True)
#%%
#En esta parte se obtienen la base de datos sin valores nulos.
preguntas = {'Aprobacion(.)': 'P20STGBSC' ,'Confianza_Partidos(**)':'P15STGBSC.G',
'Confianza_PoderJ(*)':'P15STGBSC.F', 'Confianza_FuerzasA(*)':'P15STGBSC.A'
#'Aprobacion(.)': 'P20STGBSC',
}
p_e= {'Situacion_eco_actual':'P6STGBSC', 'Situacion_futura':'P8STIC', 'Satisfaccion_Eco':'P13STGBS.B'}
def IndicePrep(dicc):
lista = []
indice = data[(data.IDENPA == 604) | (data.IDENPA == 170)]
indice = indice[list(control.values())+list(otras.values())+list(dicc.values())]
Transform_date(indice)
PaisNum(indice)
FechaNum(indice)
Dummy(indice)
pre = []
for j in indice.columns:
#Remplazar por pregunta
if j in list(dicc.values()):
indice[j] = indice[j].replace([-1, -2, -3, -4], [None, None, None, None])
# indice.dropna(inplace =True, how = 'any')
# indice.reset_index(drop=True, inplace=True)
indice[j] = (indice[j] - indice[j].min()) / (indice[j].max() - indice[j].min())
# u = pd.DataFrame(indice[[j,'Fecha_num', 'IDENPA_num', 'Fecha_lar', 'IDENPA']])
# p = datetime.strptime('03-07-18', '%d-%m-%y')
# u = u[(u.Fecha_lar >= p - timedelta(days=4)) & (u.Fecha_lar <= p + timedelta(days=5))]
# u['Pregunta'] = '{}'.format(j)
# u.reset_index(drop =True, inplace = True)
pre.append(j)
cul = pre + ['Fecha_num', 'T_C']
base = indice[cul]
return base
l = IndicePrep(p_e)
g = IndicePrep(preguntas)
l.to_excel('Economia.xlsx')
g.to_excel('Gobierno.xlsx')
#%%
#Paso extra donde queriamos ver la posibilidad de utilizar otras variables
#Base de datos de los bienes
bienes_col = {'Casa propia':'S21.A', 'Computador':'S21.B', 'Lavarropas':'S21.C', 'Teléfono Red Fija':'S21.E',
'Teléfono celular/móvil':'S21.F', 'Auto':'S21.G', 'Agua caliente':'S21.I', ' Alcantarillado/Cloacas':'S21.J',
'Al menos una comida caliente al día':'S21.K', 'Agua potable':'S21.L', ' Smartphone':'S21.M',
'Conexión a Internet en el hogar':'S21.N', 'Conexión a Internet en el hogar':'S21.O', 'Calefaccion':'S21.P'}
bienes = data[(data.IDENPA == 604) | (data.IDENPA == 170)]
bienes = bienes[bienes_col]
Nulos(bienes)
for j in bienes.columns:
bienes[j] = bienes[j].replace([-1, -2, -3, -4], [None, None, None, None])
bienes.dropna(inplace =True, how = 'any')
bienes.reset_index(drop=True, inplace=True)
bienes[j].replace(2,0, inplace =True)
#%%
#Agrupamos las medias de los valores por dia. Estos datos son utilizados para crear la grafica de tendencias paralelas.
colombia_gov = indice_gov[indice_gov.IDENPA == 170].groupby(['Fecha_lar']).mean()
peru_gov = indice_gov[indice_gov.IDENPA == 604].groupby(['Fecha_lar']).mean()
colombia_eco = indice_eco[indice_eco.IDENPA == 170].groupby(['Fecha_lar']).mean()
peru_eco = indice_eco[indice_eco.IDENPA == 604].groupby(['Fecha_lar']).mean()
colombia_gov.to_excel('col_gov.xlsx')
peru_gov.to_excel('per_gov.xlsx')
colombia_eco.to_excel('col_eco.xlsx')
peru_eco.to_excel('per_eco.xlsx')
#%%
| AOchoaArangoA/Public_Opinion | Preparacion_Datos_Grado.py | Preparacion_Datos_Grado.py | py | 17,665 | python | es | code | 0 | github-code | 1 | [
{
"api_name": "datetime.datetime.strptime",
"line_number": 60,
"usage_type": "call"
},
{
"api_name": "datetime.datetime",
"line_number": 60,
"usage_type": "name"
},
{
"api_name": "datetime.datetime.strptime",
"line_number": 100,
"usage_type": "call"
},
{
"api_name... |
31992094934 | import re
from typing import Optional, Tuple, Union
from snake.utils import format_number
def get_episode_tag(number: Union[int, str], leading_zeroes: int = 2) -> str:
return f"E{format_number(number, leading_zeroes=leading_zeroes)}"
def extract_episode_tag(filename: str, return_as_upper: bool = True) -> Tuple[Optional[str], Optional[str]]:
"""
Can match (case insentive:
```
s##e##
s###e###
s##e###
```
:param filename:
:param return_as_upper:
:return:
"""
filename = filename.lower()
matches = re.findall(r".*(s\d\d\de\d\d\d).*", filename)
if not matches:
matches = re.findall(r".*(s\d\de\d\d\d).*", filename)
if not matches:
matches = re.findall(r".*(s\d\de\d\d).*", filename)
if not matches:
return None, None
splitted_tag = matches[0].split("e")
season_tag = splitted_tag[0].upper() if return_as_upper else splitted_tag[0]
episode_tag = f"E{splitted_tag[1]}" if return_as_upper else f"e{splitted_tag[1]}"
return season_tag, episode_tag
def get_season_tag(number: Union[int, str], leading_zeroes: int = 2) -> str:
return f"S{format_number(number, leading_zeroes=leading_zeroes)}"
| ajutras/plexsnake | snake/utils/tv.py | tv.py | py | 1,213 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "typing.Union",
"line_number": 7,
"usage_type": "name"
},
{
"api_name": "snake.utils.format_number",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "re.findall",
"line_number": 27,
"usage_type": "call"
},
{
"api_name": "re.findall",
"lin... |
70862066275 | from .models import Comment, Post
from django import forms
from django.utils.text import slugify
from PIL import Image
import io
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('body', 'image')
widgets = {
'image': forms.FileInput(attrs={'class': 'btn, btn-sm'}),
}
labels = {
'body': 'Comment',
'image': 'Upload image'
}
def clean_image(self):
image = self.cleaned_data.get('image', False)
if image:
img = Image.open(image)
max_size = (800, 800) # Max size (width, height)
img.thumbnail(max_size, Image.LANCZOS)
img_io = io.BytesIO()
img_format = img.format if img.format else 'JPEG'
img.save(img_io, format=img_format, quality=60)
img_io.seek(0) # Reset file pointer to the beginning
image.name = 'resized_' + image.name # Change the image filename
# Update the image file to the resized image
image.file = img_io
return image
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'excerpt', 'content',
'featured_image',]
labels = {
'excerpt': 'Short Title',
}
def clean_title(self):
title = self.cleaned_data.get('title').capitalize()
slug = slugify(title)
unique_slug = slug
num = 1
while Post.objects.filter(slug=unique_slug).exists():
unique_slug = '{}-{}'.format(slug, num)
num += 1
self.cleaned_data['slug'] = unique_slug
return title
class ContactForm(forms.Form):
name = forms.CharField(
max_length=80,
required=True,
label='Full Name',
widget=forms.TextInput(attrs={
'placeholder': 'Ann Smith'
})
)
email = forms.EmailField(
required=True,
widget=forms.EmailInput(attrs={
'placeholder': 'ann.smith@gmail.com'
})
)
message = forms.CharField(
required=True,
widget=forms.Textarea(attrs={
'placeholder': 'What can we assist you with?'
})
)
| lukaszglowacz/norton-innovation-platform | blog/forms.py | forms.py | py | 2,244 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "django.forms.ModelForm",
"line_number": 8,
"usage_type": "attribute"
},
{
"api_name": "django.forms",
"line_number": 8,
"usage_type": "name"
},
{
"api_name": "models.Comment",
"line_number": 10,
"usage_type": "name"
},
{
"api_name": "django.forms.Fi... |
35826985836 | from django.urls import path
from events.apps import EventsConfig
from events import views
app_name = EventsConfig.name
urlpatterns = [
path('', views.EventListView.as_view(), name='list'),
path('create/', views.EventCreateView.as_view(), name='create'),
path('<int:pk>/', views.EventGetView.as_view(), name='get'),
path('update/<int:pk>/', views.EventUpdateView.as_view(), name='update'),
path('delete/<int:pk>/', views.EventDeleteView.as_view(), name='delete'),
path('register-attendee/', views.EventAttendeeRegisterView.as_view(), name='register-attendee'),
path('unregister-attendee/<int:pk>/', views.EventAttendeeUnregisterView.as_view(), name='unregister-attendee'),
]
| raymanzarek1984/tikoExercise | events/urls.py | urls.py | py | 706 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "events.apps.EventsConfig.name",
"line_number": 6,
"usage_type": "attribute"
},
{
"api_name": "events.apps.EventsConfig",
"line_number": 6,
"usage_type": "name"
},
{
"api_name": "django.urls.path",
"line_number": 9,
"usage_type": "call"
},
{
"api_nam... |
8885931053 | """
A module with auxiliary functions for working with all around numbers
"""
import itertools
import math
from collections import deque
from pzeug.number.prime import sieve_of_eratosthenes
def reverse(n):
reversed_n = 0
while n > 0:
reversed_n = 10 * reversed_n + (n % 10)
n //= 10
return reversed_n
def is_palindrome(number):
return number == reverse(number)
def digits_in_number(number):
while number:
yield number % 10
number //= 10
def digits_to_number(digits):
number = 0
for i, d in enumerate(reversed(digits)):
number += d * 10 ** i
return number
def combinations(n):
for digits in set(itertools.permutations(digits_in_number(n))):
degree = len(digits) - 1
digit_sum = 0
for digit in digits:
digit_sum += digit * 10 ** degree
degree -= 1
yield digit_sum
def circulars(digits):
digits = deque(digits)
length = len(digits)
for i in range(1, length):
digits.rotate(1)
degree = 0
digit_sum = 0
for digit in digits:
digit_sum += digit * 10 ** degree
degree += 1
yield digit_sum
# def prim_root(n):
# totient = tot(n)
# roots = []
# exp = len(totient)
# for x in totient:
# y = 1
# while pow(x, y, n) != 1:
# y += 1
# if y == exp:
# roots.append(x)
# return roots
#
#
# def colliatz_len(n, prev_len=0):
# if n == 1:
# return prev_len + 1
# if n in len_hash:
# return prev_len + len_hash[n]
#
# return colliatz_len(n // 2 if n % 2 == 0 else 3 * n + 1, prev_len + 1)
def colliatz_sequence(n):
yield n
if n != 1:
yield from colliatz_sequence(n // 2 if n % 2 == 0 else 3 * n + 1)
def gcd(a: int, b: int) -> int:
"""Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b:
a, b = b, a % b
return a
def lcm(a: int, b: int) -> int:
"""Calculate Least Common Multiple using Greatest Common Divisor function.
Examples:
>>> lcm(12,20)
60
"""
return a * b // gcd(a, b)
def largest_palindrome(min_factor, max_factor):
"""Find largest palindrome given range of factors [min_factor, max_factor]
Consider the digits of P – let them be x, y and z.
P must be at least 6 digits long since the palindrome 111111 = 143×777 – the product of two 3-digit integers.
Since P is palindromic:
P=100000x10000y1000z100z10yx
P=100001x10010y1100z
P=119091x910y100z
Since 11 is prime, at least one of the integers a or b must have a factor of 11.
So if a is not divisible by 11 then we know b must be. Using this information
we can determine what values of b we check depending on a.
"""
max_palindrome = 0
max_a = 0
max_b = 0
for a in range(max_factor, min_factor - 1, -1):
if a % 11 == 0:
b = max_factor
b_step = -1
else:
b = max_factor - max_factor % 11
b_step = -11
for k in range(b, a - 1, b_step):
multiplication = a * k
if multiplication <= max_palindrome:
break
if is_palindrome(multiplication):
max_palindrome = a * k
max_a = a
max_b = k
return max_palindrome, max_a, max_b
def smallest_num_divisible_by_each_to(k):
"""Calculate smallest number that can be divided by each of the numbers from 1 to k without any remainder.
"""
check_limit = int(math.sqrt(k))
result = 1
for prime in sieve_of_eratosthenes(k):
if prime > check_limit:
result *= prime
else:
degree = int(math.log10(k) / math.log10(prime))
result *= (prime ** degree)
return result
if __name__ == "__main__":
import doctest
doctest.testmod()
# import inspect
# import sys
# current_module = sys.modules[__name__]
# print(inspect.getsource(current_module))
import fractions
print(gcd(27, 54))
print(lcm(3, 7))
print(fractions.Fraction(27, 54) / gcd(27, 54))
| inteldict/pzeug | number/number.py | number.py | py | 4,389 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "itertools.permutations",
"line_number": 39,
"usage_type": "call"
},
{
"api_name": "collections.deque",
"line_number": 49,
"usage_type": "call"
},
{
"api_name": "math.sqrt",
"line_number": 147,
"usage_type": "call"
},
{
"api_name": "pzeug.number.prim... |
2657548095 | #!/usr/bin/env python3
import requests
import spacy
url = "https://query.wikidata.org/sparql"
url_api = "https://www.wikidata.org/w/api.php"
params_entity = {'action': 'wbsearchentities', 'language': 'en', 'format': 'json'}
params_prop = {'action': 'wbsearchentities', 'language': 'en', 'format': 'json', 'type': 'property'}
nlp = spacy.load("en_core_web_sm")
def find_matches_ent(string):
params_entity['search'] = string
json = requests.get(url_api, params_entity).json()
entities = []
for result in json['search']:
# print("{}\t{}\t{}".format(result['id'], result['label'], result['description']))
entities.append(result['id'])
return entities
def make_query(property, entity):
answers = []
query = '''
SELECT ?answerLabel WHERE {
wd:''' + entity + ''' wdt:''' + property + ''' ?answer.
SERVICE wikibase:label {
bd:serviceParam wikibase:language "en" .
}
}'''
data = requests.get(url, params={'query': query, 'format': 'json'}).json()
for item in data['results']['bindings']:
for var in item:
answers.append(item[var]['value'])
if len(answers) == 0:
return None
else:
return answers
def find_answer(properties, entities):
if not entities or not properties:
return None
ans = None
for entity in entities:
for property in properties:
ans = make_query(property, entity)
if ans is not None:
return ans
return ans
def find_answer(properties, entities):
ans = None
for entity in entities:
for property in properties:
ans = make_query(property, entity)
if ans is not None:
return ans
return ans
# What is the X of Y?
def create_and_fire_queryDueto(line):
line = nlp(line.rstrip()) # removes newline
subject = []
property = []
flag = 0
group = []
for token in line:
# print(token.text, token.lemma_, token.dep_, token.head.lemma_)
if token.dep_ == "ROOT" or token.dep_ == "pcomp":
property.append(token.lemma_)
if token.dep_ == "nsubj" or (token.dep_ == "compound" and token.head.dep_ == "nsubj"):
subject.append(token.lemma_)
prop = str(' '.join(property))
ent = str(' '.join(subject))
properties = ['P509']
entities = find_matches_ent(ent)
if len(entities) == 0 or len(properties) == 0:
return 0
answer = find_answer(properties, entities)
if answer is None:
return 0
else:
print("\t",'\t'.join(answer))
return 1
| Liya7979/LanguageTechnologyProject | Dueto.py | Dueto.py | py | 2,700 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "spacy.load",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "requests.get",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "requests.get",
"line_number": 32,
"usage_type": "call"
}
] |
5934931034 | from fastapi import APIRouter, status, Depends
from fastapi.responses import JSONResponse
from sqlalchemy.orm import Session
from slugify import slugify
from schemas import BlogRequest
from schemas import BlogOut
from models import Blog
from database import db_dependency
blog_router = APIRouter(prefix='/blog', tags=['blog'])
@blog_router.get('/list')
def list(db: Session = Depends(db_dependency)):
return db.query(Blog).all()
@blog_router.post('/store')
def store(request: BlogRequest, db: Session = Depends(db_dependency)):
try:
new_blog = Blog(
name=request.name,
description=request.description,
is_active=request.is_active,
slug=slugify(request.name),
category_id=request.category_id
)
db.add(new_blog)
db.commit()
return {'message': 'successfully'}
except:
return JSONResponse(status_code=status.HTTP_201_CREATED, content={"message": 'fail'})
@blog_router.get('/show/{blog_id}', response_model=BlogOut)
def show(blog_id: int, db: Session = Depends(db_dependency)):
blog = db.query(Blog).filter(Blog.id == blog_id).first()
if blog is not None:
return blog
else:
return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content={"message": 'fail'})
@blog_router.get('/edit/{id}')
def edit(id: int, db: Session = Depends(db_dependency)):
blog = db.query(Blog).filter(Blog.id == id).first()
if blog is not None:
return {"message": 'edit', 'data': blog}
else:
return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content={"message": 'fail'})
@blog_router.put('/update/{blog_id}')
def update(blog_id: int, request: BlogRequest, db: Session = Depends(db_dependency)):
blog = db.query(Blog).filter(Blog.id == blog_id).first()
if blog is not None:
blog.name = request.name
blog.description = request.description
blog.is_active = request.is_active
blog.category_id = request.category_id
blog.slug = slugify(request.name)
db.commit()
return {'message': 'successfully'}
else:
return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content={"message": 'fail'})
@blog_router.delete('/delete/{blog_id}')
def delete(blog_id: int, db: Session = Depends(db_dependency)):
blog = db.query(Blog).filter(Blog.id == blog_id).first()
if blog is not None:
db.delete(blog)
db.commit()
return {'message': 'Blog delete'}
else:
return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content={"message": 'fail'})
| slvler/fast-api | routers/blog.py | blog.py | py | 2,618 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "fastapi.APIRouter",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "sqlalchemy.orm.Session",
"line_number": 16,
"usage_type": "name"
},
{
"api_name": "fastapi.Depends",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "database.db_... |
19751365526 | import csv
from dataclasses import dataclass
from typing import List
# def load_sales(sales_path='./sales.csv'):
# sales = []
# with open(sales_path, encoding='utf-8') as f:
# for sale in csv.DictReader(f):
# # 値の変換
# try:
# sale['price'] = int(sale['price'])
# sale['amount'] = int(sale['amount'])
# except (ValueError, TypeError, KeyError):
# continue
# # 値のチェック
# if sale['price'] <= 0:
# continue
# if sale['amount'] <= 0:
# continue
# # 売上の計算
# sum_price = 0
# for sale in sales:
# sum_price += sale['amount'] * sale['price']
# return sum_price, sales
# 売上(CSVの各行)を表すクラスに分離する
@dataclass
class Sale:
id: int
item_id: int
amount: int
price: int
def validate(self):
if self.price <= 0:
raise ValueError('Invalid sale.price')
if self.amount <= 0:
raise ValueError('Invalid sale.amount')
# 各売上の料金を計算する処理をSalesに実装
# property:値を簡単に変更できない
# @property
def price(self):
return self.amount * self.price
@dataclass
class Sales:
data: List[Sale]
@property
def price(self):
return sum(sale.price for sale in self.data)
@classmethod
def from_assert(cls, path='./sales.csv'):
data = []
with open(path, encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
try:
sale = Sale(**row)
sale.id = int(sale.id)
sale.item_id = int(sale.item_id)
sale.amount = int(sale.amount)
sale.price = int(sale.price)
sale.validate()
except Exception as e:
print(e)
continue
data.append(sale)
return cls(data=data) | yoshikikasama/python | best_practice/code_implementation/unittest/case2/sales.py | sales.py | py | 2,084 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "dataclasses.dataclass",
"line_number": 28,
"usage_type": "name"
},
{
"api_name": "typing.List",
"line_number": 50,
"usage_type": "name"
},
{
"api_name": "csv.DictReader",
"line_number": 60,
"usage_type": "call"
},
{
"api_name": "dataclasses.dataclas... |
39011959286 | # -*- coding: utf-8 -*-
"""
Created on Thr Jan 10 09:13:24 2018
@author: takata@innovotion.co.jp
@author: harada@keigan.co.jp
"""
import argparse
import sys
import os
import pathlib
from time import sleep
current_dir = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(current_dir) + '/../') # give 1st priority to the directory where pykeigan exists
from pykeigan import usbcontroller
from pykeigan import utils
parser = argparse.ArgumentParser(description='モーター動作 トルク制御')
parser.add_argument('port',metavar='PORT',default='/dev/ttyUSB0',nargs='?',help='モーターのデバイスファイル指定 (default:/dev/ttyUSB0)')
args = parser.parse_args()
os.system('clear')
for i in range(6):
print(" ")
print("\033[5;1H","---------------------------------------")
sys.stdout.flush()
"""
----------------------
モーター接続し、各種情報の取得
----------------------
"""
torque=0
position=0
##ログ情報callback
def on_motor_log_cb(log):
if log['error_codes']!='KM_SUCCESS':
print('log {} '.format(log))
#接続
dev=usbcontroller.USBController(args.port,False)
dev.on_motor_log_cb=on_motor_log_cb
"""
----------------------
モーター動作 トルク制御
----------------------
モーターを手で回して行くとトルクが加算され、重くなる。45度毎で0.025N*m増加
"""
torque_level=0
##トルクを監視し45度毎にトルクを増加
def on_motor_measurement_cb(measurement):
global torque_level
torque=measurement['torque']
position=measurement['position']
now_torque_level=round(utils.rad2deg(position)/45)*0.025
if torque_level!=now_torque_level:
torque_level=now_torque_level
dev.set_max_torque(abs(torque_level))
print('\033[4;1H\033[2K','torque/max_torque:{0:.2f}/{1:.2f}'.format(torque,torque_level))
sys.stdout.flush()
def stop_torque_control_like_closing_cap():
if dev:
dev.on_motor_measurement_value_cb=None
dev.disable_action()
dev.set_max_torque(10.0)
def start_torque_control_like_closing_cap():
global torque_level
print('\033[2;1H\033[2K', 'Please try to turn the motor by hand.')
sys.stdout.flush()
dev.disable_action()
dev.preset_position(0)
sleep(0.2)
dev.enable_action()
dev.move_to_pos(0,utils.rpm2rad_per_sec(10))
torque_level=10
dev.on_motor_measurement_value_cb = on_motor_measurement_cb
"""
Exit with key input
"""
sleep(0.5)
while True:
print('\033[6;1H\033[2K')
sys.stdout.flush()
if sys.version_info<(3,0):
inp = raw_input('Command input > Start:[s] Reset:[r] Exit:[Other key] >>')
else:
inp = input('Command input > Start:[s] Reset:[r] Exit:[Other key] >>')
if inp == 's':
start_torque_control_like_closing_cap()
elif inp == 'r':
stop_torque_control_like_closing_cap()
elif inp !=None:
print()
dev.set_led(1, 100, 100, 100)
dev.disable_action()
dev.set_max_torque(10.0)
sleep(0.2)
dev.disconnect()
break
| keigan-motor/pykeigan_motor | examples/usb-torque-control.py | usb-torque-control.py | py | 3,090 | python | en | code | 10 | github-code | 1 | [
{
"api_name": "pathlib.Path",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "sys.path.insert",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "sys.path",
"line_number": 15,
"usage_type": "attribute"
},
{
"api_name": "argparse.ArgumentParser",
... |
22941199712 | import logging
import os
import time
from concurrent.futures import ThreadPoolExecutor
from dicomweb_client import DICOMwebClient
from pydicom.dataset import Dataset
from pydicom.filereader import dcmread
from monailabel.utils.others.generic import md5_digest, run_command
logger = logging.getLogger(__name__)
def generate_key(patient_id: str, study_id: str, series_id: str):
return md5_digest(f"{patient_id}+{study_id}+{series_id}")
def get_scu(query, output_dir, query_level="SERIES", host="127.0.0.1", port="4242", aet="MONAILABEL"):
start = time.time()
field = "StudyInstanceUID" if query_level == "STUDIES" else "SeriesInstanceUID"
run_command(
"python",
[
"-m",
"pynetdicom",
"getscu",
host,
port,
"-P",
"-k",
f"0008,0052={query_level}",
"-k",
f"{field}={query}",
"-aet",
aet,
"-q",
"-od",
output_dir,
],
)
logger.info(f"Time to run GET-SCU: {time.time() - start} (sec)")
def store_scu(input_file, host="127.0.0.1", port="4242", aet="MONAILABEL"):
start = time.time()
input_files = input_file if isinstance(input_file, list) else [input_file]
for i in input_files:
run_command("python", ["-m", "pynetdicom", "storescu", host, port, "-aet", aet, i])
logger.info(f"Time to run STORE-SCU: {time.time() - start} (sec)")
def dicom_web_download_series(study_id, series_id, save_dir, client: DICOMwebClient, frame_fetch=False):
start = time.time()
# Limitation for DICOMWeb Client as it needs StudyInstanceUID to fetch series
if not study_id:
meta = Dataset.from_json(
[
series
for series in client.search_for_series(search_filters={"SeriesInstanceUID": series_id})
if series["0020000E"]["Value"] == [series_id]
][0]
)
study_id = str(meta["StudyInstanceUID"].value)
os.makedirs(save_dir, exist_ok=True)
if not frame_fetch:
instances = client.retrieve_series(study_id, series_id)
for instance in instances:
instance_id = str(instance["SOPInstanceUID"].value)
file_name = os.path.join(save_dir, f"{instance_id}.dcm")
instance.save_as(file_name)
else:
# TODO:: This logic (combining meta+pixeldata) needs improvement
def save_from_frame(m):
d = Dataset.from_json(m)
instance_id = str(d["SOPInstanceUID"].value)
# Hack to merge Info + RawData
d.is_little_endian = True
d.is_implicit_VR = True
d.PixelData = client.retrieve_instance_frames(
study_instance_uid=study_id,
series_instance_uid=series_id,
sop_instance_uid=instance_id,
frame_numbers=[1],
)[0]
file_name = os.path.join(save_dir, f"{instance_id}.dcm")
logger.info(f"++ Saved {os.path.basename(file_name)}")
d.save_as(file_name)
meta_list = client.retrieve_series_metadata(study_id, series_id)
logger.info(f"++ Saving DCM into: {save_dir}")
with ThreadPoolExecutor(max_workers=2, thread_name_prefix="DICOMFetch") as executor:
executor.map(save_from_frame, meta_list)
logger.info(f"Time to download: {time.time() - start} (sec)")
def dicom_web_upload_dcm(input_file, client: DICOMwebClient):
start = time.time()
dataset = dcmread(input_file)
result = client.store_instances([dataset])
url = ""
for elm in result.iterall():
s = str(elm.value)
logger.info(f"{s}")
if "/series/" in s:
url = s
break
series_id = url.split("/series/")[1].split("/")[0] if url else ""
logger.info(f"Series Instance UID: {series_id}")
logger.info(f"Time to upload: {time.time() - start} (sec)")
return series_id
if __name__ == "__main__":
import shutil
from monailabel.datastore.dicom import DICOMwebClientX
client = DICOMwebClientX(
url="https://d1l7y4hjkxnyal.cloudfront.net",
session=None,
qido_url_prefix="output",
wado_url_prefix="output",
stow_url_prefix="output",
)
study_id = "1.2.840.113654.2.55.68425808326883186792123057288612355322"
series_id = "1.2.840.113654.2.55.257926562693607663865369179341285235858"
save_dir = "/local/sachi/Data/dicom"
shutil.rmtree(save_dir, ignore_errors=True)
os.makedirs(save_dir, exist_ok=True)
dicom_web_download_series(study_id, series_id, save_dir, client, True)
| Project-MONAI/MONAILabel | monailabel/datastore/utils/dicom.py | dicom.py | py | 4,693 | python | en | code | 472 | github-code | 1 | [
{
"api_name": "logging.getLogger",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "monailabel.utils.others.generic.md5_digest",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "time.time",
"line_number": 20,
"usage_type": "call"
},
{
"api_name":... |
70983117153 | from django.http import JsonResponse
class InvalidToken(BaseException):
def __init__(self, message='Invalid token', code=401):
self.message = message
self.code = code
super().__init__(self.message)
def handleError(self):
response = {
'result': False,
'status': {
'code': 401,
'message': 'Authentication error'
},
'body': {
'error': 'Token is invalid or expired'
}
}
return JsonResponse(response, status=401) | tranlong58/django_mysql_project | tts/exceptions/InvalidToken.py | InvalidToken.py | py | 579 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "django.http.JsonResponse",
"line_number": 22,
"usage_type": "call"
}
] |
71015635875 | # Self Number
# https://www.acmicpc.net/problem/4673
from functools import reduce
numbers = list(range(1, 10001))
def d(n):
return n + reduce(lambda x, y: x + y, list(map(int, list(str(n)))))
for i in numbers:
if i != 0:
next = d(i)
# numbers.remove(1)
while True:
if next > 10000:
break
numbers[next-1] = 0
next = d(next)
for i in numbers:
if i != 0:
print(i)
| yskang/AlgorithmPractice | baekjoon/python/selfNumber.py | selfNumber.py | py | 487 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "functools.reduce",
"line_number": 9,
"usage_type": "call"
}
] |
38592569457 | import sys
import os
from urllib.request import urlretrieve
from zipfile import ZipFile
if not os.path.isdir('../data'):
os.mkdir('../data')
def reporthook(blocknum, blocksize, totalsize):
bytesread = blocknum * blocksize
if totalsize > 0:
percent = bytesread * 1e2 / totalsize
s = "\r%5.1f%% (%*d / %d bytes)" % (percent, len(str(totalsize)), bytesread, totalsize)
sys.stderr.write(s)
if bytesread >= totalsize:
sys.stderr.write("\n")
else:
sys.stderr.write("read %d\n" % (bytesread,))
def download_zip(url, filename, description):
print("Downloading " + description + " from " + url)
urlretrieve(url, filename, reporthook)
print("Download finished")
print("Extracting")
zip = ZipFile(filename, 'r')
zip.extractall("../data/")
zip.close()
os.remove(filename)
download_zip('https://github.com/KhronosGroup/glTF-Sample-Models/archive/refs/heads/master.zip', '../data/gltf-sample-models.zip', "sample gltf models")
download_zip('https://github.com/KhronosGroup/glTF-Sample-Environments/archive/refs/heads/master.zip', '../data/gltf-sample-environments.zip', "sample environments")
download_zip('https://github.com/hoffstadt/pilotlight-assets/archive/refs/heads/master.zip', '../data/pilotlight-assets.zip', "test assets") | hoffstadt/pilotlight | scripts/download_assets.py | download_assets.py | py | 1,329 | python | en | code | 67 | github-code | 1 | [
{
"api_name": "os.path.isdir",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 6,
"usage_type": "attribute"
},
{
"api_name": "os.mkdir",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "sys.stderr.write",
"line_number"... |
4945479177 | from django.contrib import admin
from django.urls import path
from .views import TopView, ClothingDetail, ClothingRegister, ClothingDelete, ClothingUpdate, ClothingList, signupfunc, loginfunc, logoutfunc, form, forecast
urlpatterns = [
path('signup/', signupfunc, name='signup'),
path('login/', loginfunc, name='login'),
path('logout/', logoutfunc, name='logout'),
path('top/', TopView.as_view(), name='top'),
path('ClothingDetail/<int:pk>', ClothingDetail.as_view(), name='ClothingDetail'),
path('ClothingRegister/', ClothingRegister.as_view(), name='ClothingRegister'),
path('ClothingDelete/<int:pk>', ClothingDelete.as_view(), name='ClothingDelete'),
path('ClothingUpdate/<int:pk>', ClothingUpdate.as_view(), name='ClothingUpdate'),
path('Clothinglist/', ClothingList.as_view(), name='ClothingList'),
path('signup/', signupfunc, name='signup'),
path('', forecast, name='weather'),
path('form', form, name='form')
]
| kibachi02/morningleader | morning/urls.py | urls.py | py | 968 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "django.urls.path",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "views.signupfunc",
"line_number": 7,
"usage_type": "argument"
},
{
"api_name": "django.urls.path",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "views.loginfunc",... |
2736655443 | '''
https://www.codewars.com/kata/54d7660d2daf68c619000d95/python
'''
import math
import functools
def convert_fracts(lst):
lcm = lambda a, b : abs(a*b) // math.gcd(a, b)
tmp_list = list(map(lambda x : x[1] ,list(lst)))
lcm_num = functools.reduce(lcm,tmp_list)
return list(map(lambda x : [x[0] * lcm_num // x[1], lcm_num] , list(lst)))
'''
import math
def convert_fracts(lst):
b = []
if lst == b: return b
greater = max([l[1] for l in lst if l[1]])
greater2 = max([l[1] if l[1] != greater else 0 for l in lst if l[1]])
greater3 = max([l[1] if l[1] != greater and greater2 else 0 for l in lst if l[1]])
lcm = greater*greater2 // math.gcd(greater2 ,greater)
if lcm%greater3 != 0: lcm = lcm*greater3 // math.gcd(greater3 ,lcm)
for l in lst:
l[0]=int(l[0]*lcm/l[1])
l[1]=int(l[1]*lcm/l[1])
b.append(l)
return b
'''
'''
def convert_fracts(lst):
b = []
if lst == b: return b
greater = max([l[1] for l in lst if l[1]])
#print(greater)
while True:
if greater%lst[0][1] == 0 and greater%lst[1][1] == 0 and greater%lst[2][1] == 0:
for l in lst:
l[0]=int(l[0]*greater/l[1])
l[1]=int(l[1]*greater/l[1])
b.append(l)
return b
greater += 1
'''
'''
if lst[0][1] > lst[1][1]: greater = lst[0][1]
elif lst[0][1] > lst[2][1]: greater = lst[0][1]
elif lst[1][1] > lst[0][1]: greater = lst[1][1]
elif lst[1][1] > lst[2][1]: greater = lst[1][1]
elif lst[2][1] > lst[0][1]: greater = lst[2][1]
elif lst[2][1] > lst[1][1]: greater = lst[2][1]
'''
'''
def convert_fracts(lst):
content = []
for i in range(100000000000000000):
if i:
n = 0
for lst_from_lst in lst:
if i%lst_from_lst[1] == 0:
n += 1
if n == len(lst):
for l in lst:
l[0]=int(l[0]*i/l[1])
l[1]=int(l[1]*i/l[1])
content.append(l)
return content
'''
a = [[1, 2], [1, 3], [1, 4]]
print(convert_fracts(a))
| SzybkiRabarbar/CodeWars | 2022-03/2022-03-22Common Denominators.py | 2022-03-22Common Denominators.py | py | 2,125 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "math.gcd",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "functools.reduce",
"line_number": 10,
"usage_type": "call"
}
] |
30262927884 | import random
from logging import getLogger
import torch
logger = getLogger(__name__)
def set_seed(seed: int = 0) -> None:
# set seed
random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
logger.info("Finished setting up seed.")
| yiskw713/pytorch_template | src/libs/seed.py | seed.py | py | 321 | python | en | code | 22 | github-code | 1 | [
{
"api_name": "logging.getLogger",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "random.seed",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "torch.manual_seed",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "torch.cuda.manual_seed... |
21763797469 | import streamlit as st
# Function predicts house prices using the regression pipeline
#Credit to Ulrike Riemenschneider for providing the format for this
# page - link to repo at https://github.com/URiem/heritage-housing-PP5
def predict_price(X_live, features, sale_price_pipeline):
# from live data, subset features related to this pipeline
# the features are filtered using the list of features from the pipeline
# this is to avoid a scilent fail in case the input features
# are not in the same order as in the dataset used to train the model.
X_live_sale_price = X_live.filter(features)
# predict
price_prediction = sale_price_pipeline.predict(X_live_sale_price)
statement = (
f"* Given the features provided for the property, the model has "
f" predicted a sale value of:"
)
# Format the value written to the page
# Formatting taken from
# https://github.com/t-hullis/milestone-project-heritage-housing-issues/tree/main
if len(price_prediction) == 1:
price = float(price_prediction.round(1))
price = '${:,.2f}'.format(price)
st.write(statement)
st.write(f"**{price}**")
else:
st.write(
f"* Given the features provided for the inherited properties, "
f" the model has predicted sale values of:")
st.write(price_prediction)
return price_prediction
| sonetto104/CI-PP5-Peter-Regan-Heritage-Housing-Project | src/machine_learning/predictive_analysis_ui.py | predictive_analysis_ui.py | py | 1,409 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "streamlit.write",
"line_number": 31,
"usage_type": "call"
},
{
"api_name": "streamlit.write",
"line_number": 32,
"usage_type": "call"
},
{
"api_name": "streamlit.write",
"line_number": 34,
"usage_type": "call"
},
{
"api_name": "streamlit.write",
... |
9450769007 | from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.bash import BashOperator
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2023, 5, 6),
'retries': 0
}
dag = DAG(
'workSample_bash',
default_args=default_args,
description='A simple DAG to run 3 Python scripts in sequence',
schedule_interval="0 * * * *",
)
t1 = BashOperator(
task_id='raw_data_process',
bash_command='python app/raw_data_process.py',
dag=dag,
)
t2 = BashOperator(
task_id='feature_engineer',
bash_command='python app/feature_engineer.py',
dag=dag,
)
t3 = BashOperator(
task_id='model_training',
bash_command='python app/model_training.py',
dag=dag,
)
t1 >> t2 >> t3
| yyk722/riskThinkingWorkSample | airflow/dags/worksample_bash.py | worksample_bash.py | py | 781 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "datetime.datetime",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "airflow.DAG",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "airflow.operators.bash.BashOperator",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "airf... |
75140687072 | import sys
import time
import pyotp
import pyperclip
def run(token: str ='', _continue: bool=False):
if token == '':
with open('secret', 'r') as fin:
token = fin.read().splitlines()[0]
totp = pyotp.TOTP(token)
if _continue:
print('This program will continue copy totp code to clipboard,\npress Control+C to terminate is program.\n')
betk = tk = totp.now()
print(tk)
pyperclip.copy(tk)
while _continue:
try:
time.sleep(5)
except KeyboardInterrupt:
pyperclip.copy('')
break
tk = totp.now()
if tk == betk:
continue
pyperclip.copy(tk)
print(tk)
betk = tk
if __name__ == "__main__":
if len(sys.argv) == 1:
run()
elif len(sys.argv) == 2:
if sys.argv[1] == '-t':
run(_continue=True)
else:
run(sys.argv[1])
else:
run(sys.argv[1], '-t' in sys.argv)
| KunoiSayami/simple-totp-paste | totp.py | totp.py | py | 803 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "pyotp.TOTP",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "pyperclip.copy",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "time.sleep",
"line_number": 22,
"usage_type": "call"
},
{
"api_name": "pyperclip.copy",
"line_numbe... |
30405538314 | # 84. Largest Rectangle in Histogram
# Hard
# Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.
# Input: heights = [2,1,5,6,2,3]
# Output: 10
# Explanation: The above is a histogram where width of each bar is 1.
# The largest rectangle is shown in the red area, which has an area = 10 units.
from typing import List
def largest(arr: List[int]) -> int:
stack = []
area = 0
for i, h in enumerate(arr):
start = i
while stack and stack[-1][1] > h:
index, last_bar_height = stack.pop()
area = max(area, ((i - index) * last_bar_height))
start = index
stack.append((start, h))
for i, h in stack:
area = max(area, h * (len(arr) - i))
return area
def test():
heights = [2,1,5,6,2,3]
assert largest(heights) == 10
def test2():
heights = [2, 4]
assert largest(heights) == 4
def test3():
heights = [1, 1]
assert largest(heights) == 2
| akarsh1995/advent-of-code | src/leetcode/lc_84.py | lc_84.py | py | 1,064 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "typing.List",
"line_number": 13,
"usage_type": "name"
}
] |
41129675056 | # -*- coding: utf-8 -*-
import scrapy
from jiandan.items import JiandanItem
class ArticleSpider(scrapy.Spider):
name = 'article'
allowed_domain = 'i.jandan.net'
start_urls = ['http://i.jandan.net/']
def parse(self, response):
url_list = response.xpath("//h2[@class='thetitle']/a/@href").extract()
for url in url_list:
yield scrapy.Request(url, callback=self.parse_detail)
next_url = response.xpath("//div[@class='wp-pagenavi']/a[last()]/@href").extract_first()
if next_url is not None:
next_url = response.urljoin(next_url)
yield scrapy.Request(next_url, callback=self.parse)
def parse_detail(self, response):
item = JiandanItem()
item["title"] = response.xpath("//h1[@class='thetitle']/a/text()").extract_first()
item["name"] = response.xpath("//div[@class='postinfo']/text()").extract()[-1].split("@")[0].strip()
item["date"] = response.xpath("//div[@class='postinfo']/text()").extract()[-1].split("@")[1].strip()
item["content"] = ''.join(response.xpath("//div[@class='entry']/p/text()").extract()).replace("\n", "").strip()
if '无聊图' in item["title"]:
item["content"] = ';'.join(response.xpath("//div[@class='entry']/p/img/@data-original").extract())
print(item)
yield item
| xxllea/Spider-Work | jiandan/jiandan/spiders/article.py | article.py | py | 1,352 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "scrapy.Spider",
"line_number": 6,
"usage_type": "attribute"
},
{
"api_name": "scrapy.Request",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "scrapy.Request",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "jiandan.items.Jiandan... |
25158830328 | import os
import json
import time
import h5py
import logging
import numpy as np
from annoy import AnnoyIndex
from tensorflow.keras import optimizers
from tensorflow.keras.models import Model
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.applications.vgg16 import preprocess_input
from tensorflow.keras.layers import Dense, BatchNormalization, Activation, Dropout
logger = logging.getLogger()
logger.setLevel(logging.INFO)
ls_class = os.listdir("Data/TrainingData")
ls = []
for i in ls_class:
path, dirs, files = next(os.walk("Data/TrainingData"+"/" +i))
file_count = len(files)
ls.append([i, file_count])
def load_paired_img_wrd(folder):
class_names = [fold for fold in os.listdir(folder) if ".DS" not in fold]
image_list = []
labels_list = []
paths_list = []
for cl in class_names:
splits = cl.split("_")
subfiles = [f for f in os.listdir(folder + "/" + cl) if ".DS" not in f]
for subf in subfiles:
full_path = os.path.join(folder, cl, subf)
img = image.load_img(full_path, target_size=(224, 224))
x_raw = image.img_to_array(img)
x_expand = np.expand_dims(x_raw, axis=0)
x = preprocess_input(x_expand)
image_list.append(x)
paths_list.append(full_path)
img_data = np.array(image_list)
img_data = np.rollaxis(img_data, 1, 0)
img_data = img_data[0]
return img_data, paths_list
def load_headless_pretrained_model():
pretrained_vgg16 = vgg16.VGG16(weights='imagenet', include_top=True)
model = Model(inputs=pretrained_vgg16.input,
outputs=pretrained_vgg16.get_layer('fc2').output)
return model
def generate_features(image_paths, model):
print ("Generating features...")
start = time.time()
images = np.zeros(shape=(len(image_paths), 224, 224, 3))
file_mapping = {i: f for i, f in enumerate(image_paths)}
for i, f in enumerate(image_paths):
img = image.load_img(f, target_size=(224, 224))
x_raw = image.img_to_array(img)
x_expand = np.expand_dims(x_raw, axis=0)
images[i, :, :, :] = x_expand
logger.info("%s images loaded" % len(images))
inputs = preprocess_input(images)
logger.info("Images preprocessed")
images_features = model.predict(inputs)
end = time.time()
logger.info("Inference done, %s Generation time" % (end - start))
return images_features, file_mapping
def save_features(features_filename, features, mapping_filename, file_mapping):
print ("Saving features...")
np.save('%s.npy' % features_filename, features)
with open('%s.json' % mapping_filename, 'w') as index_file:
json.dump(file_mapping, index_file)
logger.info("Weights saved")
def load_features(features_filename, mapping_filename):
print ("Loading features...")
images_features = np.load('%s.npy' % features_filename)
with open('%s.json' % mapping_filename) as f:
index_str = json.load(f)
file_index = {int(k): str(v) for k, v in index_str.items()}
return images_features, file_index
def index_features(features, n_trees=1000, dims=4096, is_dict=False):
print ("Indexing features...")
feature_index = AnnoyIndex(dims, metric='angular')
for i, row in enumerate(features):
vec = row
if is_dict:
vec = features[row]
feature_index.add_item(i, vec)
feature_index.build(n_trees)
return feature_index
def search_index_by_key(key, feature_index, item_mapping, top_n=10):
distances = feature_index.get_nns_by_item(key, top_n, include_distances=True)
return [[a, item_mapping[a], distances[1][i]] for i, a in enumerate(distances[0])]
def get_index(input_image, file_mapping):
for index, file in file_mapping.items():
if file == input_image:
return index
raise ValueError("Image %s not indexed" % input_image)
def get_class_weights_from_vgg(save_weights=False, filename='class_weights'):
model_weights_path = os.path.join(os.environ.get('HOME'),
'.keras/models/vgg16_weights_tf_dim_ordering_tf_kernels.h5')
weights_file = h5py.File(model_weights_path, 'r')
weights_file.get('predictions').get('predictions_W_1:0')
final_weights = weights_file.get('predictions').get('predictions_W_1:0')
class_weights = np.array(final_weights)[:]
weights_file.close()
if save_weights:
np.save('%s.npy' % filename, class_weights)
return class_weights
def get_weighted_features(class_index, images_features):
class_weights = get_class_weights_from_vgg()
target_class_weights = class_weights[:, class_index]
weighted = images_features * target_class_weights
return weighted
def main():
images, image_paths = load_paired_img_wrd('/Data/TrainingData')
model = load_headless_pretrained_model()
images_features, file_index = generate_features(image_paths, model)
path = "image-to-image-search/Code"
save_features(path, images_features, path, file_index)
images_features, file_index = load_features(path, path)
image_index = index_features(images_features, dims=4096)
input_train = "/Data/TrainingData/class-điện thoại/465.jfif"
search_key = get_index(input_train, file_index)
results = search_index_by_key(search_key, image_index, file_index)
for i in range(len(results)):
im = results[i][1]
img=mpimg.imread(im)
if i==0:
img_ = img.copy()
else:
img_ = np.concatenate((img_,img), axis=1)
plt.figure(figsize=(15,15))
plt.imshow(img_)
plt.show()
if __name__ == 'main':
main()
| SteveVu2212/Image-to-Image-Search | Code/Image_Search.py | Image_Search.py | py | 5,742 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "logging.getLogger",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "logging.INFO",
"line_number": 17,
"usage_type": "attribute"
},
{
"api_name": "os.listdir",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "os.walk",
"line_nu... |
38748247827 | #!/usr/bin/python3.2
import sys
import os
import re
import subprocess
import logging
import optparse
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)s %(message)s')
def main():
logging.info('Switching to master branch')
for e in sys.argv:
print (e)
#output,_=call_command('java -jar antlr-4.0-complete.jar sys.argv[0]')
# Ejecuta el comando buscando en $PATH y reemplazando el proceso actual
if len(sys.argv) >1:
os.execlp('java','-cp','./','antlr-4.0-complete.jar','org.antlr.v4.Tool',sys.argv[1])
else:
os.execlp('java -cp ./:/home/mikelemus/antlr4_lib antlr-4.0-complete.jar org.antlr.v4.Tool','hello.g4')
logging.info('Pulled latest changes from origin into master')
logging.info('Ensuring master has the latest changes')
#return 0
if __name__ == "__main__":
main()
| mikelemus27/lemus-code | antlr4/antlr4Test/antlr4.py | antlr4.py | py | 868 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "logging.basicConfig",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "logging.INFO",
"line_number": 9,
"usage_type": "attribute"
},
{
"api_name": "logging.info",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "sys.argv",
"line... |
36972729466 | # Import OpenCV2 for image processing
import cv2
import os
import time
##from twilio.rest import Client
import RPi.GPIO as GPIO
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
IR=19
LASER=17
IN5=23
IN6=24
IN7=25
IN8=8
RED = 2 #Associate pin 23 to TRIG
GREEN = 3
BLUE = 4 #Associate pin 23 to TRIG
GPIO.setup(RED,GPIO.OUT) #Set pin as GPIO out
GPIO.setup(GREEN,GPIO.OUT)
GPIO.setup(BLUE,GPIO.OUT)
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(IR, GPIO.IN)
GPIO.setup(LASER, GPIO.OUT)
GPIO.setup(IN5, GPIO.OUT)
GPIO.setup(IN6, GPIO.OUT)
GPIO.setup(IN7, GPIO.OUT)
GPIO.setup(IN8, GPIO.OUT)
GPIO.output(IN5, False)
GPIO.output(IN6, False)
GPIO.output(IN7, False)
GPIO.output(IN8, False)
GPIO.output(RED, False)
GPIO.output(BLUE, False)
GPIO.output(GREEN, False)
##GPIO.output(LASER, False)
def forward():
GPIO.output(IN7, True)
GPIO.output(IN8, False)
## if(GPIO.input(IR) == False):
## mon=1
## print('PERSON DETECTED')
def reverse():
GPIO.output(IN7, False)
GPIO.output(IN8, True)
## if(GPIO.input(IR) == False):
## mon=1
## print('PERSON DETECTED')
## time.sleep(5)
def stop():
GPIO.output(IN7, False)
GPIO.output(IN8, False)
def IR():
if(GPIO.input(26) == False):
stop()
mon=1
print('PERSON DETECTED')
##GPIO.setup(26, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Import numpy for matrices calculations
import numpy as np
import time
import datetime
# Create Local Binary Patterns Histograms for face recognization
#recognizer = cv2.face.createLBPHFaceRecognizer()
recognizer = cv2.face.LBPHFaceRecognizer_create()
# Load the trained mode
recognizer.read('trainer/trainer.yml')
##recognizer.read('/home/pi/Desktop/face_recog_folder/Raspberry-Face-Recognition-master/trainer/trainer.yml')
# Load prebuilt model for Frontal Face
cascadePath = "haarcascade_frontalface_default.xml"
# Create classifier from prebuilt model
faceCascade = cv2.CascadeClassifier(cascadePath);
# Set the font style
font = cv2.FONT_HERSHEY_SIMPLEX
# Initialize and start the video frame capture
cam = cv2.VideoCapture(0)
flag = []
count1=0
count2=0
count3=0
sample =0
lecture=0
mon=0
count=0
##account_sid = "AC4c80a8d4e94004afc637499ca50ddc59"
##auth_token = "d7008f6cd8700dd6fac792bc35f7bfa7"
##
##client = Client(account_sid, auth_token)
while True:
forward()
time.sleep(2)
stop()
time.sleep(1)
reverse()
time.sleep(2)
stop()
time.sleep(1)
if(GPIO.input(19) == False):
mon=1
print('PERSON DETECTED')
while mon == 1:
now = datetime.datetime.now()
# Read the video frame
ret, im =cam.read()
# Convert the captured frame into grayscale
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
# Get all face from the video frame
faces = faceCascade.detectMultiScale(gray, 1.2,5)
# For each face in faces
for(x,y,w,h) in faces:
# Create rectangle around the face
cv2.rectangle(im, (x-20,y-20), (x+w+20,y+h+20), (0,255,0), 4)
# Recognize the face belongs to which ID
Id,i = recognizer.predict(gray[y:y+h,x:x+w])
#id = int(os.path.split(imagePath)[-1].split(".")[1])
print(i)
# Check the ID if exist
if i < 60:
sample= sample+1
if Id == 2 :
#flag[1]=1
count1=1
Id = "SAMEER"
print("SAMEER")
lecture=1
sample=0
forward()
time.sleep(1)
stop()
time.sleep(2)
reverse()
time.sleep(1)
stop()
time.sleep(2)
#time.sleep(2)
break
else:
count=count+1
if count > 20:
count=0
print(Id)
mon=0
Id = "unknown"
stop()
print('LASER GUN ON')
GPIO.output(LASER, GPIO.HIGH)
cv2.imwrite('frame.png',im)
## client.api.account.messages.create(
## to="+91-9902599273",
## from_="+1 716-543-3315" , #+1 210-762-4855"
## body=" Detected" )
## atttachem.sendMail( ["ashokkoppad21@gmail.com"],
## "Unknown person Detected",
## "Unknown person Detected",
## ["frame.png","test.txt"] )
# Put text describe who is in the picture
cv2.rectangle(im, (x-22,y-90), (x+w+22, y-22), (0,255,0), -1)
cv2.putText(im, str(Id), (x,y-40), font, 2, (255,255,255), 3)
# Display the video frame with the bounded rectangle
cv2.imshow('im',im)
# If 'q' is pressed, close program
if cv2.waitKey(20) & 0xFF == ord('q'): #if cv2.waitKey(10) & 0xFF == ord('q'):
break
cam.release()
# Close all windows
cv2.destroyAllWindows()
| 9ightcor3/Camouflage-Multifunctional-Bot | face_recognition.py | face_recognition.py | py | 5,321 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "RPi.GPIO.setwarnings",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "RPi.GPIO",
"line_number": 11,
"usage_type": "name"
},
{
"api_name": "RPi.GPIO.setmode",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "RPi.GPIO",
"line_n... |
16675681390 | """
实现生成cookie 的脚本
1,创建gen_gsxt_cookies.py文件,在其中创建GenGsxtCookie的类
2,实现一个方法,用于把一套代理IP,User-Agent,Cookie绑定在一起的信息放到Redis的list中
随机获取一个User-Agent
随机获取一个代理IP
获取request的session对象
把User-Agent,通过请求头,设置给session对象
把代理IP,通过proxies,设置给session对象
使用session对象,发送请求,获取需要的cookie信息
把代理IP ,User-Agent,Cookie放到字典中,序列化后,存储到Redis的list中
3,实现一个run方法,用于开启多个异步来执行这个方法。
注:为了和下载器中间件交互方便,需要再settings.py中配置一些常量
"""
#打猴子补丁 一定要在requestszhiq打
from gevent import monkey
monkey.patch_all()
from gevent.pool import Pool
import random,requests,re,js2py,pickle
from redis import StrictRedis,ConnectionPool
from dishonest.settings import USER_AGENTS,COOKIES_KEY,COOKIES_PROXY_KEY,COOKIES_USER_AGENT_KEY,REDIS_COOKIES_KEY
class GenGsxtCookie():
def __init__(self):
#链接redis
self.redis = StrictRedis(host="localhost", port=6379, db=0, password=None)
self.redis.delete('redis_cookies')#清空redis_cookies数据库
#创建携程池对象
self.pool=Pool()
def push_cookie_to_redis(self):
while True:
try:
# 实现一个方法,用于把一套代理IP,User - Agent, Cookie绑定在一起的信息放到Redis的list中
# 随机获取一个User - Agent
user_agent=random.choice(USER_AGENTS)
# 随机获取一个代理IP
response = requests.get('http://localhost:16888/random?protocol=http')
proxy=response.content.decode()
# 获取request的session对象
session=requests.session()
# 把User - Agent,通过请求头,设置给session对象
session.headers={ 'User-Agent': user_agent }
# 把代理IP,通过proxies,设置给session对象
session.proxies={'http':proxy}
# 使用session对象,发送请求,获取需要的cookie信息
index_url = 'http://www.gsxt.gov.cn/corp-query-entprise-info-xxgg-100000.html'
response = session.get(index_url)
# print(response.status_code)
# print(response.content.decode())
# 1,提取script 标签中的js
js = re.findall(r'<script>(.*?)</script>', response.content.decode())[0]
# print(js)
# 2,由于这种加密JS,最终指向的js代码,都是在eval函数中的,所以'{eval'(替换为){code=(, 然后就可以通过code,获取真正要执行的js了
js = js.replace('{eval(', '{code=(')
# 3,需要执行JS
# 3.1,获取执行js的环境
context = js2py.EvalJs()
context.execute(js)
# 3.2 打印code的值
print(context.code)
# 3.3获取生成Cookie的js
cookies_code = re.findall(r"document.(cookie=.*?)\+';Expires", context.code)[0]
# print(cookies_code)
# 在js2py中,是不能使用 'document','window'这些浏览器中对象
# var _1a=document.createElement('div');_1a.innerHTML='<a href=\\'/\\'>_21</a>';_1a=_1a.firstChild.href
# js2py是无法处理的,需要能看懂上诉js代码
# var _34=document.createElement('div');_34.innerHTML='<a href=\'/\'>_15</a>';_34=_34.firstChild.href
# _34='http://www.gsxt.gov.cn'
# cookies_code=re.sub(r"var\s+(\w+)=document.createElement\('\w+'\);\w+.innerHTML='<a href=\\'/\\'>\w+</a>';\w+=\w+.firstChild.href",r"var /1='http://www.gsxt.gov.cn'",cookies_code)
cookies_code = re.sub(r"var\s+(\w+)=document.+?firstChild.href", r"var \1='http://www.gsxt.gov.cn'",
cookies_code)
# print(cookies_code)
# 执行js,生成我们需要的cookie信息
context.execute(cookies_code)
# 打印cookie
# print(context.cookie)
# 上面用session.headers=headers添加headers,下面就不用传递headers
cookies = context.cookie.split('=')
# session.cookies.update({cookies[0]:cookies[1]})
session.cookies.set(cookies[0], cookies[1]) # 将JS的cokies 设置添加进去
session.get(index_url) # 发送请求
# print(session.cookies)
# 获取cookie字典
cookies = requests.utils.dict_from_cookiejar(session.cookies)
print(cookies)
# 把代理IP ,User - Agent,Cookie放到字典中,序列化后,存储到Redis的list中
cookies_dict={
COOKIES_KEY:cookies,
COOKIES_USER_AGENT_KEY:user_agent,
COOKIES_PROXY_KEY:proxy,
}
print(cookies_dict)
#序列化后,存储到Redis的list中
self.redis.lpush(REDIS_COOKIES_KEY,pickle.dumps(cookies_dict))
break
except Exception as ec:
print(ec)
# 实现一个run方法,用于开启多个异步来执行这个方法
def run(self):
#3,实现一个run方法,用于开启多个异步来执行这个方法
for i in range(100):
self.pool.apply_async(self.push_cookie_to_redis)
#让主线程等待所以携程任务完成
self.pool.join()
if __name__ == '__main__':
ggc=GenGsxtCookie()
ggc.run() | luopeixiong/python-test | 爬虫项目/scrapy项目/dishonest_失信人/dishonest/spiders/get_gsxt_cookies.py | get_gsxt_cookies.py | py | 5,913 | python | zh | code | null | github-code | 1 | [
{
"api_name": "gevent.monkey.patch_all",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "gevent.monkey",
"line_number": 19,
"usage_type": "name"
},
{
"api_name": "redis.StrictRedis",
"line_number": 30,
"usage_type": "call"
},
{
"api_name": "gevent.pool.P... |
31478942286 | from pygame import sprite, transform, image, font, event
class Gui(sprite.Group):
def __init__(self, rect_size):
super().__init__()
self.heart_sprites = sprite.Group()
self.bomb_sprites = sprite.Group()
self.rect_size = rect_size
self.hp = 5
self.bomb = 5
self.font = font.Font('fonts\\f1.ttf', self.rect_size)
self.heart = transform.scale(image.load('GUI\\heart.png').convert(), (self.rect_size, self.rect_size))
self.heart_pass = transform.scale(image.load('GUI\\heart_pass.png').convert(), (self.rect_size, self.rect_size))
self.max_hp = 10
self.max_bomb = 50
self.set_hearts(self.hp)
self.set_bombs(self.bomb)
def set_hearts(self, num):
if 0 < num <= self.max_hp:
if self.hp - 1 == num:
event.post(event.Event(53, {}))
self.hp = num
self.heart_sprites.empty()
for i in range(self.max_hp):
spr = sprite.Sprite()
if i < self.hp:
spr.image = self.heart
else:
spr.image = self.heart_pass
spr.image.set_colorkey((255, 255, 255))
spr.rect = spr.image.get_rect()
spr.rect.center = (int(self.rect_size * 1.5) * (i + 1), self.rect_size)
self.heart_sprites.add(spr)
elif num <= 0:
self.hp = num
self.heart_sprites.empty()
for i in range(self.max_hp):
spr = sprite.Sprite()
if i < self.hp:
spr.image = self.heart
else:
spr.image = self.heart_pass
spr.image.set_colorkey((255, 255, 255))
spr.rect = spr.image.get_rect()
spr.rect.center = (int(self.rect_size * 1.5) * (i + 1), self.rect_size)
self.heart_sprites.add(spr)
event.post(event.Event(31, {}))
def set_bombs(self, num):
if 0 <= num <= self.max_bomb:
self.bomb = num
self.bomb_sprites.empty()
spr = sprite.Sprite()
spr.image = transform.scale(image.load('GUI\\carrot_bomb.png').convert(), (self.rect_size, self.rect_size))
spr.image.set_colorkey((255, 255, 255))
spr.rect = spr.image.get_rect()
spr.rect.center = (int(self.rect_size * 1.5), self.rect_size * 2.5)
self.bomb_sprites.add(spr)
spr = sprite.Sprite()
spr.image = self.font.render(str(self.bomb), True, (0, 0, 0))
spr.image.set_colorkey((255, 255, 255))
spr.rect = spr.image.get_rect()
spr.rect.center = (int(self.rect_size * 1.5) * 2, self.rect_size * 2.5)
self.bomb_sprites.add(spr)
def draw(self, surface):
super().draw(surface)
self.heart_sprites.draw(surface)
self.bomb_sprites.draw(surface)
| Rogozhin-Dmitry/lyceum_project_2 | gui_file.py | gui_file.py | py | 2,964 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "pygame.sprite.Group",
"line_number": 4,
"usage_type": "attribute"
},
{
"api_name": "pygame.sprite",
"line_number": 4,
"usage_type": "name"
},
{
"api_name": "pygame.sprite.Group",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "pygame.sprite... |
2020300464 | from flask import request, jsonify, make_response, abort, Blueprint
from app import db
import uuid
import copy
import datetime
from .helpers import remove_item_from_location, add_item_to_location, change_item_location, get_unassigned
#Blueprints
user_bp = Blueprint("user", __name__, url_prefix="/users")
game_bp = Blueprint("game", __name__, url_prefix="/games")
### USERS ###
users_ref = db.collection('users')
#Create new user
@user_bp.route('', methods=['POST'])
def create_user():
#Verify presence of name and email
if 'email' not in request.json.keys():
abort(make_response(jsonify({"message": "Email not found"}), 404))
if 'name' not in request.json.keys():
abort(make_response(jsonify({"message": "Name not found"}), 404))
#Create user with id, games, and timestamp fields
new_user = request.json
user_id = request.json['uid']
new_user['game_ids'] = []
new_user['timestamp'] = str(datetime.datetime.now())
users_ref.document(user_id).set(new_user)
return jsonify(new_user), 200
#Read users (all or by ID)
@user_bp.route('', methods=['GET'])
def read_users():
#Returns all users if no param "id", else searches for user by ID
user_id = request.args.get('user_id')
if user_id:
user = users_ref.document(user_id).get()
return jsonify(user.to_dict()), 200
else:
all_users = [doc.to_dict() for doc in users_ref.stream()]
return jsonify(all_users), 200
#Delete user and remove them from all games
@user_bp.route('', methods=['DELETE'])
def delete_user():
user_id = request.args.get('user_id')
game_ids = users_ref.document(user_id).get().to_dict()['game_ids']
for game_id in game_ids:
#Remove user from game's list of user IDs for each game
game = games_ref.document(game_id).get().to_dict()
game['user_ids'] = list(filter(lambda x: x != user_id, game['user_ids']))
games_ref.document(game_id).set(game)
users_ref.document(user_id).delete()
return jsonify({"success": True}), 200
#Add user to game
@user_bp.route('/games', methods=['PATCH'])
def add_game_to_user():
game_id = request.args.get('game_id')
user_id = request.args.get('user_id')
#Add game ID to user's list of game IDs
user = users_ref.document(user_id).get().to_dict()
if game_id not in user['game_ids']:
user['game_ids'].append(game_id)
users_ref.document(user_id).set(user)
#Add user ID to game's list of user IDs
game = games_ref.document(game_id).get().to_dict()
if user_id not in game['user_ids']:
game['user_ids'].append(user_id)
games_ref.document(game_id).set(game)
return jsonify(game), 200
#Edit user's name
@user_bp.route('', methods=['PATCH'])
def rename_user():
user_id = request.args.get('user_id')
user = users_ref.document(user_id).get().to_dict()
name = request.json['name']
user['name'] = name
users_ref.document(user_id).set(user)
return jsonify(user), 200
### GAMES ###
games_ref = db.collection('games')
#Create a new game
@game_bp.route('', methods=['POST'])
def create_game():
if 'name' not in request.json.keys():
abort(make_response(jsonify({"message": "Game name not found"}), 404))
new_game = request.json
game_id = str(uuid.uuid4())
new_game['gid'] = game_id
new_game['user_ids'] = []
new_game['timestamp'] = str(datetime.datetime.now())
games_ref.document(game_id).set(new_game)
#Create default 'unassigned' location for game
loc_id = str(uuid.uuid4())
loc_ref = games_ref.document(game_id).collection('locations')
loc_data = {'lid':loc_id, 'gid': game_id, 'type': 'location', 'item_ids': [], 'name': 'Unassigned', 'timestamp': str(datetime.datetime.now())}
loc_ref.document(loc_id).set(loc_data)
return jsonify(new_game), 200
#Delete a game
@game_bp.route('', methods=['DELETE'])
def remove_game():
game_id = request.args.get('game_id')
user_ids = games_ref.document(game_id).get().to_dict()['user_ids']
#Remove item and location collections
loc_ref = games_ref.document(game_id).collection('locations')
for doc in loc_ref.stream():
loc_id = doc.to_dict()['lid']
loc_ref.document(loc_id).delete()
item_ref = games_ref.document(game_id).collection('items')
for doc in item_ref.stream():
item_id = doc.to_dict()['iid']
item_ref.document(item_id).delete()
#Remove game from each user
for user_id in user_ids:
user = users_ref.document(user_id).get().to_dict()
user['game_ids'] = list(filter(lambda x: x != game_id, user['game_ids']))
users_ref.document(user_id).set(user)
games_ref.document(game_id).delete()
return jsonify({"success": True}), 200
#Read games (all or by ID)
@game_bp.route('', methods=['GET'])
def read_games():
game_id = request.args.get('game_id')
if game_id:
game = games_ref.document(game_id).get()
return jsonify(game.to_dict()), 200
else:
all_games = [doc.to_dict() for doc in games_ref.stream()]
return jsonify(all_games), 200
#Read games from specific user
@user_bp.route('/games', methods=['GET'])
def read_games_from_user():
user_id = request.args.get('user_id')
games_list = []
for game_id in users_ref.document(user_id).get().to_dict()['game_ids']:
game = games_ref.document(game_id).get()
games_list.append(game.to_dict())
return jsonify(games_list)
#Rename game
@game_bp.route('', methods=['PATCH'])
def rename_game():
game_id = request.args.get('game_id')
name = request.json['name']
game = games_ref.document(game_id).get().to_dict()
new_game = copy.deepcopy(game)
new_game['name'] = name
games_ref.document(game_id).set(new_game)
return jsonify(new_game), 200
#Get list of users in game
@game_bp.route('/users', methods=['GET'])
def get_game_users():
game_id = request.args.get('game_id')
game = games_ref.document(game_id).get().to_dict()
user_ids = [users_ref.document(user_id).get().to_dict() for user_id in game['user_ids']]
return jsonify(user_ids), 200
#Remove user from game
@game_bp.route('/users', methods=['PATCH'])
def remove_user_from_game():
game_id = request.args.get('game_id')
user_id = request.args.get('user_id')
#Handle game
game = games_ref.document(game_id).get().to_dict()
game['user_ids'] = [id for id in game['user_ids'] if id != user_id]
games_ref.document(game_id).set(game)
#Handle user
user = users_ref.document(user_id).get().to_dict()
user['game_ids'] = [id for id in user['game_ids'] if id != game_id]
users_ref.document(user_id).set(user)
return jsonify(game), 200
### LOCATIONS ###
#Create location within game
@game_bp.route('/locations', methods=['POST'])
def add_location():
game_id = request.args.get('game_id')
name = request.json['name']
type_name = request.json['type']
loc_id = str(uuid.uuid4())
loc_ref = games_ref.document(game_id).collection('locations')
loc_data = {'name': name, 'lid': loc_id, 'gid': game_id, 'type': type_name, 'item_ids': [], 'timestamp': str(datetime.datetime.now())}
loc_ref.document(loc_id).set(loc_data)
return jsonify(loc_data), 200
#Delete location and unassign all items
@game_bp.route('locations', methods=['DELETE'])
def delete_location():
#Get all items from location
game_id = request.args.get('game_id')
loc_id = request.args.get('loc_id')
loc_ref = games_ref.document(game_id).collection('locations')
item_ids = loc_ref.document(loc_id).get().to_dict()['item_ids']
unassigned_id = get_unassigned(loc_ref)
#Move every item in location to 'Unassigned'
for item_id in item_ids:
change_item_location(games_ref, game_id, item_id, unassigned_id)
add_item_to_location(games_ref, game_id, item_id, unassigned_id)
loc_ref.document(loc_id).delete()
return jsonify({'success': True}), 200
#Get location or list of locations
@game_bp.route('/locations', methods=['GET'])
def read_locations():
game_id = request.args.get('game_id')
loc_id = request.args.get('loc_id')
loc_ref = games_ref.document(game_id).collection('locations')
if loc_id:
loc = loc_ref.document(loc_id).get()
return jsonify(loc.to_dict()), 200
else:
all_locs = [doc.to_dict() for doc in loc_ref.stream()]
return jsonify(all_locs), 200
#Rename location
@game_bp.route('/locations', methods=['PATCH'])
def rename_location():
game_id = request.args.get('game_id')
loc_id = request.args.get('loc_id')
name = request.json['name']
loc_ref = games_ref.document(game_id).collection('locations')
new_loc = loc_ref.document(loc_id).get().to_dict()
new_loc['name'] = name
loc_ref.document(loc_id).set(new_loc)
return jsonify(new_loc)
### ITEMS ###
#Create item w/ location ID (default to unassigned)
@game_bp.route('/items', methods=['POST'])
def create_item():
game_id = request.args.get('game_id')
loc_id = request.args.get('loc_id')
loc_ref = games_ref.document(game_id).collection('locations')
item_ref = games_ref.document(game_id).collection('items')
item_id = str(uuid.uuid4())
if not loc_id:
loc_id = get_unassigned(loc_ref)
#Add new item to items collection of game
new_item = request.json
new_item['lid'] = loc_id
new_item['gid'] = game_id
new_item['iid'] = item_id
new_item['timestamp'] = str(datetime.datetime.now())
item_ref.document(item_id).set(new_item)
#Add item to location's item ID list
add_item_to_location(games_ref, game_id, item_id, loc_id)
return jsonify(new_item), 200
#Delete item
@game_bp.route('/items', methods=['DELETE'])
def delete_item():
game_id = request.args.get('game_id')
item_id = request.args.get('item_id')
#Get loc ID of item
item_ref = games_ref.document(game_id).collection('items')
loc_id = item_ref.document(item_id).get().to_dict()['lid']
remove_item_from_location(games_ref, game_id, item_id, loc_id)
#Delete item
item_ref.document(item_id).delete()
return jsonify({'success': True}), 200
# Change location of item
@game_bp.route('/items/locations', methods=['PATCH'])
def update_item_location():
game_id = request.args.get('game_id')
item_id = request.args.get('item_id')
loc_id = request.args.get('loc_id')
new_loc = request.json['loc_id']
item = change_item_location(games_ref, game_id, item_id, new_loc)
remove_item_from_location(games_ref, game_id, item_id, loc_id)
add_item_to_location(games_ref, game_id, item_id, new_loc)
return jsonify(item), 200
# Change name/type of item
@game_bp.route('/items', methods=['PATCH'])
def update_item_fields():
game_id = request.args.get('game_id')
item_id = request.args.get('item_id')
items = games_ref.document(game_id).collection('items')
item = items.document(item_id).get().to_dict()
data = request.json
for field, value in data.items():
item[field] = value
items.document(item_id).set(item)
return jsonify(item), 200
#Get item or list of items
@game_bp.route('/items', methods=['GET'])
def read_items():
game_id = request.args.get('game_id')
item_id = request.args.get('item_id')
item_ref = games_ref.document(game_id).collection('items')
if item_id:
item = item_ref.document(item_id).get()
return jsonify(item.to_dict()), 200
else:
all_items = [doc.to_dict() for doc in item_ref.stream()]
return jsonify(all_items), 200
#Read items from location
@game_bp.route('/locations/items', methods=['GET'])
def read_items_from_location():
game_id = request.args.get('game_id')
loc_id = request.args.get('loc_id')
loc_ref = games_ref.document(game_id).collection('locations')
location = loc_ref.document(loc_id).get().to_dict()
item_ref = games_ref.document(game_id).collection('items')
item_ids = location['item_ids']
items = []
for item_id in item_ids:
items.append(item_ref.document(item_id).get().to_dict())
return jsonify(items), 200
| DeeJMWilliams/nodwick-back-end | app/routes.py | routes.py | py | 12,154 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "flask.Blueprint",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "flask.Blueprint",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "app.db.collection",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "app.db",
"line_n... |
18263639584 | from sqlalchemy.exc import InvalidRequestError
import logging
from multiprocessing import cpu_count, Pool
from pathlib import Path
from bitglitter.config.palettemodels import Palette
from bitglitter.config.readmodels.streamread import StreamRead
from bitglitter.read.process_state.videoframegenerator import video_frame_generator
from bitglitter.read.process_state.imageframeprocessor import ImageFrameProcessor
from bitglitter.read.process_state.multiprocess_state_generator import image_state_generator, video_state_generator
from bitglitter.read.process_state.videoframeprocessor import VideoFrameProcessor
from bitglitter.utilities.read import flush_inactive_frames
def frame_read_handler(input_path, output_directory, input_type, bad_frame_strikes, max_cpu_cores,
block_height_override, block_width_override, decryption_key, scrypt_n, scrypt_r, scrypt_p,
temp_save_directory, stop_at_metadata_load, auto_unpackage_stream, auto_delete_finished_stream,
save_statistics, valid_image_formats):
logging.info(f'Processing {input_path}...')
# Initializing variables that will be in all frame_process() calls
initializer_palette_a = Palette.query.filter(Palette.palette_id == '1').first()
initializer_palette_b = Palette.query.filter(Palette.palette_id == '11').first()
initializer_palette_a_color_set = initializer_palette_a.convert_colors_to_tuple()
initializer_palette_b_color_set = initializer_palette_b.convert_colors_to_tuple()
initializer_palette_a_dict = initializer_palette_a.return_decoder()
initializer_palette_b_dict = initializer_palette_b.return_decoder()
stream_palette = None
stream_palette_dict = None
stream_palette_color_set = None
initial_state_dict = {'output_directory': output_directory, 'block_height_override': block_height_override,
'block_width_override': block_width_override, 'decryption_key': decryption_key, 'scrypt_n':
scrypt_n, 'scrypt_r': scrypt_r, 'scrypt_p': scrypt_p, 'temp_save_directory':
temp_save_directory, 'initializer_palette_a': initializer_palette_a,
'initializer_palette_a_color_set': initializer_palette_a_color_set,
'initializer_palette_b_color_set': initializer_palette_b_color_set,
'initializer_palette_a_dict': initializer_palette_a_dict, 'initializer_palette_b_dict':
initializer_palette_b_dict, 'auto_delete_finished_stream': auto_delete_finished_stream,
'stop_at_metadata_load': stop_at_metadata_load, 'save_statistics': save_statistics,
'auto_unpackage_stream': auto_unpackage_stream, 'sequential': True}
# Multicore setup
if max_cpu_cores == 0 or max_cpu_cores >= cpu_count():
cpu_pool_size = cpu_count()
else:
cpu_pool_size = max_cpu_cores
frame_strikes_this_session = 0
image_strike_limit_hit = False
image_metadata_checkpoint_data = None
frame_read_results = {'active_sessions_this_stream': []}
if input_type == 'video':
frame_generator = video_frame_generator(input_path)
total_video_frames = next(frame_generator)
initial_state_dict['total_frames'] = total_video_frames
logging.info(f'{total_video_frames} frame(s) detected in video file.')
initial_state_dict['mode'] = 'video'
# Processing frames in a single process until all metadata has been received, then switch to multicore
logging.info('Starting single core sequential decoding until metadata captured...')
for frame_data in frame_generator:
initial_state_dict['frame'] = frame_data['frame']
initial_state_dict['current_frame_position'] = frame_data['current_frame_position']
video_frame_processor = VideoFrameProcessor(initial_state_dict)
# Skip if all frames completed
if video_frame_processor.skip_process:
frame_read_results['active_sessions_this_stream'].append(video_frame_processor.stream_sha256)
break
# Errors
if 'error' in video_frame_processor.frame_errors:
# Session-ending error, such as a metadata frame being corrupted
if 'fatal' in video_frame_processor.frame_errors:
logging.warning('Cannot continue.')
return {'error': True}
if bad_frame_strikes: # Corrupted frame, skipping to next one
frame_strikes_this_session += 1
logging.warning(f'Bad frame strike {frame_strikes_this_session}/{bad_frame_strikes}')
if frame_strikes_this_session >= bad_frame_strikes:
logging.warning('Reached frame strike limit. Aborting...')
return {'error': True}
if frame_data['current_frame_position'] == 1:
stream_read = video_frame_processor.stream_read
initial_state_dict['stream_read'] = stream_read
# Metadata return
if video_frame_processor.metadata and stream_read.stop_at_metadata_load:
return {'metadata': video_frame_processor.metadata}
# Stream palette load
if video_frame_processor.stream_palette and video_frame_processor.stream_palette_loaded_this_frame:
stream_palette = video_frame_processor.stream_palette
stream_palette_dict = video_frame_processor.stream_palette_dict
stream_palette_color_set = video_frame_processor.stream_palette_color_set
initial_state_dict['stream_palette'] = stream_palette
initial_state_dict['stream_palette_dict'] = stream_palette_dict
initial_state_dict['stream_palette_color_set'] = stream_palette_color_set
# Headers are decoded, can switch to multiprocessing
if stream_read.palette_header_complete and stream_read.metadata_header_complete:
frame_read_results['active_sessions_this_stream']\
.append(video_frame_processor.stream_read.stream_sha256)
break
# Begin multicore frame decode
if not video_frame_processor.skip_process:
with Pool(processes=cpu_pool_size) as worker_pool:
logging.info(f'Metadata headers fully decoded, now decoding on {cpu_pool_size} CPU core(s)...')
for multicore_read_results in worker_pool.imap(VideoFrameProcessor,
video_state_generator(frame_generator, stream_read,
save_statistics, initializer_palette_a,
initializer_palette_a_dict, initializer_palette_a_color_set,
total_video_frames, stream_palette, stream_palette_dict,
stream_palette_color_set)):
if 'error' in multicore_read_results.frame_errors:
if bad_frame_strikes: # Corrupted frame, skipping to next one
frame_strikes_this_session += 1
logging.warning(f'Bad frame strike {frame_strikes_this_session}/{bad_frame_strikes}')
if frame_strikes_this_session >= bad_frame_strikes:
logging.warning('Reached frame strike limit. Aborting...')
return {'error': True}
elif input_type == 'image':
# Normalizing the different forms of input path into a common list format format
if isinstance(input_path, list):
input_list = input_path
elif isinstance(input_path, str):
path = Path(input_path)
if path.is_dir():
input_list = []
for file_format in valid_image_formats:
for whitelisted_file in path.rglob(file_format):
input_list.append(str(whitelisted_file))
else:
input_list = [input_path]
# Begin multicore frame decode
image_metadata_checkpoint_data = None
image_strike_limit_hit = False
with Pool(processes=cpu_pool_size) as worker_pool:
logging.info(f'Decoding on {cpu_pool_size} CPU core(s)...')
for multicore_read_results in worker_pool.imap(ImageFrameProcessor, image_state_generator(input_list,
initial_state_dict)):
if 'error' in multicore_read_results.frame_errors:
if bad_frame_strikes: # Corrupted frame, skipping to next one
frame_strikes_this_session += 1
logging.warning(f'Bad frame strike {frame_strikes_this_session}/{bad_frame_strikes}'
f' ({multicore_read_results.file_name})')
if frame_strikes_this_session >= bad_frame_strikes:
logging.warning('Reached frame strike limit. Aborting...')
image_strike_limit_hit = True
break
if multicore_read_results.stream_sha256:
if multicore_read_results.stream_sha256 not in frame_read_results['active_sessions_this_stream']:
frame_read_results['active_sessions_this_stream'].append(multicore_read_results.stream_sha256)
if multicore_read_results.metadata and multicore_read_results.stream_read.stop_at_metadata_load:
image_metadata_checkpoint_data = multicore_read_results.metadata
break
# Outside the scope of image multiprocessing to work properly
if image_strike_limit_hit:
return {'error': True}
if image_metadata_checkpoint_data:
return {'metadata': image_metadata_checkpoint_data}
logging.info('Frame scanning complete.')
# Remove incomplete frames from db
flush_inactive_frames()
# Closing active sessions and unpackaging streams if its set to:
extracted_file_count = 0
active_reads_this_session = StreamRead.query.filter(StreamRead.active_this_session == True).all()
unpackaging_this_session = False
if active_reads_this_session:
logging.info(f'{len(active_reads_this_session)} active stream(s) this session.')
frame_read_results['unpackage_results'] = {}
for stream_read in active_reads_this_session:
stream_read.completed_frame_count_update()
if stream_read.auto_unpackage_stream:
unpackaging_this_session = True
unpackage_results, total_unpackaged = stream_read.attempt_unpackage(temp_save_directory)
extracted_file_count += total_unpackaged
frame_read_results['unpackage_results'][stream_read.stream_sha256] = unpackage_results
stream_read.autodelete_attempt()
else:
stream_read.check_file_eligibility()
try:
stream_read.session_activity(False)
except InvalidRequestError:
pass
if unpackaging_this_session:
logging.info('File unpackaging complete.')
frame_read_results['extracted_file_count'] = extracted_file_count
return {'frame_read_results': frame_read_results}
| MarkMichon1/BitGlitter-Python | bitglitter/read/process_state/framereadhandler.py | framereadhandler.py | py | 11,681 | python | en | code | 10 | github-code | 1 | [
{
"api_name": "logging.info",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "bitglitter.config.palettemodels.Palette.query.filter",
"line_number": 23,
"usage_type": "call"
},
{
"api_name": "bitglitter.config.palettemodels.Palette.query",
"line_number": 23,
"usa... |
26584511593 | # pylint: disable=protected-access
import logging
from datetime import datetime
from odoo import http, models, fields, SUPERUSER_ID, _
from odoo.http import request
_logger = logging.getLogger(__name__)
def get_invoice_values(data: dict) -> dict:
"""Prepares the values for the invoice creation.
* Company: Mandatory (vat, name or id). [company]
* Partner: Mandatory (vat, name or id). [partner]
* Invoice Date: Optional (dd-mm-yyyy). Default is current date. [date]
* Reference: Optional. Default is empty string. [ref]
* Type: Optional. Default is 'out_invoice'. TODO: implement other types.
* Journal: Optional (code, name or id). Default is partner's default journal. [journal]
* Document Type: Mandatory depending on the journal (code, name or id). [document_type]
Args:
data (dict): Data received from the external service.
Returns:
dict: Values for the invoice creation.
"""
company = data.get("company")
if not company:
return {"error": "Company not found"}
company = (
request.env["res.company"]
.with_user(SUPERUSER_ID)
.search([])
.filtered(
lambda c: c.vat == str(company)
or c.name.lower() == str(company).lower()
or c.id == company
)
)
if not company:
return {"error": f"Company '{data.get('company')}' not found"}
partner = data.get("partner")
if not partner:
return {"error": "Missing partner"}
partner = (
request.env["res.partner"]
.with_user(SUPERUSER_ID)
.search([])
.filtered(
lambda p: p.vat == str(partner)
or p.name.lower() == str(partner).lower()
or p.id == partner
)
)
if not partner:
return {"error": f"Partner '{data.get('partner')}' not found"}
date = data.get("date")
if date:
date = datetime.strptime(date, "%d-%m-%Y").strftime("%Y-%m-%d")
values = {
"partner_id": partner.id,
"ref": data.get("ref"),
"type": "out_invoice",
"company_id": company.id,
"invoice_date": date,
}
journal = data.get("journal")
if journal:
journal = (
request.env["account.journal"]
.with_user(SUPERUSER_ID)
.search([("type", "=", "sale"), ("company_id", "=", company.id)])
.filtered(
lambda j: j.code == str(journal)
or j.name.lower() == str(journal).lower()
or j.id == journal
)
)
if not journal:
return {"error": "Journal not found"}
values["journal_id"] = journal.id
if journal.l10n_latam_use_documents:
document_type = data.get("document_type")
if not document_type:
return {"error": "Missing document type"}
document_type = (
request.env["l10n_latam.document.type"]
.with_user(SUPERUSER_ID)
.search([])
.filtered(
lambda j: j.code == str(document_type)
or j.name.lower() == str(document_type).lower()
or j.id == document_type
)
)
values["l10n_latam_document_type_id"] = document_type.id
return values
def add_lines_to_invoice(
invoice: models.Model, lines: list, company: int
) -> dict or bool:
"""Adds the lines to the invoice.
* Product: Mandatory (name or id). [product]
* Quantity: Mandatory. [quantity]
* Taxes: Optional (name or id). Default is product's taxes. If not taxes are found,
and the product does not have a default tax, this will return an error.
If more than one Argentinian IVA Tax Type is added, will return an error. [taxes[list]]
* Price Unit: Optional. Default is product's list price. [price_unit]
Args:
invoice (models.Model): account.move record.
lines (list): List of dicts with the lines to add.
Returns:
dict or bool: error message or success.
"""
#FIXME: document_type is overwriten when adding lines
l10n_latam_document_type_id = invoice.l10n_latam_document_type_id.id
for line in lines:
product = line.get("product")
if not product:
return {"error": "An Invoice Line is missing the product"}
product = (
request.env["product.template"]
.with_user(SUPERUSER_ID)
.search([("company_id", "in", [company, False])])
.filtered(
lambda p, product=product: p.name.lower() == str(product).lower()
or p.id == product
)
)
if not product:
return {"error": f"Product '{line.get('product')}' not found"}
quantity = line.get("quantity")
if not quantity:
return {"error": "Missing quantity"}
taxes = line.get("taxes")
if not taxes and not product.taxes_id:
return {"error": "Missing taxes"}
tax_ids = []
if taxes:
for tax in taxes:
tax_id = (
request.env["account.tax"]
.with_user(SUPERUSER_ID)
.search(
[
("company_id", "=", invoice.company_id.id),
("type_tax_use", "=", "sale"),
]
)
.filtered(
lambda t, tax=tax: t.name.lower() == str(tax).lower()
or t.id == tax
)
)
if not tax_id:
return {"error": f"{tax} Not Found"}
tax_ids.append(tax_id.id)
tax_ids.extend(product.taxes_id.ids)
tax_ids = list(set(tax_ids))
vat_taxes = (
request.env["account.tax"]
.sudo()
.browse(tax_ids)
.filtered(lambda x: x.tax_group_id.l10n_ar_vat_afip_code)
)
if len(vat_taxes) > 1:
return {
"error": _(
"There must be one and only one VAT tax per line. "
'Check line with product "%s"'
)
% product.name
}
line_values = {
"product_id": product.id,
"quantity": quantity,
"price_unit": line.get("price_unit") or product.lst_price,
"tax_ids": [(6, 0, tax_ids)],
}
invoice.invoice_line_ids = [(0, 0, line_values)]
invoice.update({"l10n_latam_document_type_id":l10n_latam_document_type_id})
return {"success": True}
def create_payment_group(invoice: models.Model, context: dict) -> models.Model:
"""Creates the Payment Group for the given invoice.
Args:
invoice (models.Model): account.move record.
context (dict): Context needed to create the Payment Group.
Returns:
models.Model: account.payment.group record.
"""
_logger.info("Creating payment group for invoice %s", invoice.name)
acc_pay_group = request.env["account.payment.group"].with_user(SUPERUSER_ID)
vals = {
"partner_id": context["default_partner_id"],
"to_pay_move_line_ids": context["to_pay_move_line_ids"],
"company_id": context["default_company_id"],
"state": "draft",
"partner_type": "customer",
}
pay_group = acc_pay_group.with_context(
active_ids=invoice.id, active_model="account.move"
).create(vals)
return pay_group
def create_payments(
payments: list, payment_group: models.Model, invoice: models.Model, context: dict
) -> models.Model:
"""Creates the Payments for the given Payment Group.
Args:
payments (list): list of dictionaries with the payments data.
payment_group (models.Model): account.payment.group record.
invoice (models.Model): account.move record.
context (dict): Context needed to create the Payments.
Returns:
models.Model: account.payment record.
"""
_logger.info(
"Creating payments for payment group of invoice %s",
invoice.name,
)
acc_payment = request.env["account.payment"].with_user(SUPERUSER_ID)
payment_context = {
"active_ids": invoice.ids,
"active_model": "account.move",
"to_pay_move_line_ids": context.get("to_pay_move_line_ids"),
}
payment_context.update(context)
for payment in payments:
payment_vals = {
# inmutable fields
"company_id": invoice.company_id,
"partner_id": invoice.partner_id.id,
"payment_type": "inbound",
"partner_type": "customer",
"payment_group_id": payment_group.id,
# payment specific fields
"journal_id": payment.get("journal"),
"amount": payment.get("amount"),
"currency_id": payment.get("currency"),
"payment_date": payment.get("date"),
"communication": payment.get("communication"),
"payment_method_id": payment.get("payment_method_id"),
}
acc_payment = acc_payment.with_context(**payment_context).create(payment_vals)
return acc_payment
def create_and_post_payments(payments: list, invoice: models.Model) -> models.Model:
"""Creates and post the Payment Group for the given invoice.
* Journal: Mandatory (code, name or id). [journal]
* Currency: Optional (name). Default is invoice's currency. [currency]
* Amount: Optional. Default is invoice's total. [amount]
* Date: Optional. Default is current date. [date]
* Communication: Optional. Default is empty string. [communication]
Args:
payments (list): list of dictionaries with the payments data.
invoice (models.Model): account.move record.
Returns:
models.Model: account.payment.group record.
"""
payments_data = []
for payment in payments:
payment_journal = payment.get("journal")
if not payment_journal:
return {"error": "Missing payment journal"}
payment_journal = (
request.env["account.journal"]
.with_user(SUPERUSER_ID)
.search([("company_id", "=", invoice.company_id.id)])
.filtered(
lambda j, payment_journal=payment_journal: j.code
== str(payment_journal)
or j.name.lower() == str(payment_journal).lower()
or j.id == payment_journal
)
)
currency = payment.get("currency")
if not currency:
currency = invoice.currency_id
else:
currency = (
request.env["res.currency"]
.with_user(SUPERUSER_ID)
.search([("name", "=", currency)])
)
payments_data.append(
{
"journal": payment_journal.id,
"amount": payment.get("amount") or invoice.amount_total,
"currency": currency.id,
"date": payment.get("date") or fields.Date.today(),
"communication": payment.get("communication"),
"payment_method_id": request.env.ref(
"account.account_payment_method_manual_in"
).id,
}
)
payment_context = invoice.with_context(
active_ids=invoice,
active_model="account.move",
).action_account_invoice_payment_group()["context"]
payment_group = create_payment_group(invoice, payment_context)
payments = create_payments(payments_data, payment_group, invoice, payment_context)
# Compute Methods and Post Payments
## Payment Group compute methods
payment_group._compute_payments_amount()
payment_group._compute_matched_amounts()
payment_group._compute_document_number()
payment_group._compute_matched_amount_untaxed()
payment_group._compute_move_lines()
## Individual Payments compute methods
for payment in payment_group.payment_ids:
payment._onchange_partner_id()
payment._compute_reconciled_invoice_ids()
payment.post()
payment_group.post()
return payment_group
def post_invoices(invoices: models.Model) -> models.Model:
"""In case special invoice posting is required or multiple invoices created
Args:
invoices (models.Model): account.move
Returns:
models.Model: account.move
"""
invoices.action_post()
class ApiInvoicePaymentsControllers(http.Controller):
@http.route(
"/account/create/invoice",
type="json",
auth="jwt_cx_api_invoice_payments",
methods=["POST"],
website=True,
)
def create_invoice(self, **kwargs):
"""
Create an invoice from a request.
"""
values = get_invoice_values(kwargs)
if values.get("error"):
return values
invoice = request.env["account.move"].with_user(SUPERUSER_ID).create(values)
if not invoice:
return {"error": "Invoice not created"}
lines = kwargs.get("lines")
if lines:
res = add_lines_to_invoice(invoice, lines, values.get("company_id"))
if res.get("error"):
return res
else:
return {"error": "Missing invoice lines"}
posted_invoices = post_invoices(invoice)
res = {
"result": "Invoice created",
"invoice_id": invoice.id,
"invoice_number": invoice.display_name,
"invoice_date": invoice.invoice_date,
"invoice_amount": invoice.amount_total,
"invoice_currency": invoice.currency_id.name,
"invoice_state": invoice.state,
"invoice_journal": invoice.journal_id.name,
"invoice_partner": invoice.partner_id.name,
"invoice_partner_vat": invoice.partner_id.vat,
}
# Create payments if any
payments = kwargs.get("payments")
if payments:
payment_group = create_and_post_payments(payments, invoice)
if isinstance(payment_group, dict) and payment_group.get("error"):
return payment_group
res["result"] = "Invoice created and payments posted"
res["payment_group_id"] = payment_group.id
res["payment_group_number"] = payment_group.display_name
res["payment_group_amount"] = payment_group.payments_amount
res["payment_group_state"] = payment_group.state
return res
| calyx-servicios/account-invoicing | cx_api_invoice_payments/controllers/main.py | main.py | py | 14,672 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "logging.getLogger",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "odoo.SUPERUSER_ID",
"line_number": 39,
"usage_type": "argument"
},
{
"api_name": "odoo.http.request.env",
"line_number": 38,
"usage_type": "attribute"
},
{
"api_name": "odo... |
35878967311 | '''
▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄ ▄ ▄▄▄▄ ▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄
▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░▌ ▐░▌ ▄█░░░░▌ ▐░░░░░░░░░▌ ▐░░░░░░░░░▌
▐░▌ ▐░█▀▀▀▀▀▀▀█░▌ ▀▀▀▀▀▀▀▀▀█░▌▐░▌ ▐░▌▐░░▌▐░░▌ ▐░█░█▀▀▀▀▀█░▌▐░█░█▀▀▀▀▀█░▌
▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▀▀ ▐░░▌ ▐░▌▐░▌ ▐░▌▐░▌▐░▌ ▐░▌
▐░▌ ▐░█▄▄▄▄▄▄▄█░▌ ▄▄▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄█░▌ ▐░░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌
▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ ▐░░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌
▐░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀▀▀ ▀▀▀▀█░█▀▀▀▀ ▐░░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌
▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░░▌ ▐░▌ ▐░▌▐░▌▐░▌ ▐░▌▐░▌
▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▄▄▄▄█░░█▄▄▄▐░█▄▄▄▄▄█░█░▌▐░█▄▄▄▄▄█░█░▌
▐░░░░░░░░░░░▌▐░▌ ▐░▌▐░░░░░░░░░░░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░▌ ▐░░░░░░░░░▌
▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀
A CLI to automate #100DaysOfX Challenges.
Author: bksahu <bablusahoo16@gmail.com>
'''
print(__doc__)
import subprocess
import inspect, glob
import os, re
import tweepy
import time, argparse
##############################################################
link_to_repo = '' # Set your github repo name
## Check README.md to learn how to acquire your Twitter keys
consumer_key = '' # Put your twitter consumer key
consumer_secret = '' # Put your twitter consumer secret
access_token = '' # Put your twitter access token
access_token_secret = '' # Put your twitter access token secret
###############################################################
def get_cwd():
"""Return the pathname of the Git Repository.
Make sure this script is kept in same git repo.
"""
# get this script's name
filename = inspect.getframeinfo(inspect.currentframe()).filename
# get it's path
path = os.path.dirname(os.path.abspath(filename))
return path
def execute(*arg):
"""Return the stdout_data and executes the command.
Example
-------
>>> sys.stdout.write(execute('git', 'status'))
On branch master
Your branch is up to date with 'origin/master'.
Changes not staged for commit:
(use "git add/rm <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
...
"""
PIPE = subprocess.PIPE
try:
status = subprocess.Popen([*arg], stdout=PIPE, stderr=PIPE)
stdout_data, stderr_data = status.communicate()
except subprocess.CalledProcessError as e:
print(e.output)
return stdout_data
def get_message(link_to_repo=''):
"""Return the commit message and tweet
[Note]: To this work the dir name must be in the form of `Day. LessonName`. Example: `1. Linear Regression`
"""
# get the name of second latest dir created. (First latest dir being created is .git)
latestDir = sorted(glob.glob(os.path.join('.', '*/')), key=os.path.getmtime)[-1]
# get the day
day = re.split(r'\W+', latestDir)[1]
# get the lesson name
lessonName = ''
for idx, word in enumerate(re.split(r'\W+', latestDir)):
if idx > 1:
lessonName += word + ' '
# Set git commit message. Eg: Day 1 - Linear Regression added
commitMessage = 'Day ' + day + ' - ' + lessonName + 'added'
# Set git tweet message. Eg: Day 1 - Linear Regression completed of #100daysofMLcode www.yourRepoLink.com
tweetMessage = 'Day ' + day + ' - ' + lessonName + 'completed of #100DaysOfMLcode ' + link_to_repo
return commitMessage, tweetMessage
def git_operation(commitMessage):
"""Return status and execute git operations in order.
"""
# Check if it is a git repo or not. If not then exit script
status = execute('git', 'status')
if status == b'':
print('fatal: not a git repository (or any of the parent directories): .git\nPut this script inside your Repo')
# Delay for 2 sec
time.sleep(2)
quit()
# git pull
print('Executing git pull...', end=' ')
execute('git', 'pull')
print('Done')
# git add *
print('Executing git add --all...', end=' ')
execute('git', 'add', '.')
print('Done')
# git commit
print('Executing git commit -m...', end=' ')
execute('git', 'commit', '-m', commitMessage)
print('Done')
# git push
print('Executing git push...', end=' ')
execute('git', 'push')
print('Done')
def tweet(tweetMessage):
"""Return status and tweet
"""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
print('Tweeting...', end=' ')
api = tweepy.API(auth)
api.update_status(status = tweetMessage)
print('Done')
if __name__ == "__main__":
# Set path to repo
os.chdir(get_cwd())
# Define argparse
parser = argparse.ArgumentParser(description='A CLI tool to automate #100DaysOfX challenge.')
parser.add_argument('-m','--commit', help='Commit message', required=False)
parser.add_argument('-t','--tweet', help='Tweet message', required=False)
args = vars(parser.parse_args())
if args['commit'] and args['tweet'] is not None:
print('Commit Message: ', args['commit'])
print('Tweet Message: ', args['tweet'])
choice = input("Is it correct [y/n] ?\n>> ")
if choice == 'y':
# retrive the commit message and tweet from args
commitMessage = args['commit']
tweetMessage = args['tweet']
else:
commitMessage = input('Commit Message: ')
tweetMessage = input('Commit Message: ')
else:
commitMessage, tweetMessage = get_message(link_to_repo)
# Do the git operation
git_operation(commitMessage)
# Tweet
tweet(tweetMessage)
# Delay for 2 sec
time.sleep(2)
| bksahu/Lazy100 | Lazy100.py | Lazy100.py | py | 7,191 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "inspect.getframeinfo",
"line_number": 44,
"usage_type": "call"
},
{
"api_name": "inspect.currentframe",
"line_number": 44,
"usage_type": "call"
},
{
"api_name": "os.path.dirname",
"line_number": 46,
"usage_type": "call"
},
{
"api_name": "os.path",
... |
29370143691 | """ohmydog URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from ohmydogApp import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('confimar_asistencia/<int:turno_id>/<str:asistio>',
views.confirmar_asistencia, name= "confirmar_asistencia"),
path('actualizar_libreta/<int:turno_id>', views.actualizar_libreta, name="actualizar_libreta"),
path('autenticacion/', include('autenticacion.urls')),
path('perros/', include('perros.urls')),
path('paseadores_cuidadores/', include('paseadores_cuidadores.urls')),
path('adopcion/', include('adopcion.urls')),
path('turnos/', include('turnos.urls')),
path('pagos/', include('pagos.urls')),
path('cruza/', include('cruza.urls')),
path('donaciones/', include('donaciones.urls')),
path('estadisticas/', include('estadisticas.urls')),
path('perdidos/', include('perdidos.urls')),
path('contactos/', views.ver_contactos, name="contactos"),
path('contactos/editar/telefono', views.editar_telefono, name="contacto_editar_telefono"),
path('contactos/editar/mail', views.editar_mail, name="contacto_editar_mail"),
path('contactos/editar/<str:nombre_red_social>', views.editar_red_social, name="contacto_editar_red_social"),
path('ubicaciones/admin', views.ver_ubicaciones_veterinario, name="ver_ubicaciones_veterinario"),
path('ubicaciones/admin/agregar', views.agregar_ubicacion, name="agregar_ubicacion"),
path('ubicaciones/admin/get', views.get_ubicaciones, name="get_ubicaciones"),
path('ubicaciones/admin/editar/<int:id_veterinaria>', views.editar_ubicacion, name="editar_ubicacion"),
path('ubicaciones/admin/borrar/<int:id_veterinaria>', views.borrar_ubicacion, name="borrar_ubicacion")
]
urlpatterns+=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) | bautimercado/oh-my-dog | ohmydog/ohmydog/urls.py | urls.py | py | 2,566 | python | es | code | 0 | github-code | 1 | [
{
"api_name": "django.urls.path",
"line_number": 23,
"usage_type": "call"
},
{
"api_name": "django.contrib.admin.site",
"line_number": 23,
"usage_type": "attribute"
},
{
"api_name": "django.contrib.admin",
"line_number": 23,
"usage_type": "name"
},
{
"api_name": "... |
33971192494 | import attr
from swh.core.utils import decode_with_escape
from swh.storage import get_storage
from swh.storage.tests.test_postgresql import db_transaction
def headers_to_db(git_headers):
return [[key, decode_with_escape(value)] for key, value in git_headers]
def test_revision_extra_header_in_metadata(swh_storage_backend_config, sample_data):
storage = get_storage(**swh_storage_backend_config)
rev = sample_data.revision
md_w_extra = dict(
rev.metadata.items(),
extra_headers=headers_to_db(
[
["gpgsig", b"test123"],
["mergetag", b"foo\\bar"],
["mergetag", b"\x22\xaf\x89\x80\x01\x00"],
]
),
)
bw_rev = attr.evolve(rev, extra_headers=())
object.__setattr__(bw_rev, "metadata", md_w_extra)
assert bw_rev.extra_headers == ()
assert storage.revision_add([bw_rev]) == {"revision:add": 1}
# check data in the db are old format
with db_transaction(storage) as (_, cur):
cur.execute("SELECT metadata, extra_headers FROM revision")
metadata, extra_headers = cur.fetchone()
assert extra_headers == []
assert metadata == bw_rev.metadata
# check the Revision build from revision_get is the original, "new style", Revision
assert storage.revision_get([rev.id]) == [rev]
| SoftwareHeritage/swh-storage | swh/storage/tests/test_revision_bw_compat.py | test_revision_bw_compat.py | py | 1,342 | python | en | code | 6 | github-code | 1 | [
{
"api_name": "swh.core.utils.decode_with_escape",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "swh.storage.get_storage",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "attr.evolve",
"line_number": 27,
"usage_type": "call"
},
{
"api_name": "... |
38425988516 | import datetime
from django.core.cache import cache
from django.db.models import Q
from common import keys, errors
from social.models import Swiped, Friend
from swiper import config
from user.models import User
def get_recd_list(user):
now = datetime.datetime.now()
max_brith_year = now.year - user.profile.min_dating_age
min_birth_year = now.year - user.profile.max_dating_age
swiped_list = Swiped.objects.filter(uid=user.id).only('sid')
sid_list = [s.sid for s in swiped_list]
sid_list.append(user.id)
users = User.objects.filter(location=user.profile.location,
birth_year__range=[max_brith_year, min_birth_year],
sex=user.profile.dating_sex).exclude(id__in=sid_list)[:20]
data = [user.to_dict() for user in users]
return data
def like(uid, sid):
Swiped.like(uid=uid, sid=sid)
if Swiped.has_like(uid=uid, sid=sid).exists():
Friend.make_friends(uid1=uid, uid2=sid)
return True
return False
def dislike(uid, sid):
Swiped.dislike(uid=uid, sid=sid)
Friend.delete_friend(uid, sid)
return True
def superlike(uid, sid):
Swiped.like(uid=uid, sid=sid)
if Swiped.has_like(uid=uid, sid=sid).exists():
Friend.make_friends(uid1=uid, uid2=sid)
return True
return False
def rewind(user):
key = keys.REWIND_KEY % user.id
cached_rewinded_times = cache.get()
if cached_rewinded_times < config.MAX_REWIND:
cached_rewinded_times += 1
now = datetime.datetime.now()
left_seconds = 86400 - now.hour * 3600 - now.minute * 60 - now.second
cache.set(cached_rewinded_times, timeout=left_seconds)
try:
record = Swiped.objects.filter(uid=user.id).latest('time')
Friend.delete_friend(uid1=user.id, uid2=record.sid)
record.delete()
return 0, None
except Swiped.DoesNotExist:
return errors.NO_RECORD, '无操作记录,无法反悔'
else:
return errors.EXCEED_MAXIMUN_REWIND, '超过最大反悔次数'
def show_friends(user):
friends = Friend.objects.filter(Q(uid1=user.id) | Q(uid2=user.id))
friends_id = []
for friend in friends:
if friend.uid1 == user.id:
friends_id.append(friend.uid2)
else:
friends_id.append(friend.uid1)
users = User.objects.filter(id__in=friends_id)
data = [user.to_dict() for user in users]
return data | cy777/swiper | social/logic.py | logic.py | py | 2,477 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "datetime.datetime.now",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "datetime.datetime",
"line_number": 13,
"usage_type": "attribute"
},
{
"api_name": "user.models.profile",
"line_number": 14,
"usage_type": "attribute"
},
{
"api_name": ... |
1926384493 | import add_parent_path # PyFlakesIgnore
import copy
import logging
import assertions
from StringIO import StringIO
class AssertTestingHelper(object):
def __init__(self,b_raise_exception=True):
self.b_raise_exception = b_raise_exception
def install_hooks(self):
self._orig_assert_logger = assertions.Assertions.logger
# install a logger for assertions module that catches logs in StringWriter self.output
logger = logging.getLogger('TestAssertions')
logger.propagate = False
logger.setLevel(logging.WARNING) # assertions should not log below this level
# remove previous loggers, since we may be getting a logger from previous invocations
for h in copy.copy(logger.handlers): # safer to copy list, since we modify it during iteration
logger.removeHandler(h)
self.output = StringIO()
handler = logging.StreamHandler(self.output)
logger.addHandler(handler)
assertions.Assertions.logger = logger
def uninstall_hooks(self):
assertions.Assertions.logger = self._orig_assert_logger
def get_output(self, b_reset=True):
s = self.output.getvalue()
if b_reset:
self.output.seek(0)
self.output.truncate()
return s
| giltayar/Python-Exercises | tests/assert_testing_helper.py | assert_testing_helper.py | py | 1,326 | python | en | code | 4 | github-code | 1 | [
{
"api_name": "assertions.Assertions",
"line_number": 12,
"usage_type": "attribute"
},
{
"api_name": "logging.getLogger",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "logging.WARNING",
"line_number": 17,
"usage_type": "attribute"
},
{
"api_name": "cop... |
199318416 | import socketserver
import xmltodict
import dicttoxml
import json
import xml.parsers.expat
import ast
HOSTNAME = 'localhost'
PORT = 8182
class MyTCPHandler(socketserver.StreamRequestHandler):
def handle(self):
print(f'connection received: {self.client_address}')
data = self.rfile.readline().strip()
print(f'data received: {data.decode()}')
try:
my_dict=xmltodict.parse(data.decode())
data=json.dumps(my_dict)
print(data)
except xml.parsers.expat.ExpatError:
try:
my_dict = ast.literal_eval(data.decode())
data=dicttoxml.dicttoxml(my_dict)
print(data)
except:
print('Wrong data!')
self.wfile.write(b'Error: wrong data!')
return
try:
self.wfile.write(data.encode())
except AttributeError:
self.wfile.write(data)
if __name__ == "__main__":
with socketserver.TCPServer((HOSTNAME, PORT), MyTCPHandler) as server:
server.serve_forever()
| Vadim-212/python-itstep-dz | dz8_(20.02.20)/server.py | server.py | py | 1,106 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "socketserver.StreamRequestHandler",
"line_number": 14,
"usage_type": "attribute"
},
{
"api_name": "xmltodict.parse",
"line_number": 22,
"usage_type": "call"
},
{
"api_name": "json.dumps",
"line_number": 23,
"usage_type": "call"
},
{
"api_name": "xml... |
13417303225 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed May 8 20:32:44 2019
@author: kamini
"""
import sys
import wave
import matplotlib.pyplot as plt
import numpy as np
import struct
import scipy
import scipy.io.wavfile as wav
from scipy import signal
import pdb
def melFilter(Fs,Nfft):
flow=0
fhigh=Fs/2
initmel=1125*np.log(1+flow/700)
finalmel=1125*np.log(1+fhigh/700)
melfreqlin=np.linspace(initmel,finalmel,22)
melFreq=700*(np.exp(melfreqlin/1125)-1)
melFiltBank=[]
# print(melFreq)
binno=np.floor((Nfft+1)*melFreq/Fs)
for m in range(1,21):
melwind=[]
for k in range(Nfft):
if k<=binno[m-1]:
melwind.append(0)
elif binno[m-1]<k and k<binno[m]:
melwind.append((k-binno[m-1])/(binno[m]-binno[m-1]))
elif k==binno[m]:
melwind.append(1)
elif binno[m]<k and k<binno[m+1]:
melwind.append((k-binno[m+1])/(binno[m]-binno[m+1]))
else:
melwind.append(0)
melFiltBank.append(melwind[:Nfft//2])
return melFiltBank
def dct2(signal):
N=len(signal)
dctout = np.zeros((N))
for k in range(N):
mult = signal*np.cos(np.pi/N*(np.array(range(N))+0.5)*k)
dctout[k] = np.sum(mult)
return dctout*2
def pltfontset(text_size,title_size,label_size, tick_size,legend_size,suptitle_size):
plt.rc('font', size=text_size, weight = 'bold') # controls default text sizes
plt.rc('axes', titlesize=title_size) # fontsize of the axes title
plt.rc('axes', labelsize=label_size) # fontsize of the x and y labels
plt.rc('xtick', labelsize=tick_size) # fontsize of the tick labels
plt.rc('ytick', labelsize=tick_size) # fontsize of the tick labels
plt.rc('legend', fontsize=legend_size) # legend fontsize
plt.rc('figure', titlesize=suptitle_size) # fontsize of the figure title
def displayImage(ax,matrix,figtitle,xaxislabel, yaxislabel, xaxislimit=None, yaxislimit=None):
if xaxislimit==None:
xaxislimit=[0,np.shape(matrix)[1]]
if yaxislimit==None:
yaxislimit=[0,np.shape(matrix)[0]]
ax.imshow(matrix/np.max(matrix),extent=xaxislimit+yaxislimit,cmap='Greys',aspect='auto')
ax.set_xlabel(xaxislabel,fontsize=14, fontweight='bold')
ax.set_ylabel(yaxislabel,fontsize=14, fontweight='bold')
ax.set_title(figtitle,fontsize=20, fontweight='bold')
def energyComp(axisflag,frame,silencethreshold = 0.001,window=np.array([1]),Nfft=0):
if len(window)==1:
window = np.array([1]*len(frame))
squaredSum = np.sum((np.abs(frame)*window)**2)
if axisflag=='time':
energy = squaredSum
elif axisflag=='freq':
if Nfft==0:
print('Specify Nfft')
return None
energy = squaredSum/Nfft*2
if energy < silencethreshold:
energy = silencethreshold
intensity = 10*np.log10(silencethreshold)
else:
intensity = 10*np.log10(energy)
return energy, intensity
def trapezoidalwin(N):
if N>=6:
return np.array([0.25,0.5,0.75]+[1]*(N-6)+[0.75,0.5,0.25])
else:
print('Window length not sufficient')
return 0
def energyContours(wavfilename,contourfolder):
name=wavfilename.split('/')[-1][:-4]
# read wav file and get info sampling rate and noSamles
wavfile=wave.open(wavfilename,'rb')
Fs = wavfile.getframerate()
Ts = 1.0/Fs
noSamples = wavfile.getnframes()
framesizetime = 0.01
frameSize = int(Fs*framesizetime) # noSamples
winsizetime=0.02
winSize = int(Fs*winsizetime) # noSamples
Nfft = 512
noMelCoeff = 20
melFiltBank=melFilter(Fs,Nfft)
# read wav file sample by sample to determine maximum absolute value of the audio signal
maxsigampl = 0
for i in range(noSamples):
sample = wavfile.readframes(1)
sampleval = struct.unpack("<h",sample)
maxsigampl = 1.0*max(maxsigampl,np.abs(sampleval))
wavfile.close()
wavfile=wave.open(wavfilename,'rb')
# initializations
signal=[]
frameseq=[]
timeseq=[]
signal1=[]
energyContour=[]
energy1Contour=[]
intensityContour=[]
intensity1Contour=[]
band2to20EnergyContour=[]
band2to20IntensityContour=[]
band1Contour=[]
band2Contour=[]
band3Contour=[]
band4Contour=[]
sonoContour=[]
sonointenContour=[]
band1overlapContour=[]
band2overlapContour=[]
band3overlapContour=[]
band4overlapContour=[]
band1vaishaliContour=[]
band2vaishaliContour=[]
band3vaishaliContour=[]
band4vaishaliContour=[]
spectralTiltContour=[]
spectrogram=np.empty((Nfft//2,0))
#fid=open(contourfolder+name+'.csv','w')
# window
hamWin = np.hamming(winSize)
# wav file format to read a complete frame
fmt = "<" + "h" * frameSize
# read wav file samples frame by frame where each frame has frameSize samples
#framedata0 = [0]*frameSize
#frameNo = -1 # frame counter
extrabuffer=int(np.ceil(winSize/frameSize/2))
maxwinSize=extrabuffer*2*frameSize # maxwinsize is always even, so we can use maxwinSize//2 safely
frameNo = -extrabuffer
bufferwin=[0]*maxwinSize
# for i in range(-maxwinSize//2,noSamples,frameSize):
for index in range(0,noSamples,frameSize):
frame = wavfile.readframes(frameSize)
if len(frame) != 2*frameSize:
# print('Number of samples in the frame are less than frameSize = '+ str(frameSize))
fmt = "<" + "h" * (len(frame)//2)
data1 = struct.unpack(fmt,frame) # frame is read as string of bytes which is in short hex format 'h' which is 2 byte long
data = data1/maxsigampl # scaling by max amplitude
if len(data) == frameSize:
framedata1 = list(data)
else:
framedata1 = list(data)+[0]*(frameSize-len(data)) #append zeros at the end
frameNo+=1
bufferwin = bufferwin[frameSize:]+framedata1
# print(i,frameNo,len(framedata1),len(bufferwin))
if frameNo<0:
continue
# windata0 = np.array(framedata0+framedata1)
frameseq.append(frameNo)
time=frameNo*framesizetime
timeseq.append(time)
windata0 = bufferwin[maxwinSize//2-winSize//2:maxwinSize//2+(winSize+1)//2]
windata1 = windata0*hamWin
# compute energy
frameEnergy, frameIntensity = energyComp('time',framedata1)
winEnergy, winIntensity = energyComp('time',windata1)
energyContour.append(winEnergy)
intensityContour.append(winIntensity)
# compute spectrum
spectrum = np.fft.fft(windata1, n=Nfft)
halfspectrum = spectrum[:Nfft//2]
magspectrum = (np.abs(np.flip(halfspectrum)))*np.sqrt(2.0/Nfft) # only for plotting spectrogram as image, don't use elsewhere
magspectrum = np.clip(magspectrum,0.0001,None)
spectrogram=np.hstack((spectrogram,20*np.log10(magspectrum[:,np.newaxis])))
# compute spectral band energy
band1 = halfspectrum[0*Nfft//Fs:500*Nfft//Fs]
band2 = halfspectrum[500*Nfft//Fs:1000*Nfft//Fs]
band3 = halfspectrum[1000*Nfft//Fs:2000*Nfft//Fs]
band4 = halfspectrum[2000*Nfft//Fs:4000*Nfft//Fs]
energy, intensity = energyComp('freq',halfspectrum,0.001,trapezoidalwin(len(halfspectrum)),Nfft=Nfft)
band1energy, band1intensity = energyComp('freq',band1,0.0005,trapezoidalwin(len(band1)),Nfft=Nfft)
band2energy, band2intensity = energyComp('freq',band2,0.0005,trapezoidalwin(len(band2)),Nfft=Nfft)
band3energy, band3intensity = energyComp('freq',band3,0.0005,trapezoidalwin(len(band3)),Nfft=Nfft)
band4energy, band4intensity = energyComp('freq',band4,0.0005,trapezoidalwin(len(band4)),Nfft=Nfft)
energy1Contour.append(energy)
intensity1Contour.append(intensity)
band1Contour.append(band1intensity)
band2Contour.append(band2intensity)
band3Contour.append(band3intensity)
band4Contour.append(band4intensity)
# compute sonorant band energy
sonorantBand=halfspectrum[300*Nfft//Fs:2300*Nfft//Fs] #0.3K-2.3K
sonorantenergy, sonorantintensity = energyComp('freq',sonorantBand,0.0005,trapezoidalwin(len(sonorantBand)),Nfft=Nfft)
sonoContour.append(sonorantenergy)
sonointenContour.append(sonorantintensity)
# compute energy in bark bands 2 to 20 as per rosenberg AuToBI system
band2to20=halfspectrum[200*Nfft//Fs:6500*Nfft//Fs] #0.3K-2.3K
band2to20energy, band2to20intensity = energyComp('freq',band2to20,0.0005,trapezoidalwin(len(band2to20)),Nfft=Nfft)
band2to20EnergyContour.append(band2to20energy)
band2to20IntensityContour.append(band2to20intensity)
# compute energy across overlapping formant bands
overlapBand1=halfspectrum[250*Nfft//Fs:1200*Nfft//Fs] #250-1200Hz
overlapBand2=halfspectrum[800*Nfft//Fs:3200*Nfft//Fs] #800-3200Hz
overlapBand3=halfspectrum[1700*Nfft//Fs:3800*Nfft//Fs] #1700-3800Hz
overlapBand4=halfspectrum[3000*Nfft//Fs:4700*Nfft//Fs] #3000-4700Hz
overlapband1energy, overlapband1intensity = energyComp('freq',overlapBand1,0.0005,trapezoidalwin(len(overlapBand1)),Nfft=Nfft)
overlapband2energy, overlapband2intensity = energyComp('freq',overlapBand2,0.0005,trapezoidalwin(len(overlapBand2)),Nfft=Nfft)
overlapband3energy, overlapband3intensity = energyComp('freq',overlapBand3,0.0005,trapezoidalwin(len(overlapBand3)),Nfft=Nfft)
overlapband4energy, overlapband4intensity = energyComp('freq',overlapBand4,0.0005,trapezoidalwin(len(overlapBand4)),Nfft=Nfft)
band1overlapContour.append(overlapband1intensity)
band2overlapContour.append(overlapband2intensity)
band3overlapContour.append(overlapband3intensity)
band4overlapContour.append(overlapband4intensity)
# compute disjoint formant bands as per Vaishali thesis
vaishaliBand1=halfspectrum[60*Nfft//Fs:400*Nfft//Fs] #60-400Hz
vaishaliBand2=halfspectrum[400*Nfft//Fs:2000*Nfft//Fs] #400-2000Hz
vaishaliBand3=halfspectrum[2000*Nfft//Fs:5000*Nfft//Fs] #2000-5000Hz
vaishaliBand4=halfspectrum[5000*Nfft//Fs:8000*Nfft//Fs] #5000-8000Hz
vaishaliband1energy, vaishaliband1intensity = energyComp('freq',vaishaliBand1,0.0005,trapezoidalwin(len(vaishaliBand1)),Nfft=Nfft)
vaishaliband2energy, vaishaliband2intensity = energyComp('freq',vaishaliBand2,0.0005,trapezoidalwin(len(vaishaliBand2)),Nfft=Nfft)
vaishaliband3energy, vaishaliband3intensity = energyComp('freq',vaishaliBand3,0.0005,trapezoidalwin(len(vaishaliBand3)),Nfft=Nfft)
vaishaliband4energy, vaishaliband4intensity = energyComp('freq',vaishaliBand4,0.0005,trapezoidalwin(len(vaishaliBand4)),Nfft=Nfft)
band1vaishaliContour.append(vaishaliband1intensity)
band2vaishaliContour.append(vaishaliband2intensity)
band3vaishaliContour.append(vaishaliband3intensity)
band4vaishaliContour.append(vaishaliband4intensity)
# spectral tilt using MFCC
mellogenergy=[]
if np.all(halfspectrum==0.0):
spectralTilt=0.0
else:
for mb in range(noMelCoeff):
melspectrum=halfspectrum*melFiltBank[mb]
melenergy, melintensity = energyComp('freq',melspectrum,0.0005,Nfft=Nfft)
mellogenergy.append(melintensity)
dctlist=scipy.fft.dct(mellogenergy)
spectralTilt=dctlist[1]
spectralTiltContour.append(spectralTilt)
# framedata0 = framedata1
signal1.append(framedata1)
signal.extend(framedata1)
# fid.write(energyContour,intensityContour,sonoContour,sonointenContour, \
#band1Contour,band2Contour,band3Contour,band4Contour, \
#band1overlapContour,band2overlapContour,band3overlapContour,band4overlapContour, \
#band1vaishaliContour,band2vaishaliContour,band3vaishaliContour,band4vaishaliContour, \
#spectralTiltContour+'\n')
wavfile.close()
## save all the contours in respective folders
#np.savetxt(energyfolder+name+'full.txt',(energyContour,intensityContour),fmt='%7.5f')
#np.savetxt(energyfolder+name+'sono.txt',(sonoContour),fmt='%7.5f')
#np.savetxt(spectrumBalBandfolderchrist+name+'.txt',(band1Contour,band2Contour,band3Contour,band4Contour),fmt='%7.5f')
#np.savetxt(spectrumBalBandfolderoverlap+name+'.txt',(band1overlapContour,band2overlapContour,band3overlapContour,band4overlapContour),fmt='%7.5f')
#np.savetxt(spectrumBalBandfoldervaishali+name+'.txt',(band1vaishaliContour,band2vaishaliContour,band3vaishaliContour,band4vaishaliContour),fmt='%7.5f')
#np.savetxt(spectralTiltfolder+name+'.txt',spectralTiltContour,fmt='%7.5f')
np.savetxt(contourfolder+name+'_others.csv',list(zip(frameseq,timeseq,energyContour,intensityContour,\
sonoContour,sonointenContour,band2to20EnergyContour,band2to20IntensityContour, \
band1Contour,band2Contour,band3Contour,band4Contour, \
band1overlapContour,band2overlapContour,band3overlapContour,band4overlapContour, \
band1vaishaliContour,band2vaishaliContour,band3vaishaliContour,band4vaishaliContour, \
spectralTiltContour)),delimiter=',',fmt='%7.5f',header="frameNo,time,energy,"+\
"intensity,sonorantEnergy,sonorantIntensity,band2to20Energy,band2to20Intensity,band1Intensity,band2Intensity,"+\
"band3Intensity,band4Intensity,band1overlapInten,band2overlapInten,band3overlapInten,"+\
"band4overlapInten,band1vaishaliInten,band2vaishaliInten,band3vaishaliInten,"+\
"band4vaishaliInten,spectralTilt")
np.savetxt(contourfolder+name+'_spectrogram.txt',spectrogram,fmt='%7.5f')
| sujoyrc/multimodal_raga_analysis | Code/Kamini_Code/energyContoursfunc.py | energyContoursfunc.py | py | 13,877 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "numpy.log",
"line_number": 22,
"usage_type": "call"
},
{
"api_name": "numpy.log",
"line_number": 23,
"usage_type": "call"
},
{
"api_name": "numpy.linspace",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "numpy.exp",
"line_number": 25,... |
8320557537 | #! /usr/bin/env python3
import re
from functools import partial
DEFAULT_ENCODING = "utf-8"
def pre_repl(self, p, match):
string = match.group()[2:-1] # Rule: ${var}
#print("Found: {0:s}".format(string))
if ":" in string:
filename = string.split(":")[1] + ".html"
self.create_page(filename, output=None, parent=p)
elif string in self:
return self[string]
return ""
class SimpleTemplate(dict):
pattern_matcher = None
include_patter_matcher = None
def __get_pattern_matcher(self):
if self.pattern_matcher is None:
self.pattern_matcher = re.compile("\$\{(?:f:)?\w+\}")
return self.pattern_matcher
def __get_include_pattern_matcher(self):
if self.include_patter_matcher is None:
self.include_patter_matcher = re.compile("\$\{f:\w+\}")
return self.include_patter_matcher
def __process_template_loop(self, pm, repl, t, dest):
"""Managing read/write cycles.
pm: tags pattern
repl: replacement function
t: input template file object
dest: output file object
"""
ipm = self.__get_include_pattern_matcher()
do_replace = partial(pm.sub, repl)
do_write = dest.write
line = t.readline()
while line != '':
# Check include tag elements
elems, patts = ipm.split(line), ipm.findall(line)
if len(elems) > 1:
# Include tags found: split and process sequentially
# due to missing process of file tag's previous sections
for x in range(0, len(elems)):
do_write(do_replace(elems[x]))
if x < len(elems) - 1:
do_write(do_replace(patts[x]))
else:
# No file tags: process entire line
dest.write(do_replace(line)) # TODO: ERROR ERROR ERROR
line = t.readline()
def __process_template(self, input, pm, p):
"""Template reading and transformation initialization."""
with open(input, "r", encoding=DEFAULT_ENCODING) as t:
repl = partial(pre_repl, self, p)
self.__process_template_loop(pm, repl, t, p)
def create_page(self, input="base_template.html", output="test.html", parent=None):
"""Make transformation from input to output.
Using recursion in order to write template transformations.
input: tamplate fila name
output: output of tree tranformation. Used only on root
parent: file object reference for no-root nodes
"""
pm = self.__get_pattern_matcher()
if parent == None:
# Start of template tree: new file creation
with open(output, "w", encoding=DEFAULT_ENCODING) as f:
self.__process_template(input, pm, f)
else:
# Go deep into the tree: use existing open file
self.__process_template(input, pm, parent)
if __name__ == '__main__':
e = SimpleTemplate(
title="Pippo",
body='Pluto',
header='Template generator',
par="This is a test",
secpar="This is a second test",
font="tahoma",
fontsize="11px"
)
e.create_page(input="base_template.html", output="test.html")
| lmlwci0m/gen-scripts | htmlgen.py | htmlgen.py | py | 3,626 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "re.compile",
"line_number": 31,
"usage_type": "call"
},
{
"api_name": "re.compile",
"line_number": 36,
"usage_type": "call"
},
{
"api_name": "functools.partial",
"line_number": 49,
"usage_type": "call"
},
{
"api_name": "functools.partial",
"line... |
16906652773 | import amino
from tabulate import tabulate
from src.utils import Login
from src.utils import Communities
from src.utils import Chats
from src.scripts.raid_box import RaidBox
from src.scripts.activity_box import ActivityBox
from src.scripts.profile_box import ProfileBox
from src.scripts.chat_box import ChatBox
from src.scripts.other_box import OtherBox
from src.scripts.account_box import AccountBox
import shutil, subprocess, sys
def print_centered(text):
console_width, _ = shutil.get_terminal_size()
padding = (console_width - len(text)) // 2
print(' ' * padding + text)
def input_centered(prompt):
console_width, _ = shutil.get_terminal_size()
prompt_lines = prompt.split('\n')
padding = (console_width - max(len(line) for line in prompt_lines)) // 2
centered_prompt = '\n'.join(' ' * padding + line for line in prompt_lines)
user_input = input(centered_prompt)
return user_input
def clear_console():
if sys.platform.startswith('win'):
_ = subprocess.call('cls', shell=True)
elif sys.platform.startswith('linux') or sys.platform.startswith('darwin'):
_ = subprocess.call('clear', shell=True)
else:
print('Unsupported platform. Cannot clear console.')
import colorama
from colorama import init, Fore
colorama.init()
class MainApp:
def start(self):
Yellow = Fore.YELLOW
Reset = Fore.RESET
self.client = amino.Client()
Login.login(self.client)
self.sub_client = amino.SubClient(
comId=Communities.communities(
self.client), profile=self.client.profile)
while True:
clear_console()
try:
print(f'''
[{Yellow}1{Reset}] Raid Box By {Yellow}zeviel{Reset}
[{Yellow}2{Reset}] Activity Box By {Yellow}zeviel{Reset}
[{Yellow}3{Reset}] Profile Box By {Yellow}Savier{Reset}
[{Yellow}4{Reset}] Chat Box By {Yellow}Azayakasa{Reset}
[{Yellow}5{Reset}] Other Box By {Yellow}Auroraflow{Reset} & {Yellow}Roger{Reset}
[{Yellow}6{Reset}] Account Box By {Yellow}Morphine{Reset} & {Yellow}Moriarti{Reset}
''')
select = int(input_centered(f"[{Yellow}Select{Reset}] {Yellow}->{Reset} "))
if select == 1:
clear_console()
RaidBox(self.client, self.sub_client).start()
elif select == 2:
clear_console()
ActivityBox(self.sub_client).start()
elif select == 3:
clear_console()
ProfileBox(self.client, self.sub_client).start()
elif select == 4:
clear_console()
ChatBox(self.client, self.sub_client).start()
elif select == 5:
clear_console()
OtherBox(self.client, self.sub_client).start()
elif select == 6:
clear_console()
AccountBox(self.client).start()
except Exception as e:
clear_console()
print(e) | TheCuteOwl/Amino-Boxes-But-Better | src/service.py | service.py | py | 2,768 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "shutil.get_terminal_size",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "shutil.get_terminal_size",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "sys.platform.startswith",
"line_number": 28,
"usage_type": "call"
},
{
"api_nam... |
4691161197 | import os
import sys
import subprocess
from setuptools import find_packages, setup
from setuptools.command.build_py import build_py
class Build(build_py):
def run(self):
make_runsolver = ["make", "runsolver"]
runsolver_dir = os.path.join(
os.path.dirname(__file__), "runsolver", "runsolver"
)
if subprocess.call(make_runsolver, cwd=runsolver_dir) != 0:
sys.exit(-1)
build_py.run(self)
setup(
name="runsolver",
version="3.4.0",
packages=find_packages(),
cmdclass={"build_py": Build},
entry_points={"console_scripts": ["runsolver=runsolver:run"]},
package_data={"runsolver": ["runsolver/*"]},
)
| rkkautsar/runsolver-py | setup.py | setup.py | py | 690 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "setuptools.command.build_py.build_py",
"line_number": 9,
"usage_type": "name"
},
{
"api_name": "os.path.join",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 12,
"usage_type": "attribute"
},
{
"api_name": "os.path... |
71509372195 | import time
import datetime
def convert_mil(ms):
"""Converts a time in milliseconds from midnight format into a
compatible time format of HH:MM:SS, currently the time provided
in milliseconds is floored to avoid having times in the future.
"""
# Floor the results to avoid rounding errors for seconds entries
try:
ms = int(float(ms))
hour = (ms / 3600000) % 24
min = (ms / 60000) % 60
sec = (ms / 1000) % 60
return datetime.time(hour, min, sec)
except ValueError:
return None
def convert_sec(sec):
"""Converts a time in seconds from midnight format into compatible
time format of HH:MM:SS
"""
# Ensure the value is an integer
try:
sec = int(float(sec))
hour = (sec / 3600) % 24
min = (sec / 60) % 60
sec = sec % 60
return datetime.time(hour, min, sec)
except ValueError:
return None
def convert_str(time):
"""Convers a time that is a string of the format HH:MM:SS into a compatible
time format object of HH:MM:SS
"""
try:
return datetime.datetime.strptime(time, '%H:%M:%S').time()
except ValueError:
return None
def float_to_int(value):
"""Converts a string representation of a float value to an int
FLOORING the value (e.g. 2.99 becomes 2)
"""
try:
return int(float(value))
except ValueError:
return None
def market_hours(time):
"""Determines if the time provide is within the market operating hours,
which are usually between 9:30 and 16:00.
:param time: A datetime.time object of the time to check
"""
open = datetime.time(9, 30, 00)
close = datetime.time(16, 00, 00)
try:
if time < open or time > close:
return False
return True
except:
return False
def time_delta(before, after):
"""Determines the number of seconds difference between two times.
:param before: A datetime.time object of the time before
:param after: A datetime.time object of the time after
"""
# Create a placeholder date
date = datetime.datetime(1984, 1, 1)
# Get the time delta between the two times
before_time = date.combine(date, before)
after_time = date.combine(date, after)
return (after_time - before_time).seconds
def add_seconds(time, seconds):
"""Adds the specified number of seconds to the time provided and returns a
datetime.time object
:param time: A datetime.time object of the time to add seconds to.
:param seconds: An integer, the number of seconds to add
"""
# Create a placeholder date
date = datetime.datetime(1984, 1, 1)
# Get the new time
orig_time = date.combine(date, time)
return (orig_time + datetime.timedelta(0, seconds)).time()
| gnu-user/finance-research | scripts/util.py | util.py | py | 2,825 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "datetime.time",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "datetime.time",
"line_number": 34,
"usage_type": "call"
},
{
"api_name": "datetime.datetime.strptime",
"line_number": 44,
"usage_type": "call"
},
{
"api_name": "datetime.datet... |
16751302675 | """RedLogo PERSONAL GPU fan speed curve tuning project
on Linux Ubuntu, GPU: GTX 1080 Ti"""
import matplotlib.pyplot as plt
import numpy as np
old_profile_temperature = np.array([])
old_profile_fan_speed = np.array([])
new_profile_temperature = np.array([])
new_profile_fan_speed = np.array([])
fan_speed_curve_file_current = open('fan-speed-curve-current.csv', 'r')
for line in fan_speed_curve_file_current:
line = line.strip()
if line:
line_split = line.split(',')
old_profile_temperature = np.append(old_profile_temperature, line_split[0])
old_profile_fan_speed = np.append(old_profile_fan_speed, line_split[1])
fan_speed_curve_file_current.close()
fan_speed_curve_file_new_design = open('fan-speed-curve-new-design.csv', 'r')
for line in fan_speed_curve_file_new_design:
line = line.strip()
if line:
line_split = line.split(',')
new_profile_temperature = np.append(new_profile_temperature, line_split[0])
new_profile_fan_speed = np.append(new_profile_fan_speed, line_split[1])
fan_speed_curve_file_new_design.close()
fig = plt.figure()
plt.plot(old_profile_temperature, old_profile_fan_speed, 'ro-', ms=5)
plt.plot(new_profile_temperature, new_profile_fan_speed, 'gx-', ms=5)
plt.title('RedLogo Linux Ubuntu GPU fan speed curves')
plt.legend(['current fan speed profile', 'fan speed profile to be deployed'])
horizontal_lines = np.linspace(0, 100, 21)
for item in horizontal_lines:
plt.axhline(item, color='grey', lw=0.5)
vertical_lines = np.linspace(0, 80, 41)
for item in vertical_lines:
plt.axvline(item, color='grey', lw=0.5)
plt.xticks(np.arange(0, 82, 2))
plt.yticks(np.arange(0, 105, 5))
fig_manage = plt.get_current_fig_manager()
fig_manage.window.setGeometry(0, 0, 1500, 900)
plt.show()
| redlogo/Linux-Ubuntu-GPU-fan-speed-curve-control | GPU-fan-control-tune-curve.py | GPU-fan-control-tune-curve.py | py | 1,777 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "numpy.array",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "numpy.array",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "numpy.array",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "numpy.array",
"line_number": 9,
... |
72680595875 | from .cart import Cart
import json
from django.shortcuts import render, HttpResponse, redirect, get_object_or_404
from django.contrib import messages
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.views.generic import View
import time
from math import ceil
from .models import Product, Category, District, Subdistrict, Subcategory,Order,OrderItem,ProductReview
from .forms import ProductForm, ProductUpForm, VariantForm,ContactForm
from notifications.signals import notify
from django.views import generic, View
from django.urls import reverse_lazy
from django.db.models import Q
class CreateProdView(generic.CreateView):
model = Product
form_class = ProductForm
template_name = 'product/productcreate.html'
def form_valid(self, form):
form.instance.user = self.request.user
messages.success(self.request, 'Successfully Created Your Product.')
messages.success(self.request, ' Now Add Subdistrict and Subcategory!')
return super().form_valid(form)
def get_success_url(self):
id = self.object.id
# user = self.request.user
# us = User.objects.all()
# for i in us:
# try:
# j = i.tuitionclass
# except:
# j = None
# if j:
# if receiverchoose(j, self.object):
# receiver = i
# if receiver != user:
# notify.send(user, recipient=receiver, level='success', verb="is searching for a teacher for "+str(self.object.medium)+" for " + str(
# self.object.class_in.all().first())+" for subject " + str(self.object.subject.all().first()) + f''' <a class =" btn btn-primary btn-sm " href="/posts/post/{self.object.sno}">go</a> ''')
# kwargs={'pk': id}
return reverse_lazy('product:addsub', kwargs={'pk': id})
def addsubdistrict(request, pk):
prod = Product.objects.get(id=pk)
if request.method == 'POST':
form = ProductUpForm(request.POST, instance=prod)
if form.is_valid():
sub = form.cleaned_data['subdistrict']
subcheck = Subdistrict.objects.filter(
district=prod.district).filter(name=sub)
if not subcheck:
Subdistrict.objects.create(name=sub, district=prod.district)
sub = form.cleaned_data['subcategory']
subchecks = Subcategory.objects.filter(
category=prod.category).filter(name=sub)
if not subchecks:
Subcategory.objects.create(name=sub, category=prod.category)
form.save()
messages.success(request, 'Product Created Successfully. ')
messages.success(request, 'Add More Varint! ')
return redirect(f'/variant/{prod.id}/')
else:
subdistrict = Subdistrict.objects.filter(district=prod.district)
subcategory = Subcategory.objects.filter(category=prod.category)
form = ProductUpForm(
instance=prod, data_list=subdistrict, c_list=subcategory)
context = {
'form': form,
}
return render(request, 'product/productcreate.html', context)
class EditProdView(generic.UpdateView):
model = Product
form_class = ProductForm
template_name = 'product/productcreate.html'
def get_success_url(self):
id = self.kwargs['pk']
return reverse_lazy('product:addsub', kwargs={'pk': id})
def delete(request,id):
prod=Product.objects.get(id=id)
print(prod.name)
prod.delete()
return redirect('product:myprod')
def variantadd(request,id):
if request.method=="POST":
form=VariantForm(request.POST,request.FILES)
parent=Product.objects.get(id=id)
if form.is_valid():
image=form.cleaned_data['image']
print(image)
obj=form.save(commit=False)
obj.user=request.user
obj.parent=parent
obj.category=parent.category
obj.subcategory=parent.subcategory
obj.district=parent.district
obj.subdistrict=parent.subdistrict
obj.phone=parent.phone
obj.save()
messages.success(request, "Successfully added a varinat!")
else:
form=VariantForm()
return render(request,'product/productcreate.html',{'form':form,'pass':True})
def search(request):
if request.method == "POST":
query = request.POST['q']
print(query)
if query:
queryset = (Q(name__icontains=query)) | (
Q(specifications__icontains=query)) | (Q(category__name__icontains=query)) | (Q(district__name__icontains=query)) | (Q(subcategory__icontains=query)) | (Q(subdistrict__icontains=query)) | (Q(parent__name__icontains=query))
results = Product.objects.filter(queryset).order_by('-timeStamp').distinct()
else:
results = []
# for re in results:
# print(re.name)
context= {'query':query,'results':results}
else:
context= {}
return render(request, 'product/search.html',context)
def productshow(request):
cart = Cart(request)
category = Category.objects.all().order_by('name')
district = District.objects.all().order_by('name')
if request.method == "POST":
dis = request.POST['district_i']
cat = request.POST['category_i']
inStock = request.POST.get('inStock')
price_from = request.POST.get('price_from', 1)
price_to = request.POST.get('price_to', 1000000)
sorting = request.POST.get('sorting',)
if not price_from:
price_from=1
if not price_to:
price_to=1000000
if dis or cat:
queryset = (Q(district__name__icontains=dis)) & (
Q(category__name__icontains=cat))
results = Product.objects.filter(
queryset).filter(price__gte=price_from).filter(price__lte=price_to).order_by('-timeStamp').distinct()
else:
results = []
if inStock:
results=results.filter(available_quantity__gte=1)
params = {
'results': results.order_by(sorting),
'district': district,
'category': category,
'dis': dis,
'cat': cat,
'cart': cart,
'price_to':price_to,
'price_from':price_from,
'inStock':inStock,
'sorting':sorting
}
else:
prod = Product.objects.all()
n = len(prod)
nSlides = ceil(n/4)
allProds = []
catprods = Product.objects.values(
'category', 'id').order_by('-timeStamp')
# print(catprods)
cats = {item['category'] for item in catprods}
for cat in cats:
prod = Product.objects.filter(category=cat).filter(parent=None).order_by('-timeStamp')
for p in prod:
if cart.has_product(p.id):
p.in_cart=True
else:
p.in_cart=False
n = len(prod)
nSlides = ceil(n / 4)
allProds.append([prod, range(1, nSlides), nSlides])
params = {
'allProds': allProds,
'category': category,
'district': district,
'cart': cart
}
return render(request, 'product/index.html', params)
def index(request):
product = Product.objects.all()
product_list = list(product.values(
'user__username', 'name', 'district__name'))
context = {}
context["product"] = json.dumps(product_list)
return render(request, 'About.html', context)
import random
def prod_detail(request, id):
prod = Product.objects.get(id=id)
if request.method=='POST':
stars=request.POST['stars']
content=request.POST['content']
ProductReview.objects.create(user=request.user,product=prod,stars=stars,content=content)
cart = Cart(request)
related_products=list(prod.category.category_set.filter(parent=None).exclude(id=prod.id))
if len(related_products) >= 3:
related_products=random.sample(related_products,3)
if cart.has_product(prod.id):
prod.in_cart=True
else:
prod.in_cart=False
return render(request, 'product/detail.html', {'prod': prod, 'cart': cart,'related_products':related_products})
from django.conf import settings
def cart_detail(request):
cart = Cart(request)
pub_key=settings.STRIPE_API_KEY_PUBLISHABLE
productsstring = ''
for item in cart:
product = item['product']
url='/prod/%s/' % product.id
b = "{'id':'%s', 'title':'%s','price':'%s','image':'%s','quantity':'%s', 'total_price':'%s','url':'%s','available_quantity':'%s'}," % (
product.id, product.name, product.price, product.image.url, item['quantity'], item['total_price'],url,product.available_quantity)
productsstring = productsstring + b
context = {
'cart': cart,
'pub_key':pub_key,
'productsstring': productsstring
}
return render(request, 'product/cart.html', context)
def success(request):
return render(request, 'product/success.html')
def your_products(request):
prod=Product.objects.filter(user=request.user).order_by('timeStamp')
context={
'prod':prod,
}
return render(request,'product/your_products.html',context)
def product_orders(request):
items=OrderItem.objects.filter(owner=request.user).order_by('-date_of_order')
context={
'items':items
}
return render(request,'product/product_orders.html',context)
import datetime
# TOKEN generator import
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import EmailMessage
from django.template.loader import render_to_string
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
def items_shipped(request,id):
item=OrderItem.objects.get(id=id)
item.status="Shipped"
item.shipped_date=datetime.datetime.now()
item.save()
orderid=item.order.id
user=request.user
current_site = get_current_site(request)
mail_subject = 'Your product Has Shipped'
message = render_to_string('product/order_shipped.html', {
'user': user,
'domain': current_site.domain,
'orderid':orderid,
'item':item,
})
to_email = item.order.user.email
email = EmailMessage(
mail_subject, message, to=[to_email]
)
email.send()
print(item.order.user.email)
messages.success(request,'Status CHanged to shipped!')
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def items_arrived(request,id):
item=OrderItem.objects.get(id=id)
item.status="Arrived"
item.shipped_date=datetime.datetime.now()
item.save()
messages.success(request,'Status CHanged to Arrived!')
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def contact(request):
if request.method=='POST':
form=ContactForm(request.POST)
if form.is_valid():
form.save()
messages.success(request,'Successfully Submitted')
return redirect('/')
else:
form=ContactForm()
context={
'form':form
}
return render(request,'product/contact_us.html',context) | Fahad-CSE16/SellOrBuy | product/views.py | views.py | py | 11,500 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "django.views.generic.CreateView",
"line_number": 18,
"usage_type": "attribute"
},
{
"api_name": "django.views.generic",
"line_number": 18,
"usage_type": "name"
},
{
"api_name": "models.Product",
"line_number": 19,
"usage_type": "name"
},
{
"api_name... |
17780386462 | """fixed category model
Revision ID: 35b0f0000908
Revises: 6cfa0419ad9a
Create Date: 2021-10-08 11:51:06.628030
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '35b0f0000908'
down_revision = '6cfa0419ad9a'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint('categories_user_id_fkey', 'categories', type_='foreignkey')
op.drop_column('categories', 'user_id')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('categories', sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=False))
op.create_foreign_key('categories_user_id_fkey', 'categories', 'users', ['user_id'], ['id'])
# ### end Alembic commands ###
| ywakili18/HIITdontQUIT | migrations/versions/35b0f0000908_fixed_category_model.py | 35b0f0000908_fixed_category_model.py | py | 872 | python | en | code | 2 | github-code | 1 | [
{
"api_name": "alembic.op.drop_constraint",
"line_number": 21,
"usage_type": "call"
},
{
"api_name": "alembic.op",
"line_number": 21,
"usage_type": "name"
},
{
"api_name": "alembic.op.drop_column",
"line_number": 22,
"usage_type": "call"
},
{
"api_name": "alembic.... |
39202685667 | import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import dash_table
import dash_html_components as html
from app.models import Wineset
from app.plotlydash.results import Result
from app import mongo
import math
def get_log(value, flag= False):
log_value = math.log10(value)
return int(log_value) if flag else log_value
def get_navbar():
# Navbar
navbar = dbc.NavbarSimple(className="nav nav-pills", children=[
dbc.NavItem(
dbc.NavLink("Home", href="/index")
)
])
return navbar
def create_dashboard(server):
dash_app = dash.Dash(server=server,
routes_pathname_prefix='/dashapp/',
external_stylesheets=[
dbc.themes.LUX,
'/static/style.css']
)
wineset = Wineset(mongo.cx)
data = wineset.get_formatted_dataframe()
# Input
inputs = dbc.FormGroup([
html.H4("Selecione o País"),
dcc.Dropdown(id="country", options=[{"label":x,"value":x} for x in Wineset.get_countrylist(data)], value="World")
])
dash_app.layout = dbc.Container(fluid=True, children=[
get_navbar(),
dbc.Row([
dbc.Col(md=2, children=[
inputs,
html.Br(),html.Br(),html.Br(),
html.Div(id="output-panel")
]),
dbc.Col(md=10, children=[
dbc.Col(html.H4("Catálogo Wine"), width={"size":6,"offset":3}),
dbc.Tabs(className="nav", children = [
dbc.Tab(
create_first_data_table('database-table', data),
label="Tabela de Dados"),
dbc.Tab(children = [
dcc.Graph(id='wine_score_graph'),
dcc.Slider(
id='price_slider',
min=0,
max=get_log(data['lowest_price'].max()),
value=get_log(data['lowest_price'].max()),
marks = {i: '{}'.format(10 ** i) for i in range(get_log(data['lowest_price'].max(),True)+1)},
step= 0.01
),
html.Div(id='slider_output_container')],
label="Gráfico Avaliação x Preço")
]),
]),
]),
])
init_callbacks(dash_app, data)
return dash_app.server
def create_first_data_table(table_id, df):
"""Create Dash datatable from Pandas DataFrame."""
filtered_df = df[['Nome', 'country', 'grape', 'classification', 'lowest_price', 'Score']]
table = dash_table.DataTable(
id = table_id,
style_data = {
'whitespace':'normal',
'height':'auto',
},
columns=[{
"name": i,
"id": i,
"presentation": "markdown"} for i in filtered_df.columns],
data=filtered_df.to_dict('records'),
filter_action="native",
sort_action="native",
sort_mode='native',
page_size=50
)
#table = dbc.Table.from_dataframe(df, striped=True, bordered=True, hover=True)
return table
def init_callbacks(dash_app, df):
result = Result(df)
@dash_app.callback(
Output("database-table","data"),
[Input('country', 'value')])
def create_data_table(country):
print("Criando tabela de dados para o país:", country)
"""Create Dash datatable from Pandas DataFrame."""
filtered_df = df[['Nome', 'country', 'grape', 'classification', 'lowest_price', 'Score']]
countrydf = filtered_df if country == 'World' else df.loc[(df.country == country)]
data=countrydf.to_dict('records')
return data
@dash_app.callback(
Output("wine_score_graph","figure"),
[Input('country', 'value'),
Input('price_slider', 'value')])
def update_graph(country, value):
return result.plot_prices_byscore(country, 10 ** value)
@dash_app.callback(
Output("price_slider","max"),
[Input('country', 'value')])
def update_slider(country):
return get_log(result.recalibrate_slider(country))
@dash_app.callback(
Output("slider_output_container","children"),
[Input('price_slider', 'value')])
def show_slider_value(value):
return 'Preço Máximo: "${:20,.2f}"'.format(10 ** value)
#def plot_prices(df):
# result = Result(df)
# print("Estou no plot_prices")
# print(df['vivino_score'].head())
#
# return result.plot_prices_byscore()
| gmendonc/winescrapper | mvp/app/plotlydash/dashboard.py | dashboard.py | py | 4,756 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "math.log10",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "dash_bootstrap_components.NavbarSimple",
"line_number": 18,
"usage_type": "call"
},
{
"api_name": "dash_bootstrap_components.NavItem",
"line_number": 19,
"usage_type": "call"
},
{
... |
70721287074 | # -*- coding: utf-8 -*-
"""
Created on Wed May 8 14:10:24 2019
@author: iremn
"""
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from tflearn.data_utils import image_preloader
import numpy as np
X, Y = image_preloader('dataset', image_shape=(256, 256), mode='folder', categorical_labels=True, normalize=True, files_extension = ['.jpg', '.jpeg', '.png',".JPG"])
x = np.array(X)
y = np.array(Y)
train_images, test_images, train_labels, test_labels = train_test_split(x, y, train_size=0.9, test_size=0.1)
from keras.utils import to_categorical
print('Eğitim verisinin şekli : ', train_images.shape, train_labels.shape)
print('Test verisinin şekli : ', test_images.shape, test_labels.shape)
dimData = np.prod(train_images.shape[1:])
train_data = train_images.reshape(train_images.shape[0], dimData)
test_data = test_images.reshape(test_images.shape[0], dimData)
train_data = train_data.astype('float32')
test_data = test_data.astype('float32')
train_data /= 255
test_data /= 255
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(dimData,)))
model.add(Dense(512, activation='relu'))
model.add(Dense(train_labels.shape[1], activation='softmax'))
print(dimData)
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
history = model.fit(train_data, train_labels, batch_size=256, epochs=50, verbose=1,
validation_data=(test_data, test_labels))
model.save('bitirmeModel.h5')
[test_loss, test_acc] =model.evaluate(test_data,test_labels)
print("Test verilerinde değerlendirme sonucu : Kayıp = {}, Dogruluk {}".format(test_loss, test_acc))
plt.subplot(121)
plt.plot(history.history['loss'], 'r')
plt.plot(history.history['val_loss'], 'b')
plt.legend(['Egitim Kayıbı', 'Dogrulama Kayıbı'])
plt.xlabel('Epochs ')
plt.ylabel('Kayıp')
plt.title('Kayıp Egrisi')
plt.subplot(122)
plt.plot(history.history['acc'], 'r')
plt.plot(history.history['val_acc'], 'b')
plt.legend(['Egitim Dogrulugu', 'Dogrulama Dogrulugu'])
plt.xlabel('Epochs ')
plt.ylabel('Dogruluk')
plt.title('Dogruluk Egrisi')
plt.show()
plt.figure()
plt.title('Test Edilen Kişi')
plt.subplot()
plt.imshow(test_images[1, :,:], cmap='gray')
tahmin=int(model.predict_classes(test_data[[1],:]))
#modelimizin tahmini görmek için csv de yazılan idye göre çekme işlemi..
import numpy as np
import pandas as pd
df = pd.read_csv("isimler.csv")
print("Tahmin edilen kişi:")
print((df['first_name'][tahmin]))
| iremnurk/Universite-BitirmeProjesi-DerinOgrenme-YuzTanima | 03modelEgitim.py | 03modelEgitim.py | py | 2,661 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "tflearn.data_utils.image_preloader",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "numpy.array",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "numpy.array",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "sklearn.mo... |
32973108172 | import numpy as np
import matplotlib.pyplot as plt
import ipywidgets as wd
import pandas as pd
from IPython.display import display, update_display, Javascript, HTML
from inspect import signature
from graphviz import Digraph
import scipy.stats as sp
import plotly.express as px
import plotly.graph_objects as go
import warnings
import re
'''
Documentation for instructors:
How to set up a causal network:
1.
How to initialise the causal network in a notebook:
1. This .py script has to be imported
from causality_simulation2 import *
2. Define init_data = { 'node_name': [array_of_values], 'node_name2': [array_of_values], ... }, where the node_names have to be those causal nodes that have init=True, and the array of values have to be the fixed initial sample data, e.g. heights of students or coordinates of trees
How to set up an experiment:
1. experiment_name = Experiment(causal_network_name, init_data)
Every new experiment needs a new instance of Experiment
2. For group assignment
experiment_name.assignment()
Add argument config=[assignment_group1, assignment_group2, ...] for fixed (greyed out) assignment
assignment_group = { 'name': 'Name of group', 'samples_str': '1-10,15,20-30' }
If samples_str == '' for all groups, then samples are randomly assigned
3. For experimental setup
experiment_name.setting(show=['Name of node to show', ...])
Add argument disable='all' to disallow editing of settings
Add argument config=[intervention_group1, intervention_group2, ...], where intervention_groups have format { 'name': 'Name of group', 'intervention': { 'Name of node': ['fixed', 0], ...} }
See code for detail
4. For plotting of collected data
experiment_name.plot(show=['Name of node to show', ...])
'''
display(HTML('''<style>
[title="Assigned samples:"] { min-width: 150px; }
</style>'''))
def dialog(title, body, button):
display(Javascript("require(['base/js/dialog'], function(dialog) {dialog.modal({title: '%s', body: '%s', buttons: {'%s': {}}})});" % (title, body, button)))
class CausalNode:
def __init__(self, vartype, func, name, causes=None, min=0, max=100, categories=[], init=False):
'''
name: string, must be unique
vartype: 'categorical', 'discrete', 'continuous'
causes: (node1, ..., nodeN)
func: f
f is a function of N variables, matching the number of nodes and their types, returns a single number matching the type of this node
self.network: {node_name: node, ...}, all nodes that the current node depends on
init: True/False, whether variable is an initial immutable attribute
'''
# n_func_args = len(signature(func).parameters)
# n_causes = 0 if causes == None else len(causes)
# if n_func_args != n_causes:
# raise ValueError('The number of arguments in func does not match the number of causes.')
self.name = name
self.causes = causes
self.func = func
self.network = self.nodeDict()
self.vartype = vartype
self.min = min
self.max = max
self.categories = categories
self.init = init
def traceNetwork(self):
'''
Generates set of all nodes that current node depends on
'''
nodes = {self}
if self.causes != None:
for c in self.causes:
nodes = nodes.union(c.traceNetwork())
return nodes
def nodeDict(self):
'''
Generates a dictionary of name, node pairs for easier lookup of nodes by name
'''
nodes = self.traceNetwork()
network = {}
for n in nodes:
network[n.name] = n
return network
def generateSingle(self, fix={}):
'''
Generates a single multidimensional data point. Returns dict of name, value pairs
fix: {node_name: val, ...}
'''
data = {}
while len(data) != len(self.network):
for m, n in self.network.items():
if m not in data.keys():
if n.causes == None:
if m not in fix.keys():
data[m] = n.func()
else:
data[m] = fix[m]
else:
ready = True
for c in n.causes:
if c.name not in data.keys():
ready = False
break
if ready:
parents_val = [data[c.name] for c in n.causes]
if m not in fix.keys():
data[m] = n.func(*parents_val)
else:
data[m] = fix[m]
return data
def generate(self, n, intervention={}):
'''
Generates n data points. Returns dict of name, np.array(values) pairs
intervention: {node_name: [type, other_args]}
intervention format:
['fixed', val] (val could be number or name of category)
['range', start, end]
['array', [...]] array size must be n
'''
fix_all = {} # {name: [val, ...], ...}
for name, args in intervention.items():
if args[0] == 'fixed':
fix_all[name] = np.array([args[1] for i in range(n)])
elif args[0] == 'range':
fix_all[name] = np.random.permutation(np.linspace(args[1], args[2], n))
if self.vartype == 'discrete':
fix_all[name] = np.rint(fix_all[name])
elif args[0] == 'array':
fix_all[name] = np.array(args[1])
fixes = [None] * n # Convert to [{name: val, ...}, ...]
for i in range(n):
fixes[i] = {}
for name, arr in fix_all.items():
fixes[i][name] = arr[i]
data_dicts = [self.generateSingle(fix=fix) for fix in fixes]
data = {}
for name in self.network:
data[name] = np.array([d[name] for d in data_dicts])
return pd.DataFrame(data)
def drawNetwork(self):
g = Digraph(name=self.name)
def draw_edges(node, g):
if node.causes:
for cause in node.causes:
g.edge(cause.name, node.name)
draw_edges(cause, g)
draw_edges(self, g)
return g
class CausalNetwork:
def __init__(self, root_node):
self.root_node = root_node
self.init_attr = [name for name, node in self.root_node.network.items() if node.init] # List of immutable attributes
def drawNetwork(self):
return self.root_node.drawNetwork()
def generate(self, init_data, config, runs):
'''
Performs experiment many times (runs) according to config, returns data [i][group][var]
config: dict {'name': group_name, 'samples_str': '1-100', 'intervention': {...}}
'''
self.data = []
for i in range(runs):
exp = Experiment(self, init_data)
is_random = ''.join([g['samples_str'] for g in config]) == ''
samples = randomAssign(exp.N, len(config)) if is_random else [text2Array(g['samples_str']) for g in config]
groups = [{'name': config[i]['name'], 'samples': samples[i]} for i in range(len(config))]
exp.setAssignment(groups)
exp.doExperiment(config)
self.data.append(exp.data)
def statsContinuous(self, group, varx, vary):
'''
Calculates distribution of Pearson r and p-value between varx and vary (names of variables)
'''
runs = len(self.data)
results = np.zeros((runs, 2))
for i in range(runs):
x = self.data[i][group][varx]
y = self.data[i][group][vary]
results[i] = sp.pearsonr(x, y)
fig, ax = plt.subplots(1, 2, figsize=(14, 5))
fig.suptitle(vary + ' vs. ' + varx + ', ' + str(runs) + ' runs')
ax[0].hist(results[:,0])
ax[0].set_title('Pearson r')
ax[1].hist(np.log(results[:,1]))
ax[1].set_title('log(p)')
# def statsAB(self, group0, group1, var):
# '''
# Calculates distribution of Welch's t and p-value of var between the null hypothesis (group0) and intervention (group1)
# '''
# runs = len(self.data)
# results = np.zeros((runs, 2))
# for i in range(runs):
# a = self.data[i][group0][var]
# b = self.data[i][group1][var]
# results[i] = sp.ttest_ind(a, b, equal_var=False)
# fig, ax = plt.subplots(1, 2, figsize=(14, 5))
# fig.suptitle(var + ' between groups ' + group0 + ' and ' + group1 + ', ' + str(runs) + ' runs')
# ax[0].hist(results[:,0])
# ax[0].set_title("Welch's t")
# ax[1].hist(np.log(results[:,1]))
# ax[1].set_title('log(p)')
def statsAB(self, group0, group1, var, resamples=1000):
'''
Permutation test
'''
runs = len(self.data)
results = np.zeros((runs, 2))
for i in range(runs):
a = self.data[i][group0][var]
b = self.data[i][group1][var]
na = len(a)
nb = len(b)
sample_all = np.concatenate((a, b))
results[i,0] = abs(np.mean(a) - np.mean(b))
mean_diffs = np.zeros(resamples)
for j in range(resamples):
permuted = np.random.permutation(sample_all)
mean_diffs[j] = abs(np.mean(permuted[0:na]) - np.mean(permuted[na+1:]))
results[i,1] = np.sum(mean_diffs>=results[i,0]) / resamples
fig, ax = plt.subplots(1, 2, figsize=(14, 5))
fig.suptitle(var + ' between groups ' + group0 + ' and ' + group1 + ', ' + str(runs) + ' runs')
ax[0].hist(results[:,0])
ax[0].set_title("Difference in mean")
ax[1].hist(np.log(results[:,1]))
ax[1].set_title('log(p)') # p = probability that a random assignment into A, B groups will give (abs) mean greater than the observed one
class Experiment:
def __init__(self, network, init_data):
'''
init_data: dict of name, array to initialise basic immutable attributes. Keys must match init_attr in instance of Network
'''
self.node = network.root_node
l = []
for key, arr in init_data.items():
l.append(len(arr))
if max(l) != min(l):
raise ValueError('Every array in init_data must have the same length.')
self.init_data = init_data
if set(init_data.keys()) != set(network.init_attr):
raise ValueError("init_data doesn't match the causal network's init_attr.")
self.N = l[0] # Sample size
self.data = {} # {group_name: {node_name: [val, ...], ...}, ...}
self.assigned = False
self.done = False
self.p = None
def assignment(self, config=None, hide_random=False):
'''
UI for group assignment of samples
config: list of dicts, each being {'name': group_name, 'samples_str': string}
samples_str: e.g. '1-25,30,31-34', if all groups have empty string '' then assume randomise
'''
self.group_assignment = groupAssignment(self)
if config is not None:
self.group_assignment.setAssignment(config, hide_random)
self.submitAssignment()
def setAssignment(self, groups):
'''
Sets assignment into self.groups without UI
groups: list of dicts, each being {'name': group_name, samples: [array]}
'''
self.groups = groups
seen = set()
self.group_ids = dict()
for i in range(len(self.groups)):
name = self.groups[i]['name']
if name not in seen:
seen.add(name)
self.group_ids[name] = i
else:
dialog('Duplicate group names', 'Some of the groups have been given the same name. Please choose a unique name for each group.', 'OK')
return
self.group_names = list(self.group_ids.keys())
def submitAssignment(self, sender=None):
'''
Collects the group assignments from UI
self.groups: list of dicts, each being {'name': group_name, samples: [array]}
self.group_ids: dict {'group_name': id} for easier reverse lookup
Checks for duplicate group names
'''
self.setAssignment(self.group_assignment.getAssignment())
self.assigned = True
# Populate self.data for plotOrchard
for g in self.groups:
mask = [i in g['samples'] for i in range(self.N)]
d = dict()
for node_name, arr in self.init_data.items():
d[node_name] = arr[mask]
d['id'] = np.array(g['samples'])+1
self.data[g['name']] = pd.DataFrame(d)
if self.p:
self.p.updateAssignments()
else:
if self.node.name == 'Success Rate':
self.plotAssignment(plot='Basketball')
else:
self.plotAssignment()
def plotAssignment(self, plot='Truffula'):
'''
Can be implemented differently in different scenarios
'''
self.p = assignmentPlot(self, plot)
def setting(self, show='all', config=None, disable=[]):
'''
Let user design experiment
disabled: array of names
show: array of names
'''
if not self.assigned:
dialog('Groups not assigned', 'You have not yet assigned any groups! Click on "Visualise assignment" before running this box.', 'OK')
return
disable = self.node.network if disable == 'all' else disable
self.intervention_setting = interventionSetting(self, show=show, disable=disable)
if config is not None:
self.intervention_setting.setIntervention(config)
self.doExperiment(config)
def doExperiment(self, intervention, msg=False):
'''
Perform experiment under intervention
intervention: list of dictionaries, each being {'name': group_name, 'intervention': {'node_name', [...]}}
'''
self.data = dict()
for g in intervention:
j = self.group_ids[g['name']]
mask = [i in self.groups[j]['samples'] for i in range(self.N)]
for node_name, arr in self.init_data.items():
g['intervention'][node_name] = ['array', arr[mask]]
N_samples = len(self.groups[self.group_ids[g['name']]]['samples'])
self.data[g['name']] = self.node.generate(N_samples, intervention=g['intervention'])
self.done = True
if msg:
display(wd.Label(value='Data from experiment collected!'))
def plot(self, show='all'):
'''
Plots data after doExperiment has been called
'''
if not self.done:
dialog('Experiment not performed', 'You have not yet performed the experiment! Click on "Perform experiment" before running this box.', 'OK')
return
p = interactivePlot(self, show)
self.p = p
p.display()
def plotOrchard(self, gradient=None, show='all'):
'''
Takes in the name of the group in the experiment and the name of the
variable used to create the color gradient
'''
if not self.done:
dialog('Experiment not performed', 'You have not yet performed the experiment! Click on "Perform experiment" before running this box.', 'OK')
return
o = orchardPlot(self, gradient=gradient, show=show)
self.o = o
o.display()
class groupAssignment:
def __init__(self, experiment):
'''
UI for group assignment of samples
submitAssignment: callback function
'''
self.experiment = experiment
wd.Label(value='Sample size: %d' % self.experiment.N)
self.randomise_button = wd.Button(description='Randomise assignment', layout=wd.Layout(width='180px'))
self.group_assignments = [singleGroupAssignment(1)]
self.add_group_button = wd.Button(description='Add another group')
self.submit_button = wd.Button(description='Visualise assignment')
self.box = wd.VBox([g.box for g in self.group_assignments])
display(self.randomise_button, self.box, self.add_group_button, self.submit_button)
self.randomise_button.on_click(self.randomise)
self.add_group_button.on_click(self.addGroup)
self.submit_button.on_click(self.experiment.submitAssignment)
def setAssignment(self, config, hide_random):
for i in range(len(config)-1):
self.addGroup()
self.greyAll()
for i in range(len(config)):
self.group_assignments[i].setName(config[i]['name'])
if ''.join([g['samples_str'] for g in config]) == '':
self.randomise()
else:
for i in range(len(config)):
self.group_assignments[i].setSamples(config[i]['samples_str'])
if hide_random:
self.randomise_button.layout.visibility = 'hidden'
def addGroup(self, sender=None):
i = self.group_assignments[-1].i
self.group_assignments.append(singleGroupAssignment(i+1))
self.box.children = [g.box for g in self.group_assignments]
def getAssignment(self):
'''
Reads the settings and returns a list of dictionaries
'''
return [g.getAssignment() for g in self.group_assignments]
def randomise(self, sender=None):
'''
Randomly assigns samples to groups and changes settings in UI
'''
N = self.experiment.N
N_group = len(self.group_assignments)
assigned_ids = randomAssign(N, N_group)
for i in range(N_group):
self.group_assignments[i].samples.value = array2Text(assigned_ids[i])
def greyAll(self):
self.randomise_button.disabled = True
self.add_group_button.disabled = True
self.submit_button.disabled = True
for g in self.group_assignments:
g.greyAll()
class singleGroupAssignment:
def __init__(self, i):
'''
UI for a single line of group assignment
'''
self.i = i # Group number
self.name = 'Group %d' % i
i_text = wd.Label(value=self.name, layout=wd.Layout(width='70px'))
self.group_name = wd.Text(description='Name:')
self.samples = wd.Text(description='Assigned samples:', layout=wd.Layout(width='400px'))
self.box = wd.HBox([i_text, self.group_name, self.samples])
def getAssignment(self):
'''
Returns dict {'name': group_name, 'samples': [list_of_sample_ids]}
'''
assignment = dict()
self.name = self.name if self.group_name.value == '' else self.group_name.value
assignment['name'] = self.name
assignment['samples'] = text2Array(self.samples.value)
return assignment
def setName(self, name):
self.group_name.value = name
def setSamples(self, samples):
self.samples.value = samples
def greyAll(self):
self.group_name.disabled = True
self.samples.disabled = True
class interventionSetting:
def __init__(self, experiment, show='all', disable=[]):
self.experiment = experiment
self.group_settings = [singleGroupInterventionSetting(self.experiment, g, show=show, disable=disable) for g in self.experiment.groups]
submit = wd.Button(description='Perform experiment')
display(submit)
submit.on_click(self.submit)
def submit(self, sender=None):
self.experiment.doExperiment(self.getIntervention(), msg=True)
def getIntervention(self):
return [{'name': s.name, 'N': s.N, 'intervention': s.getIntervention()} for s in self.group_settings]
def setIntervention(self, config):
for c in config:
j = self.experiment.group_ids[c['name']]
self.group_settings[j].setIntervention(c)
class singleGroupInterventionSetting:
def __init__(self, experiment, config, show='all', disable=[]):
'''
UI settings for a single group
config: {'name': group_name, 'samples': [sample_ids]}
'''
self.experiment = experiment
self.name = config['name']
self.N = len(config['samples'])
group_text = wd.Label(value='Group name: %s, %d samples' % (self.name, self.N))
display(group_text)
to_list = list(self.experiment.node.network.keys()) if show == 'all' else show
to_list.sort()
self.node_settings = [singleNodeInterventionSetting(self.experiment.node.network[name], disable=name in disable) for name in to_list]
def getIntervention(self):
intervention = dict()
for s in self.node_settings:
inter = s.getIntervention()
if inter is not None:
intervention[s.name] = inter
return intervention
def setIntervention(self, config):
for s in self.node_settings:
if s.name in config['intervention'].keys():
s.setIntervention(config['intervention'][s.name])
class singleNodeInterventionSetting:
def __init__(self, node, disable=False):
'''
Single line of radio buttons and text boxes for intervening on a single variable in a single group
'''
self.name = node.name
self.disable = disable
self.is_categorical = node.vartype == 'categorical'
self.indent = wd.Label(value='', layout=wd.Layout(width='20px'))
self.text = wd.Label(value=self.name, layout=wd.Layout(width='180px'))
self.none = wd.RadioButtons(options=['No intervention'], layout=wd.Layout(width='150px'))
self.fixed = wd.RadioButtons(options=['Fixed'], layout=wd.Layout(width='70px'))
self.fixed.index = None
if self.is_categorical:
fixed_arg = wd.Dropdown(options=node.categories, disabled=True, layout=wd.Layout(width='100px'))
else:
fixed_arg = wd.BoundedFloatText(disabled=True, layout=wd.Layout(width='70px'))
self.fixed_arg = fixed_arg
self.range_visibility = 'hidden' if self.is_categorical else 'visible'
self.range = wd.RadioButtons(options=['Range'], layout=wd.Layout(width='70px', visibility=self.range_visibility))
self.range.index = None
self.range_arg1_text = wd.Label(value='from', layout=wd.Layout(visibility=self.range_visibility, width='30px'))
self.range_arg1 = wd.BoundedFloatText(min=node.min, max=node.max, disabled=True, layout=wd.Layout(width='70px', visibility=self.range_visibility))
self.range_arg2_text = wd.Label(value='to', layout=wd.Layout(visibility=self.range_visibility, width='15px'))
self.range_arg2 = wd.BoundedFloatText(min=node.min, max=node.max, disabled=True, layout=wd.Layout(width='70px', visibility=self.range_visibility))
self.none.observe(self.none_observer, names=['value'])
self.fixed.observe(self.fixed_observer, names=['value'])
self.range.observe(self.range_observer, names=['value'])
self.box = wd.HBox([self.indent, self.text, self.none, self.fixed, self.fixed_arg, self.range, self.range_arg1_text, self.range_arg1, self.range_arg2_text, self.range_arg2])
display(self.box)
if self.disable:
self.greyAll()
def greyAll(self):
self.none.disabled = True
self.fixed.disabled = True
self.fixed_arg.disabled = True
self.range.disabled = True
self.range_arg1.disabled = True
self.range_arg2.disabled = True
def setIntervention(self, intervention):
if intervention[0] == 'fixed':
self.fixed.index = 0
self.fixed_arg.value = intervention[1]
elif intervention[0] == 'range':
self.range.index = 0
self.range_arg1.value = intervention[1]
self.range_arg2.value = intervention[2]
# Radio button .index = None if off, .index = 0 if on
def none_observer(self, sender):
if self.none.index == 0:
self.fixed.index = None
self.fixed_arg.disabled = True
self.range.index = None
self.range_arg1.disabled = True
self.range_arg2.disabled = True
if self.disable:
self.greyAll()
def fixed_observer(self, sender):
if self.fixed.index == 0:
self.none.index = None
self.fixed_arg.disabled = False
self.range.index = None
self.range_arg1.disabled = True
self.range_arg2.disabled = True
if self.disable:
self.greyAll()
def range_observer(self, sender):
if self.range.index == 0:
self.none.index = None
self.fixed.index = None
self.fixed_arg.disabled = True
self.range_arg1.disabled = False
self.range_arg2.disabled = False
if self.disable:
self.greyAll()
def getIntervention(self):
'''
generates intervention from UI settings
'''
if self.none.index == 0: # None is deselected, 0 is selected
return None
elif self.fixed.index == 0:
return ['fixed', self.fixed_arg.value]
elif self.range.index == 0:
return ['range', self.range_arg1.value, self.range_arg2.value]
class assignmentPlot:
def __init__(self, experiment, plot='Truffula'):
self.experiment = experiment
self.group_names = experiment.group_names
self.data = experiment.data
self.plot = plot
self.buildTraces()
if self.plot == 'Truffula':
self.layout = go.Layout(title=dict(text='Tree Group Assignments'),barmode='overlay', height=650, width=800,
xaxis=dict(title='Longitude', fixedrange=True), yaxis=dict(title='Latitude', fixedrange=True),
hovermode='closest',
margin=dict(b=80, r=200, autoexpand=False),
showlegend=True)
else:
self.layout = go.Layout(title=dict(text='Student Group Assignments'),barmode='overlay', height=650, width=800,
xaxis=dict(title='Student', fixedrange=True),
yaxis=dict(title='Height', fixedrange=True, range=(120, 200)),
hovermode='closest',
margin=dict(b=80, r=200, autoexpand=False),
showlegend=True)
self.plot = go.FigureWidget(data=self.traces, layout=self.layout)
display(self.plot)
def buildTraces(self):
self.traces = []
self.group_names = self.experiment.group_names
self.data = self.experiment.data
if self.plot == 'Truffula':
for i, name in enumerate(self.group_names):
self.traces += [go.Scatter(x=self.data[name]['Longitude'], y=self.data[name]['Latitude'], mode='markers', hovertemplate='Latitude: %{x} <br>Longitude: %{y} <br>', marker_symbol=i, name=name)]
else:
for i, name in enumerate(self.group_names):
self.traces += [go.Bar(x=self.data[name]['id'], y=self.data[name]['Height (cm)'], hovertemplate='Student: %{x} <br>Height: %{y} cm<br>', name=name)]
def updateAssignments(self):
self.buildTraces()
with self.plot.batch_update():
self.plot.data = []
for trace in self.traces:
self.plot.add_traces(trace)
self.plot.layout = self.layout
class orchardPlot:
def __init__(self, experiment, gradient=None, show='all'):
self.data = experiment.data
self.experiment = experiment
self.options = self.data[experiment.group_names[0]].columns.tolist()
if show != 'all':
for i in self.options.copy():
if i not in show:
self.options.remove(i)
for name in experiment.node.nodeDict():
if experiment.node.nodeDict()[name].vartype == 'categorical' and name in show:
self.options.remove(name)
self.options.sort()
if not gradient:
gradient = self.options[0]
self.textbox = wd.Dropdown(
description='Gradient: ',
value=gradient,
options=self.options
)
self.textbox.observe(self.response, names="value")
self.plotOrchard(gradient)
def validate(self):
return self.textbox.value in self.options
def response(self, change):
if self.validate():
with self.g.batch_update():
for i, name in enumerate(self.experiment.group_names):
self.g.data[i].marker.color = self.data[name][self.textbox.value]
self.g.update_layout({'coloraxis':{'colorscale':'Plasma', 'colorbar':{'title':self.textbox.value}}})
self.g.data[i].hovertemplate = 'Latitude: %{x} <br>Longitude: %{y} <br>' + self.textbox.value + ': %{marker.color}<br>'
def plotOrchard(self, gradient):
"""Takes in the name of the group in the experiment and the name of the
variable used to create the color gradient"""
traces = []
for i, name in enumerate(self.experiment.group_names):
traces += [go.Scatter(x=self.data[name]['Longitude'], y=self.data[name]['Latitude'],
marker=dict(color=self.data[name][gradient], coloraxis='coloraxis'),
mode='markers',
name=name,
hovertemplate='Latitude: %{x} <br>Longitude: %{y} <br>'+ self.textbox.value + ': %{marker.color}<br>', hoverlabel=dict(namelength=0), marker_symbol=i)]
width = 700 if (len(self.experiment.group_names) == 1) else 725 + max([len(name) for name in self.experiment.group_names])*6.5
go_layout = go.Layout(title=dict(text='Orchard Layout'),barmode='overlay', height=650, width=width,
xaxis=dict(title='Longitude', fixedrange=True, range=[-50, 1050]),
yaxis=dict(title='Latitude', fixedrange=True, range=[-50, 1050]),
hovermode='closest', legend=dict(yanchor="top", y=1, xanchor="left", x=1.25),
coloraxis={'colorscale':'Plasma', 'colorbar':{'title':gradient}})
self.g = go.FigureWidget(data=traces, layout=go_layout)
def display(self):
container = wd.HBox([self.textbox])
display(wd.VBox([container, self.g]))
class interactivePlot:
def __init__(self, experiment, show='all'):
self.experiment = experiment
self.x_options = list(experiment.node.network.keys())
self.y_options = self.x_options.copy()
if show != 'all':
for i in self.x_options.copy():
if i not in show:
self.x_options.remove(i)
self.y_options.remove(i)
self.x_options.sort()
self.y_options.sort()
self.y_options += ['None (Distributions Only)']
self.textbox1 = wd.Dropdown(
description='x-Axis Variable: ',
value=self.x_options[0],
options=self.x_options
)
self.textbox2 = wd.Dropdown(
description='y-Axis Variable: ',
value=self.y_options[0],
options=self.y_options
)
self.button = wd.RadioButtons(
options=list(experiment.data.keys()) + ['All'],
layout={'width': 'max-content'},
description='Group',
disabled=False
)
self.observe()
self.initTraces()
def display(self):
container = wd.HBox([self.textbox1, self.textbox2])
display(wd.VBox([container, self.g]))
display(self.button)
display(Nothing(), display_id='1')
self.button.layout.display = 'none'
def display_values(self, group):
text = ""
xType, yType = self.experiment.node.nodeDict()[self.textbox1.value].vartype, self.experiment.node.nodeDict()[self.textbox2.value].vartype
if xType != 'categorical' and yType != 'categorical':
with warnings.catch_warnings():
warnings.simplefilter("ignore")
r = sp.pearsonr(self.experiment.data[group][self.textbox1.value], self.experiment.data[group][self.textbox2.value])
text += group + ': ' + 'Correlation (r) is ' + '{0:#.3f}, '.format(r[0]) + 'P-value is ' + '{0:#.3g}'.format(r[1])
return text
def createTraces(self, x, y):
traces = []
annotations = []
annotation_y = -0.20 - 0.02*len(self.experiment.group_names)
traceType = self.choose_trace(x, y)
if traceType == 'histogram':
for group in self.experiment.group_names:
data = self.experiment.data[group]
if self.experiment.node.nodeDict()[x].vartype == 'categorical':
opacity = 1
else:
opacity = 0.75
traces += [go.Histogram(x=data[x], name=group, bingroup=1, opacity=opacity)]
y = 'Count'
barmode = 'overlay'
elif traceType == 'scatter':
for group in self.experiment.group_names:
data = self.experiment.data[group]
traces += [go.Scatter(x=data[x], y=data[y], mode='markers', opacity=0.75, name=group)]
annotations += [dict(xref='paper',yref='paper',x=0.5, y=annotation_y, showarrow=False, text=self.display_values(group))]
annotation_y += -0.05
barmode = 'overlay'
elif traceType == 'bar':
for group in self.experiment.group_names:
avg = self.experiment.data[group].groupby(x).agg('mean')
std = self.experiment.data[group].groupby(x).agg('std')[y]
traces += [go.Bar(x=list(avg.index), y=avg[y], name=group, error_y=dict(type='data', array=std))]
annotations += [dict(xref='paper',yref='paper',x=0.5, y=annotation_y, showarrow=False, text=self.display_values(group))]
annotation_y += -0.05
barmode = 'group'
elif traceType == 'barh':
for group in self.experiment.group_names:
avg = self.experiment.data[group].groupby(y).agg('mean')
std = self.experiment.data[group].groupby(y).agg('std')[x]
traces += [go.Bar(x=avg[x], y=list(avg.index), name=group, error_x=dict(type='data', array=std), orientation='h')]
annotations += [dict(xref='paper',yref='paper',x=0.5, y=annotation_y, showarrow=False, text=self.display_values(group))]
annotation_y += -0.05
barmode = 'group'
go_layout = go.Layout(title=dict(text=x if traceType == 'histogram' else x + " vs. " + y ),
barmode=barmode,
height=500+50,
width=800,
xaxis=dict(title=x), yaxis=dict(title=y),
annotations = annotations,
margin=dict(b=80+50, r=200, autoexpand=False))
return traces, go_layout
def initTraces(self):
traces, layout = self.createTraces(self.x_options[0], self.y_options[0])
self.g = go.FigureWidget(layout=layout)
for t in traces:
self.g.add_traces(t)
def updateTraces(self):
self.g.data = []
traces, layout = self.createTraces(self.textbox1.value, self.textbox2.value)
for t in traces:
self.g.add_traces(t)
self.g.layout.annotations = layout.annotations
self.g.layout = layout
def observe(self):
self.textbox1.observe(self.response, names="value")
self.textbox2.observe(self.response, names="value")
self.button.observe(self.update_table, names='value')
def choose_trace(self, x, y):
if y == 'None (Distributions Only)':
return 'histogram'
xType, yType = self.experiment.node.nodeDict()[x].vartype, self.experiment.node.nodeDict()[y].vartype
if xType != 'categorical' and yType != 'categorical':
return 'scatter'
elif xType == 'categorical' and yType != 'categorical':
return 'bar'
elif xType != 'categorical' and yType == 'categorical':
return 'barh'
else:
return 'table'
def pivot_table(self):
if self.textbox1.value == self.textbox2.value:
df = "Cannot create a pivot table with only one variable"
return df
if self.button.value == 'All':
for group in self.experiment.group_names:
df = pd.DataFrame()
df = pd.concat([df, self.experiment.data[group]])
df = df.groupby([self.textbox1.value, self.textbox2.value]).agg('count').reset_index().pivot(self.textbox1.value, self.textbox2.value, self.options[0])
else:
df = self.experiment.data[self.button.value].groupby([self.textbox1.value, self.textbox2.value]).agg('count').reset_index().pivot(self.textbox1.value, self.textbox2.value, self.options[0])
return df
def update_table(self, change):
update_display(self.pivot_table(), display_id='1');
self.button.layout.display = 'flex'
def validate(self):
return self.textbox1.value in self.x_options and self.textbox2.value in (self.x_options + ['None (Distributions Only)'])
def response(self, change):
if self.validate():
traceType = self.choose_trace(self.textbox1.value, self.textbox2.value)
with self.g.batch_update():
if traceType == 'table':
self.g.update_layout({'height':10, 'width':10})
self.g.layout.xaxis.title = ""
self.g.layout.yaxis.title = ""
self.g.layout.title = ""
self.button.layout.display = 'flex'
else:
self.updateTraces()
update_display(Nothing(), display_id='1')
self.button.layout.display = 'none'
class Nothing:
def __init__(self):
None
def __repr__(self):
return ""
def text2Array(text):
text = text.replace(' ', '')
if re.fullmatch(r'^((\d+)(|-(\d+)),)*(\d+)(|-(\d+))$', text) is None:
return None
matches = re.findall(r'((\d+)-(\d+))|(\d+)', text)
ids = []
for m in matches:
if m[3] != '':
ids = np.concatenate((ids, [int(m[3])-1])) # Subtract one because text starts at 1, array starts at 0
else:
if int(m[2]) < int(m[1]):
return None
else:
ids = np.concatenate((ids, np.arange(int(m[1])-1, int(m[2]))))
uniq = list(set(ids))
uniq.sort()
if len(ids) != len(uniq):
return None
return uniq
def array2Text(ids):
ids.sort()
ids = np.array(ids)+1 # Add one because text starts at 1, array starts at 0
segments = []
start = ids[0]
end = ids[0]
for j in range(len(ids)):
if j == len(ids)-1:
end = ids[j]
s = str(start) if start == end else '%d-%d' % (start, end)
segments.append(s)
elif ids[j+1] != ids[j]+1:
end = ids[j]
s = str(start) if start == end else '%d-%d' % (start, end)
segments.append(s)
start = ids[j+1]
return ','.join(segments)
def randomAssign(N, N_group):
'''
Randomly assigns N total items into N_group groups
Returns a list of lists of ids
'''
arr = np.arange(N)
np.random.shuffle(arr)
result = []
for i in range(N_group):
start = i*N//N_group
end = min((i+1)*N//N_group, N)
result.append(arr[start:end])
return result
# Some functions for causal relations
def gaussian(mean, std):
def f():
return np.random.normal(mean, std)
return f
def constant(x):
def f():
return x
return f
def uniform(a, b):
def f():
return np.random.random()*(b-a) + a
return f
def poisson(rate):
def f():
return np.random.poisson(lam=rate)
return f
def choice(opts, weights=None, replace=True):
def f():
nonlocal weights
if weights is None:
chosen = np.random.choice(opts, replace=replace)
else:
weights = np.array(weights)
p = weights/sum(weights)
chosen = np.random.choice(opts, p=p, replace=replace)
return chosen
return f
# Solves for the coefficients given a set of points
def solveLinear(*points):
n = len(points)
A = np.zeros((n, n))
b = np.zeros(n)
for i in range(n):
A[i] = np.append(points[i][0:-1], 1)
b[i] = points[i][-1]
sol = np.linalg.solve(A, b)
return sol[0:-1], sol[-1]
def linear(x1, y1, x2, y2, fuzz=0):
M, c = solveLinear((x1, y1), (x2, y2))
def f(x):
return M[0]*x + c + np.random.normal(0, fuzz)
return f
def linearFunc(x1, m1, c1, x2, m2, c2, func, fuzz=0, integer=False):
# Applies linear function on the input of func(*args[0:-1]), where the slope and intercept are determined by args[-1] according to x1, m1, c1, x2, m2, c2
M_m, c_m = solveLinear((x1, m1), (x2, m2))
M_c, c_c = solveLinear((x1, c1), (x2, c2))
def f(*args):
x = args[-1]
m = M_m[0]*x + c_m
c = M_c[0]*x + c_c
number = m*func(*args[0:-1]) + c + np.random.normal(0, fuzz)
if integer:
number = max(int(number), 0)
return number
return f
def dependentPoisson(*points):
M, c = solveLinear(*points)
def f(*args):
rate = max(M@np.array(args) + c, 0)
return np.random.poisson(lam=rate)
return f
def dependentGaussian(x1, mean1, std1, x2, mean2, std2):
M_mean, c_mean = solveLinear((x1, mean1), (x2, mean2))
M_std, c_std = solveLinear((x1, std1), (x2, std2))
def f(x): # x is input value used to calculate mean and std of new distribution
mean = M_mean[0]*x + c_mean
std = max(M_std[0]*x + c_std, 0)
return abs(np.random.normal(mean, std))
return f
def categoricalLin(data): # data: {'category': (m, c, fuzz), etc}
def f(x, y): # y is the category, x is the input value
fuzz = data[y][2] if len(data[y]) == 3 else 0
return data[y][0] * x + data[y][1] + np.random.normal(0, fuzz)
return f
def categoricalGaussian(data): # data: {'category': (mean, std), etc}
def f(x): # x is the category
return np.random.normal(data[x][0], data[y][1])
return f
'''
truffula
'''
# Uniformly distributed from 0m to 1000m
latitude_node = CausalNode('continuous', choice(np.linspace(0, 1000, 50), replace=False), name='Latitude', min=0, max=1000, init=True)
longitude_node = CausalNode('continuous', choice(np.linspace(0, 1000, 50), replace=False), name='Longitude', min=0, max=1000, init=True)
# Gaussian+absolute value, more wind in south
wind_node = CausalNode('continuous', lambda x,y: dependentGaussian(0, 2, 5, 1000, 10, 10)(x) + dependentGaussian(0, 6, 3, 1000, 2, 4)(x), name='Wind Speed', causes=[latitude_node, longitude_node], min=0, max=40)
supplement_node = CausalNode('categorical', constant('Water'), name='Supplement', categories=['Water', 'Kombucha', 'Milk', 'Tea'])
fertilizer_node = CausalNode('continuous', gaussian(10, 2), 'Fertilizer', min=0, max=20)
supplement_soil_effects = {'Water': (1, 0), 'Kombucha': (0.6, -5), 'Milk': (1.2, 10), 'Tea': (0.7, 0)}
# Fertilizer improves soil, kombucha destroys it
soil_node = CausalNode('continuous', lambda x, y: categoricalLin(supplement_soil_effects)(linear(0, 10, 20, 100, fuzz=5)(x), y), 'Soil Quality', causes=[fertilizer_node, supplement_node], min=0, max=100)
supplement_bees_effects = {'Water': (1, 0), 'Kombucha': (1.3, 0), 'Milk': (1, 0), 'Beer': (0.2, 0)}
# Beehive in north, bees avoid wind, love kombucha
bees_node = CausalNode('discrete', lambda x, y, z: categoricalLin(supplement_bees_effects)(dependentPoisson((0, 0, 250), (500, 30, 10), (0, 30, 40))(x, y), z), name='Number of Bees', causes=[latitude_node, wind_node, supplement_node], min=0, max=300)
# Bees and good soil improve fruiting
fruit_node = CausalNode('discrete', dependentPoisson((0, 0, 0), (100, 200, 28), (100, 50, 16)), name='Number of Fruits', causes=[soil_node, bees_node])
# fruit_node.drawNetwork()
truffula = CausalNetwork(fruit_node)
'''
basketball
'''
shottype_node = CausalNode('categorical', choice(['Above head', 'Layup', 'Hook shot'], weights=[6, 3, 2]), name='Shot Type', categories=['Above head', 'Layup', 'Hook shot'])
hours_node = CausalNode('continuous', choice(np.linspace(0, 14, 30), weights=1/np.linspace(1, 15, 30)), name='Hours Practised per Week')
height_node = CausalNode('continuous', gaussian(170, 10), name='Height (cm)', min=150, max=190, init=True)
ability_node = CausalNode('continuous', linearFunc(0, 1, 0, 10, 1, 20, linear(150, 40, 190, 60, fuzz=10)), name='Ability', causes=[height_node, hours_node])
shottype_modifier = {'Above head': (1, 0), 'Layup': (0.6, 0), 'Hook shot': (0.3, 0)}
success_node = CausalNode('continuous', categoricalLin(shottype_modifier), name='Success Rate', causes=[ability_node, shottype_node])
basketball = CausalNetwork(success_node) | sensesensibilityscience/datascience | old/causality_simulation2.py | causality_simulation2.py | py | 45,718 | python | en | code | 2 | github-code | 1 | [
{
"api_name": "IPython.display.display",
"line_number": 42,
"usage_type": "call"
},
{
"api_name": "IPython.display.HTML",
"line_number": 42,
"usage_type": "call"
},
{
"api_name": "IPython.display.display",
"line_number": 47,
"usage_type": "call"
},
{
"api_name": "... |
38760269349 | import streamlit as st
from deta import Deta
DETA_KEY="c05lph41_umJvMdPncrzTfw3dLRynCV8Fb8cQYEaq"
deta=Deta(DETA_KEY)
db=deta.Base("perlengkapan_db")
st.title("Danbox")
st.header("PERALATAN")
st.subheader('Perlengkapan Laboratorium')
from PIL import Image
import streamlit as st
pilihan = st.selectbox(
'Pilihan Pengambilan',
('pick up', ' delivered'))
st.write('You selected:', pilihan)
#NAMA
import streamlit as st
nama=st.text_input('Nama Pelanggan')
if not nama:
st.warning('Mohon masukkan nama.')
#KELAS
kelas=st.text_input('Kelas')
if not kelas:
st.warning('Mohon masukkan Kelas.')
#TANGGAL
tanggal=st.text_input('Tanggal Pemesanan')
if not tanggal:
st.warning('Mohon masukkan tanggal')
st.subheader('Peralatan Laboratorium')
col7, col8, col9=st.columns(3)
with col7:
st.subheader("Sarung Tangan")
image = Image.open('gambar/sarung.jpg')
st.image(image, width=150)
import streamlit as st
numberA = st.number_input('Jumlah sarung tangan',0)
with col8:
st.subheader("Serbet")
image = Image.open('gambar/serbet.jpg')
st.image(image, width=150)
import streamlit as st
numberB = st.number_input('Jumlah serbet',0)
with col9:
st.subheader("Tabung Reaksi")
image = Image.open('gambar/reak.png')
st.image(image, width=150)
import streamlit as st
numberC = st.number_input('Jumlah tabung reaksi',0)
col10, col11, col12=st.columns(3)
with col10:
st.subheader("Gelas Piala")
image = Image.open('gambar/piala.jpg')
st.image(image, width=150)
import streamlit as st
numberD = st.number_input('Jumlah Gelas Piala',0)
besarr = st.selectbox(
'Pilih Ukuran Gelas Piala (mL)',
('10', ' 25','50','100','150','200','250'))
st.write('You selected:',besarr)
with col11:
st.subheader("Tabung Ulir")
image = Image.open('gambar/lir.jpg')
st.image(image, width=150)
import streamlit as st
numberE = st.number_input('Jumlah tabung ulir',0)
besar = st.selectbox(
'Pilih Ukuran Tabung Ulir(mm)',
('13xH.100', '16xH.100','16xH.150','18xH.180','20xH.150','25xH.150','25xH.200'))
st.write('You selected:', besar)
with col12:
st.header("Gelas Ukur")
image = Image.open('gambar/pia.jpg')
st.image(image, width=150)
import streamlit as st
numberE = st.number_input('Jumlah Gelas Ukur',0)
ukuran = st.selectbox(
'Pilih Ukuran Gelas Ukur(mL)',
('10', ' 25','50','100','150','200','250'))
st.write('You selected:', ukuran)
lab = st.button("rincian")
if lab:
import pandas as pd
hargaA=2000*numberA
hargaB=5000*numberB
hargaC=10000*numberC
hargaD=20000*numberD
hargaE=20000*numberE
data = [['Sarung Tangan',numberA,hargaA],['Serbet',numberB,hargaB],['Tabung Reaksi',numberC,hargaC],['Gelas Piala',numberD,hargaD],['Tabung Ulir',numberE,hargaE]]
df=pd.DataFrame(data,columns=['Perlengkapan','jumlah','harga (Rp.)'])
df
hargaA=2000
hargaB=5000
hargaC=10000
hargaD=20000
hargaE=20000
hitung=(hargaA*numberA)+(hargaB*numberB)+(hargaC*numberC)+(hargaD*numberD)+(hargaE*numberE)
if hitung<30000:
st.write("total harga perlengkapan Rp.",hitung)
if hitung>30000:
hitung=hitung-0.1*hitung
st.write("Diskon 10% total harga perlengkapan Rp.",hitung)
agree = st.checkbox('Saya setuju')
if agree:
st.write('Terima kasih atas pesanannya!')
def pesanan(pilihan,namapel,kelas,tanggal,numberA,numberB,numberC,numberD,numberE):
return db.put({"Pengambilan":pilihan,"Nama":namapel,"Kelas":kelas,"Tanggal":tanggal,"sarung tangan":numberA,"Serbet":numberB,"Tabung Reaksi ":numberC,"Gelas Piala ":numberD," Tabung Ulir":numberE})
pesanan(pilihan,nama,kelas,tanggal,numberA,numberB,numberC,numberD,numberE)
if st.button('KIRIM'):
st.write('Pesanan Diterima')
else:
st.write('Terimakasih Atas Pesanannya')
| erlandesvarapramedya/Deployment-Danbox | pages/3_Peralatan.py | 3_Peralatan.py | py | 3,968 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "deta.Deta",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "deta.Base",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "streamlit.title",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "streamlit.header",
"line_number... |
73376081633 | import os
import sys
import pickle
import argparse
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
from scipy.optimize import curve_fit
from scipy.optimize import least_squares
import math
from matplotlib import cm
from matplotlib.ticker import LinearLocator
from mpl_toolkits.mplot3d import Axes3D
from scipy.stats import norm
import quadprog
import cvxopt
from scipy import linalg as la
import pygad
from data_management.read_csv import *
def filter_vf_tracks(tracks):
"""
This method reads the tracks file from highD data.
:param arguments: the parsed arguments for the program containing the input path for the tracks csv file.
:return: a list containing all tracks as dictionaries.
"""
vf_tracks = []
for track in tracks:
dhw = track[DHW]
pr_id = track[PRECEDING_ID][0]-1
if not(np.all(dhw==0)) and (track[BBOX][0][2]<6) and (track[LANE_ID][-1] == track[LANE_ID][0]) and (tracks[pr_id][LANE_ID][-1] == tracks[pr_id][LANE_ID][0]):
vf_dhw = dhw[dhw>1]
vf_dhw = vf_dhw[vf_dhw<50]
if (np.count_nonzero(vf_dhw) == np.count_nonzero(dhw)) and (tracks[pr_id][BBOX][0][2]<6) and (np.count_nonzero(dhw)>275):
vf_tracks.append(track)
return vf_tracks
def combine_and_compute(vf_tracks,tracks):
NU = "nu"
P_X_V = "p_x_v"
pairs = []#save information of every vehicle pair
count = 0
for track in vf_tracks:
pr_track = tracks[track[PRECEDING_ID][0]-1]
frame = np.intersect1d(track[FRAME],pr_track[FRAME])
x_v = track[X_VELOCITY][:len(frame)]
x_a = track[X_ACCELERATION][:len(frame)]
dhw = track[DHW][:len(frame)]
pr_x_v = pr_track[X_VELOCITY][-len(frame):]
nu = pr_x_v - x_v
pr_x_a = pr_track[X_VELOCITY][-len(frame):] - pr_track[X_VELOCITY][-len(frame)-1:-1]
if track[LANE_ID][0] < 4:
x_a = -x_a
nu = -nu
x_v = -x_v
pair = {TRACK_ID: pr_track[TRACK_ID]*100+track[TRACK_ID],
FRAME: frame,
X_VELOCITY: x_v,
X_ACCELERATION: x_a,
DHW: dhw,
NU: nu,
PRECEDING_ID: track[PRECEDING_ID][:len(frame)],
LANE_ID: track[LANE_ID][:len(frame)],
P_X_V: pr_x_v
}
pairs.append(pair)
# if count == 0:
# V = x_v
# A = x_a
# Nu = nu
# D = dhw
# Pr_x_a = pr_x_a
# count = 1
# else:
# V = np.concatenate((V,x_v))
# A = np.concatenate((A,x_a))
# Nu = np.concatenate((Nu,nu))
# D = np.concatenate((D,dhw))
# Pr_x_a = np.concatenate((Pr_x_a,pr_x_a))
if count == 0:
V = x_v
A = x_a
Nu = nu
D = dhw
Pr_x_a = pr_x_a
count = 1
elif np.all(nu>-4) and np.all(nu<4) and np.all(dhw>10) and np.all(dhw<49):
V = np.concatenate((V,x_v))
A = np.concatenate((A,x_a))
Nu = np.concatenate((Nu,nu))
D = np.concatenate((D,dhw))
Pr_x_a = np.concatenate((Pr_x_a,pr_x_a))
return V,A,Nu,D,Pr_x_a,pairs
def dynamics(x,Ax,Bx,kp,kd,d_sigma):
w = norm.rvs(0, d_sigma, size=1)
return Ax @ x + Bx * (kp*x[0]+kd*x[1]+w)
def error_vis_2(data):
mu, std = stats.norm.fit(data)
x = np.linspace(data.min(), data.max(), 100)
pdf = stats.norm.pdf(x, mu, std)
plt.hist(data, bins=30, density=True, alpha=0.6, color='b')
plt.plot(x, pdf, 'r-', lw=2)
plt.xlabel('values')
plt.ylabel('Probability')
plt.title('Histogram : $\mu$=' + str(round(mu,4)) + ' $\sigma=$'+str(round(std,4)))
plt.show()
def error_vis(x):
n, bins, patches = plt.hist(x, 100, density=1, alpha=0.75)
y = norm.pdf(bins, np.mean(x), np.std(x))# fit normal distribution
plt.grid(True)
plt.plot(bins, y, 'r--')
plt.xlim((-2, 2))
plt.ylim((0, 1))
plt.xticks(np.arange(-2, 2.01, 1),fontproperties = 'Times New Roman', size = 28)
plt.yticks(np.arange(0, 1.01, 0.2),fontproperties = 'Times New Roman', size = 28)
plt.xlabel('values',fontdict={'family' : 'Times New Roman', 'size': 32})
plt.ylabel('Probability',fontdict={'family' : 'Times New Roman', 'size': 32})
plt.title('$\sigma=$'+str(round(np.std(x),4)),fontproperties = 'Times New Roman', size = 30)
plt.show()
def error_calculate_and_vis(pairs,kp,kd,h,Ax,Bx,Dx):
NOISE = "noise"
ERROR = "error"
NU = "nu"
P_X_V = "p_x_v"
E = "relative_pos"
count_2 = 0
count_3 = 0
for pair in pairs:
duration = len(pair[FRAME])
pair[E] = pair[DHW] - h * pair[X_VELOCITY]# - r
count = 0
for j in range(duration-1):
error = np.array([[pair[E][j+1]],[pair[NU][j+1]]]) - Ax@np.array([[pair[E][j]],[pair[NU][j]]]) - Bx * (kp*pair[E][j]+kd*pair[NU][j]) - Dx*(pair[P_X_V][j+1]-pair[P_X_V][j])
disturbance = pair[P_X_V][j+1]-pair[P_X_V][j]
if count_2 == 0:
error_all = error
disturbance_all = disturbance
count_2 = 1
else:
error_all = np.hstack((error_all,error))
disturbance_all = np.hstack((disturbance_all,disturbance))
if count == 0:
Error = error
count = 1
else:
Error = np.hstack((Error,error))
noise = kp*pair[DHW]-kp*h*pair[X_VELOCITY]+kd*pair[NU]-pair[X_ACCELERATION]
if count_3 == 0:
Noise = noise
count_3 = 1
else:
Noise = np.concatenate((Noise,noise))
pair[ERROR] = Error
pair[NOISE] = Noise
# error_mu = [np.mean(error_all[0,:]),np.mean(error_all[1,:])]
# error_sigma = [np.std(error_all[0,:]),np.std(error_all[1,:])]
noise_cov = np.cov(Noise)
n_mu = np.mean(Noise)
# print(n_mu,noise_cov)
#print('noise_cov',noise_cov)
#print('error_mu',error_mu,'error_sigma',error_sigma)
Gamma = (noise_cov * Bx@Bx)**(-1)
# print('Gamma',Gamma)
mu = np.mean(error_all[0,:])
sigma = np.std(error_all[0,:])
filter = (error_all[0,:]>mu-3*sigma) & (error_all[0,:]<mu+3*sigma)
error_all = np.vstack((error_all[0,:][filter],error_all[1,:][filter]))
mu_dis = np.mean(disturbance_all)
sigma_dis = np.std(disturbance_all)
filter_dis = (disturbance_all>mu_dis-3*sigma_dis) & (disturbance_all<mu_dis+3*sigma_dis)
# disturbance_all = disturbance_all[filter_dis]
# error_vis_2(disturbance_all)
# print(disturbance_all.shape)
# error_vis(error_all[0,:])
# error_vis(error_all[1,:])
error_vis(error_all[0,:]/Bx[0])
error_vis(error_all[1,:]/Bx[1])
# B1d = error_all[0,:]/2 + error_all[1,:]*Bx[0,0]/(2*Bx[1,0])
# B2d = error_all[0,:]*Bx[1,0]/(2*Bx[0,0]) + error_all[1,:]/2
# d = (c*error_all[0,:]/(Bx[0]) + error_all[1,:]/(Bx[1]))*0.7
d = (error_all[0,:]/(Bx[0]) + error_all[1,:]/(Bx[1]))*0.6
# d_mu = c*0.5*np.mean(error_all[0,:])+np.mean(error_all[1,:])*0.5
# d_sigma = np.std(error_all[1,:])
d_mu = np.mean(d)
d_sigma = np.std(d)
# print('d_mu',d_mu,'d_sigma',d_sigma)
# print('d_mu',np.mean(d),'d_sigma',np.std(d))
error_vis(d)
# error_vis(B1d)
# error_vis(B2d)
return Gamma, d_mu, d_sigma
def quadprog_solve_qp(P, q, G, h, A=None, b=None):
qp_G = .5 * (P + P.T) # make sure P is symmetric
qp_a = -q
if A is not None:
qp_C = -np.vstack([A, G]).T
qp_b = -np.hstack([b, h])
meq = A.shape[0]
else: # no equality constraint
qp_C = -G.T
qp_b = -h
meq = 0
return quadprog.solve_qp(qp_G, qp_a, qp_C, qp_b, meq)[0]
def cvxopt_solve_qp(P, q, G, h, A=None, b=None):
P = .5 * (P + P.T) # make sure P is symmetric
args = [cvxopt.matrix(P), cvxopt.matrix(q)]
args.extend([cvxopt.matrix(G), cvxopt.matrix(h)])
if A is not None:
args.extend([cvxopt.matrix(A), cvxopt.matrix(b)])
sol = cvxopt.solvers.qp(*args)
if 'optimal' not in sol['status']:
return None
return np.array(sol['x']).reshape((P.shape[1],))
def kernel(x1,x2):
return (1+x1@x2)**2###############
def value_func(x,x_t,alphas,N_data):
sum = 0
for i in range(N_data):
sum += alphas[i]*kernel(x,x_t[i])
return sum
def quad_value_func(x,X):
return x.T@X@x
# def derivative_v(x,x_t,alphas,N_data):
# sum = 0
# for i in range(N_data):
# sum += alphas[i]*2*(1+x_t[i]@x)*x_t[i].T
# return sum
# def pi_hat(x,x_all,alphas,N_data,Ax,Bx,beta):
# de = derivative_v(Ax@x,x_all,alphas,N_data)
# return -beta*de@Bx
def vf_plot(x_t,alphas,N_data,X_idare=0,function='kernel',three_d=1,contour=1):
# X = np.linspace(-35,20,200) #0.5 20*20
# Y = np.linspace(-7,7,200) #0.1 20*20
n = 100
X = np.linspace(-20,20,n) #0.5 20*20
Y = np.linspace(-5,5,n) #0.1 20*20
X,Y = np.meshgrid(X,Y)
Z = np.zeros((n,n))
if function == 'kernel':
for i in range(n):
for j in range(n):
Z[j,i] = value_func(np.array([X[0,i],Y[j,0]]),x_t,alphas,N_data)
if function == 'quad':
for i in range(n):
for j in range(n):
Z[j,i] = quad_value_func(np.array([X[0,i],Y[j,0]]),X_idare)
if three_d==1:
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)
ax.zaxis.set_major_formatter('{x:.02f}')
# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
if contour==1:
# plt.contourf(X,Y,Z)
# for x in x_t:
# if x[0]<20:
# plt.scatter(x[0], x[1], s = 30, c = 'b')
C=plt.contour(X,Y,Z,levels=[10**i for i in range(-4,8)])
plt.clabel(C, inline=True, fontsize=10)
plt.show()
# print(value_func(np.array([-20,0]),x_t,alphas,N_data)) | zhaoxs1121/IRL | functions.py | functions.py | py | 9,339 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "numpy.all",
"line_number": 35,
"usage_type": "call"
},
{
"api_name": "numpy.count_nonzero",
"line_number": 38,
"usage_type": "call"
},
{
"api_name": "numpy.intersect1d",
"line_number": 49,
"usage_type": "call"
},
{
"api_name": "numpy.all",
"line... |
37440181439 | # Author : Bryce Xu
# Time : 2020/1/17
# Function:
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicConv(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1, groups=1, relu=True, bn=True, bias=False):
super(BasicConv, self).__init__()
self.out_channels = out_planes
self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias)
self.bn = nn.BatchNorm2d(out_planes,eps=1e-5, momentum=0.01, affine=True) if bn else None
self.relu = nn.ReLU() if relu else None
def forward(self, x):
x = self.conv(x)
if self.bn is not None:
x = self.bn(x)
if self.relu is not None:
x = self.relu(x)
return x
class ChannelPool(nn.Module):
def forward(self, x):
return torch.cat( (torch.max(x,1)[0].unsqueeze(1), torch.mean(x,1).unsqueeze(1)), dim=1 )
class SpatialGate(nn.Module):
def __init__(self):
super(SpatialGate, self).__init__()
kernel_size = 7
self.compress = ChannelPool()
self.spatial = BasicConv(2, 1, kernel_size, stride=1, padding=(kernel_size-1) // 2, relu=False)
def forward(self, x):
x_compress = self.compress(x)
x_out = self.spatial(x_compress)
scale = torch.sigmoid(x_out) # broadcasting
return x * scale
class SAM(nn.Module):
def __init__(self):
super(SAM, self).__init__()
self.SpatialGate = SpatialGate()
def forward(self, x):
x_out = self.SpatialGate(x)
return x_out
class SAAM(nn.Module):
def __init__(self, gate_channels):
super(SAAM, self).__init__()
kernel_size = 7
self.compress = ChannelPool()
self.spatial = BasicConv(2, 1, kernel_size, stride=1, padding=(kernel_size - 1) // 2, relu=False)
self.linear = nn.Sequential(
nn.Linear(100, gate_channels),
nn.Dropout(0.5),
nn.Linear(gate_channels, gate_channels),
nn.BatchNorm1d(gate_channels),
nn.ReLU()
)
self.gate_channels = gate_channels
def forward(self, x, x_emb=None, x_emb_targets=None, wordEmbedding=False):
x_compress = self.compress(x)
x_out = self.spatial(x_compress) # (N,1,f,f)
if not wordEmbedding:
scale = torch.sigmoid(x_out) # broadcasting
return x * scale
else:
# x:(N,gate_chanels,filter_size,filter_size)
x_process = x.view(x.size(0), self.gate_channels, -1)
x_process = x_process.view(x.size(0), -1, self.gate_channels) # (N,fxf,gate_channels)
x_process = F.normalize(x_process, dim=2)
x_emb_targets = self.linear(x_emb_targets) # (C,gate_channels)
x_emb_targets = F.normalize(x_emb_targets, dim=1)
distance = torch.matmul(x_process, x_emb_targets.t())
distance = distance.view(x.size(0), x_emb_targets.size(0), distance.size(1)) # (N,C,fxf)
positive_distance = torch.stack(
[distance[i][i * x_emb_targets.size(0) // x.size(0)] for i in range(0, x.size(0))]) # (N,fxf)
positive_distance_softmax = F.softmax(positive_distance, dim=1) # (N,fxf)
positive_distance_softmax = positive_distance_softmax.view(x.size(0), 1, x.size(2), x.size(2)) # (N,1,f,f)
x_out = x_out.mul(positive_distance_softmax)
alpha = 0.4
distance -= positive_distance.view(x.size(0), 1, -1) # (N,C,fxf)
distance = torch.clamp(distance, min=alpha)
distance = distance.mul(positive_distance_softmax.view(x.size(0), 1, x.size(2) * x.size(2)))
loss = torch.mean(torch.sum(torch.sum(distance, dim=2), dim=1), dim=0)
scale = torch.sigmoid(x_out) # broadcasting
return x * scale, loss
| brycexu/SAA | Few-Shot Classification/SAAM.py | SAAM.py | py | 3,960 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "torch.nn.Module",
"line_number": 9,
"usage_type": "attribute"
},
{
"api_name": "torch.nn",
"line_number": 9,
"usage_type": "name"
},
{
"api_name": "torch.nn.Conv2d",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "torch.nn",
"line_numb... |
14921838958 | from webium.driver import get_driver
from webium.driver import close_driver
from Login import loginpage
from selenium.webdriver.support.ui import Select
import time
from creds import admin_login, admin_password
import random
from random import choice
from string import digits
from navigation_bar import NavigationBar
from admin_booking import AdminBookingPage
from channel_page import ChannelPage
ActivityName = "AlertTest"
ActivityTimezone = 'AT'
ChannelNameList =[]
class BaseTest(object):
def teardown_class(self):
close_driver()
class Test_GODO327_341(BaseTest):
def test_327(self):
get_driver().maximize_window()
page = loginpage()
page.open()
page.login_field.send_keys(admin_login)
page.password_field.send_keys(admin_password)
page.button.click()
page = ChannelPage()
page.open()
page.add_channel_button.click()
time.sleep(5)
NewChannelName = ("AutoTestNameOnly_" + ''.join(choice(digits) for i in range(3)))
page.channel_name.send_keys(NewChannelName)
ChannelNameList.append(NewChannelName)
page.save_button.click()
time.sleep(5)
page.search_field.send_keys(NewChannelName)
time.sleep(2)
assert page.table_channel_name.get_attribute('textContent') == ' ('+''.join(NewChannelName)+')'
assert page.table_channel_comission.get_attribute('textContent') == '' #FAILED FOR PERCENTAGE - Bug 3110
assert page.table_channel_phonenumber.get_attribute('textContent') == ''
assert page.table_channel_email.get_attribute('textContent') == ''
page.table_channel_editbutton.click()
time.sleep(5)
assert page.channel_name.get_attribute('value') == NewChannelName
assert page.status_checkbox.is_selected() == True
page.cancel_button.click()
time.sleep(7)
page = NavigationBar()
page.main_actions_drop_down.click()
time.sleep(2)
page.add_a_booking.click()
page = AdminBookingPage()
select = Select(page.activity_list)
select.select_by_visible_text(ActivityName)
page.first_tickets_type.send_keys('1')
time.sleep(5)
page.datepicker_next_month.click()
time.sleep(5)
EventDate = str(random.randint(2, 30))
for i in range(0, len(page.dates)):
if page.dates[i].get_attribute("textContent") == EventDate:
page.dates[i].click()
else:
continue
break
time.sleep(5)
EventTimeHours = str(random.randint(2, 10))
minutes_values = ('00', '15', '30', '45')
EventTimeMinutes = random.choice(minutes_values)
timeday = random.choice(('AM', 'PM'))
EventTimeWithZone = (EventTimeHours + ':' + ''.join(EventTimeMinutes) + ' ' + ''.join(timeday) + ' ' + ''.join(
ActivityTimezone))
select = Select(page.time)
select.select_by_visible_text(EventTimeWithZone)
time.sleep(5)
page.enter_customer_information_button.click()
FirstName = "Alexey"
page.first_name.send_keys(FirstName)
LastName = "Kolennikov"
page.last_name.send_keys(LastName)
EmailAddress = '6196511@mailinator.com'
page.email_address.send_keys(EmailAddress)
page.complete_booking_button.click()
time.sleep(2)
select = Select(page.channel_list)
time.sleep(5)
select.select_by_visible_text(NewChannelName)
assert select.first_selected_option.text == NewChannelName
def test_341(self):
page = ChannelPage()
page.open()
time.sleep(2)
entries1 = page.table_entries_qty.get_attribute('textContent')
page.add_channel_button.click()
time.sleep(5)
page.channel_name.send_keys(ChannelNameList[0])
page.save_button.click()
time.sleep(5)
assert page.channel_exist_alert.get_attribute('textContent') == 'Channel name ('+''.join(ChannelNameList)+') already exists, please choose another.'
page.OK_alert.click()
time.sleep(5)
entries2 = page.table_entries_qty.get_attribute('textContent')
assert entries1 == entries2 #FAILED BUG 3351
| 6196511/GoDo-AutoTests-Python-with-Selenium | Tests Marketing Hub-Channels/test_GODO-327-341 Add new channel (Channel name only)-2channels same channel name.py | test_GODO-327-341 Add new channel (Channel name only)-2channels same channel name.py | py | 4,374 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "webium.driver.close_driver",
"line_number": 22,
"usage_type": "call"
},
{
"api_name": "webium.driver.get_driver",
"line_number": 26,
"usage_type": "call"
},
{
"api_name": "Login.loginpage",
"line_number": 27,
"usage_type": "call"
},
{
"api_name": "c... |
14618555086 | #!/usr/bin/env python3
import argparse
import os
import pickle
import MultiProcess
def main():
parser = argparse.ArgumentParser(description="Will test mulitple resolution and return the resolution that give a the file size closer to the goad file size");
parser.add_argument('outputDir', type=str, help='path to the output dir')
parser.add_argument('--deleteLayout', type=str, help='id to layout to delete', default=None)
parser.add_argument('--trans', type=str, help='path to the trans software', default='../build/trans')
parser.add_argument('--config', type=str, help='path to the generated config file', default='./ConfigTest.ini')
parser.add_argument('-serverPort', type=int, help='server listen port', default=5042)
parser.add_argument('hostname', type=str, help='Server hostname')
parser.add_argument('authkey', type=str, help='Authentification key')
args = parser.parse_args()
if args.deleteLayout is None:
#SpecializedWorker = MultiProcess.FixedBitrateAndFixedDistances( args.trans, args.config, args.outputDir, args.hostname)
workerArg = MultiProcess.WorkerArg( args.trans, args.config, args.outputDir, args.hostname)
MultiProcess.RunClient(workerArg, args.hostname, args.serverPort, args.authkey)
else:
for (dirpath, dirnames, filenames) in os.walk(args.outputDir):
for dirname in dirnames:
if 'QEC' in dirname:
path = os.path.join(args.outputDir, dirname, 'quality_storage.dat')
print(path)
with open(path, 'rb') as i:
q = pickle.load(i)
for layoutId in q.names:
if args.deleteLayout in layoutId:
print(layoutId)
q.names.remove(layoutId)
k = []
for layoutId in k:
if args.deleteLayout in layoutId:
print ('***', layoutId)
k.append(layoutId)
for layoutId in k:
del q.goodQuality[layoutId]
k = []
for layoutId in k:
if args.deleteLayout in layoutId:
print ('###', layoutId)
k.append(layoutId)
for layoutId in k:
del q.badQuality[layoutId]
with open(path, 'wb') as o:
pickle.dump(q,o)
if __name__ == '__main__':
main()
| xmar/360Transformations | transformation/Scripts/client.py | client.py | py | 2,600 | python | en | code | 68 | github-code | 1 | [
{
"api_name": "argparse.ArgumentParser",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "MultiProcess.WorkerArg",
"line_number": 22,
"usage_type": "call"
},
{
"api_name": "MultiProcess.RunClient",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": ... |
37811907070 | from micarraylib.arraycoords.core import micarray
from micarraylib.arraycoords import array_shapes_raw
from micarraylib.arraycoords.array_shapes_utils import _polar2cart
import pytest
import numpy as np
def test_micarray_init():
arr = micarray(array_shapes_raw.cube2l_raw, "cartesian", None, "foo")
assert arr.name == "foo"
assert arr.capsule_names == list(array_shapes_raw.cube2l_raw.keys())
assert arr.coords_dict == array_shapes_raw.cube2l_raw
assert arr.coords_form == "cartesian"
assert arr.angle_units == None
# no coordinates form
with pytest.raises(ValueError):
micarray(array_shapes_raw.ambeovr_raw)
# cartesian with angle units
with pytest.raises(ValueError):
micarray(array_shapes_raw.cube2l_raw, "cartesian", "degree")
def test_micarray_center_coords():
arr = micarray(array_shapes_raw.cube2l_raw, "cartesian")
arr.center_coords()
assert np.allclose(
np.mean(np.array([c for c in arr.coords_dict.values()]), axis=0), [0, 0, 0]
)
arr = micarray(array_shapes_raw.ambeovr_raw, "polar", "degrees")
arr.center_coords()
assert np.allclose(
np.mean(np.array([c for c in arr.coords_dict.values()]), axis=0), [0, 0, 0]
)
assert arr.coords_form == "cartesian"
assert arr.angle_units == None
def test_micarray_standard_coords():
arr = micarray(array_shapes_raw.eigenmike_raw, "polar", "degrees")
arr.standard_coords("cartesian")
assert np.allclose(
np.mean(np.array([c for c in arr.coords_dict.values()]), axis=0), [0, 0, 0]
)
arr.standard_coords("polar")
assert arr.coords_form == "polar"
assert arr.angle_units == "radians"
# sanity check on range of angles in polar coordinates
assert all([c[0] > 0 and c[0] < 180 for c in arr.coords_dict.values()])
assert all([c[1] <= 180 and c[1] >= -180 for c in arr.coords_dict.values()])
# returning to cartesian should result in coordinates centered around zero
coords_cart = _polar2cart(arr.coords_dict, "radians")
assert np.allclose(
np.mean(np.array([v for v in coords_cart.values()]), axis=0),
[0, 0, 0],
)
# value when form not specified
with pytest.raises(ValueError):
arr.standard_coords()
| micarraylib/micarraylib | tests/test_arraycoords_core.py | test_arraycoords_core.py | py | 2,263 | python | en | code | 12 | github-code | 1 | [
{
"api_name": "micarraylib.arraycoords.core.micarray",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "micarraylib.arraycoords.array_shapes_raw.cube2l_raw",
"line_number": 10,
"usage_type": "attribute"
},
{
"api_name": "micarraylib.arraycoords.array_shapes_raw",
"li... |
42214484809 | #!/usr/bin/env python
# coding: utf-8
import copy
import logging
import numpy as np
import os
import pandas as pd
import random
import sys
from tarquinia.experiments import get_results
from tarquinia.model_selection import MeasureStratifiedKFold, \
FragmentStratifiedKFold, kfold_factory
from tarquinia.classifiers import MLP
from sklearn.svm import SVC
from sklearn.naive_bayes import GaussianNB
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
import warnings
from sklearn.exceptions import ConvergenceWarning
def set_seed(seed):
os.environ['PYTHONHASHSEED']=str(seed)
random.seed(seed)
np.random.seed(seed)
def experiment(experiment_name, dataset, col_features, col_label,
names, algs, grids,
cv_class=FragmentStratifiedKFold, outer_splits=4, inner_splits=3,
num_samples=2, logger=None):
cv_object = kfold_factory(cv_class, outer_splits, num_samples)
suite_name = cv_object.suite_name()
result, predictions = get_results(experiment_name, dataset,
col_features, col_label, names,
algs, grids, cv_class=cv_class,
outer_splits=outer_splits,
inner_splits=inner_splits,
num_samples=num_samples,
logger=logger)
for name in names:
first_col = f'{suite_name}-{name}-0'
last_col = f'{suite_name}-{name}-{outer_splits-1}'
majority_vote = (predictions.loc[:, first_col:last_col]
.sum(axis=1)
.apply(lambda x: 0 \
if x <= outer_splits/2 \
else 1))
confidence = (predictions.loc[:, first_col:last_col]
.sum(axis=1)
.apply(lambda x: x/outer_splits)
.apply(lambda x: x if x >= 0.5 \
else 1-x))
predictions[f'{suite_name}-{name}-majority'] = majority_vote
predictions[f'{suite_name}-{name}-confidence'] = confidence
for i in range(outer_splits):
del predictions[f'{suite_name}-{name}-{i}']
result.to_csv(f'models/{experiment_name}/{suite_name}/'
f'global_results.csv')
predictions.to_csv(f'models/{experiment_name}/{suite_name}/'
f'global_predictions.csv')
return result, predictions
def main():
experiment_name = 'JAS'
logging.basicConfig(
level=logging.INFO,
format='[{%(asctime)s %(filename)s:%(lineno)d} %(levelname)s - '
'%(message)s',
handlers=[
logging.FileHandler(filename=f'logs/{experiment_name}/tarquinia.log'),
logging.StreamHandler(sys.stderr)
]
)
logger = logging.getLogger('tarquinia')
np.random.seed(20220225)
random.seed(20220225)
warnings.filterwarnings("ignore", category=ConvergenceWarning)
dataset = 'data/data-tarquinia-latest.csv'
tarquinia = pd.read_csv(dataset, sep='\t', decimal=',', index_col='id')
col_features = tarquinia.columns[4:13]
print(col_features)
col_label = 'PROVENIENZA'
names = ['LDA', 'MLP', 'SVM-lin', 'SVM-rbf', 'SVM-poly',
'DT', 'RF', 'KNN', 'LR', 'NB']
algs = [LinearDiscriminantAnalysis, MLP,
SVC, SVC, SVC, DecisionTreeClassifier,
RandomForestClassifier, KNeighborsClassifier,
LogisticRegression, GaussianNB]
lp_lda = {'solver': ['svd', 'lsqr']}
lp_mlp = {'hidden_layer_sizes': [[2], [3], [2, 2]],
'activation': ['logistic', 'relu'],
'alpha': [1E-4, 1E-3],
'learning_rate': ['constant', 'adaptive'],
'learning_rate_init': [1E-4, 1E-3, 1E-2],
'shuffle': [True, False],
'momentum': [0.8, 0.9]
}
c_values = np.logspace(-4, 3, 10)
gamma_values = ['auto', 'scale'] + list(np.logspace(-4, 3, 10))
lp_svc_lin = {'C': c_values, 'kernel': ['linear']}
lp_svc_rbf = {'C': c_values, 'kernel': ['rbf'], 'gamma': gamma_values}
lp_svc_poly = {'C': c_values, 'kernel': ['poly'], 'degree': [2, 3, 5, 9]}
lp_dt = {'criterion': ['gini', 'entropy'],
#'max_leaf_nodes': [2],
'max_features': [None, 'sqrt'],
'max_depth': [None] + list(range(2, 10)),
'min_samples_split': list(range(2, 6)),
'min_samples_leaf': list(range(2, 6)),
'ccp_alpha': [0, 0.5, 1, 1.5]}
lp_rf = copy.deepcopy(lp_dt)
lp_rf['n_estimators'] = [3, 5, 7, 9]
lp_knn = {'n_neighbors': np.arange(1, 8),
'metric': ['minkowski'],
'p': list(range(2, 4))}
lp_lr = {'penalty': ['l1', 'l2'],
'C': c_values,
'solver': ['liblinear'],
'max_iter': [5000]}
lp_nb = {}
grids = [lp_lda, lp_mlp, lp_svc_lin, lp_svc_rbf, lp_svc_poly,
lp_dt, lp_rf, lp_knn, lp_lr, lp_nb]
cv_class = MeasureStratifiedKFold
outer_splits = 4
inner_splits = 3
num_samples = None
experiment(experiment_name, tarquinia, col_features, col_label,
names, algs, grids, cv_class=cv_class,
outer_splits=outer_splits, inner_splits=inner_splits,
num_samples=num_samples, logger=logger)
cv_class = FragmentStratifiedKFold
experiment(experiment_name, tarquinia, col_features, col_label,
names, algs, grids, cv_class=cv_class,
outer_splits=outer_splits, inner_splits=inner_splits,
num_samples=num_samples, logger=logger)
num_samples = 2
experiment(experiment_name, tarquinia, col_features, col_label,
names, algs, grids, cv_class=cv_class,
outer_splits=outer_splits, inner_splits=inner_splits,
num_samples=num_samples, logger=logger)
if __name__ == '__main__':
main() | dariomalchiodi/JAS-Tarquinia-classification | experiments/JAS/experiments-with-dim-reduction.py | experiments-with-dim-reduction.py | py | 6,585 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "os.environ",
"line_number": 30,
"usage_type": "attribute"
},
{
"api_name": "random.seed",
"line_number": 31,
"usage_type": "call"
},
{
"api_name": "numpy.random.seed",
"line_number": 32,
"usage_type": "call"
},
{
"api_name": "numpy.random",
"lin... |
4693870026 | from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from time import sleep
from itertools import product
from string import ascii_uppercase
from difflib import SequenceMatcher
import json
base_url = "https://www.oscaro.es/"
browser = webdriver.Chrome(ChromeDriverManager().install())
run = bool()
start = "BFJ"
end = "HBP"
browser.get(base_url)
sleep(5)
def longestSubstringFinder(string1, string2): # TODO
seqMatch = SequenceMatcher(None, string1, string2)
match = seqMatch.find_longest_match(0, len(string1), 0, len(string2))
answer = string1[match.a: match.a + match.size]
return answer
def waitForCaptcha():
while True:
sleep(2)
if len(browser.find_elements_by_id("recaptcha_widget")) == 0:
break
def getCommon(carList):
longest = carList[0]
for car in carList[1:]:
longest = longestSubstringFinder(longest, car)
return longest
def reload():
browser.get(base_url)
waitForCaptcha()
old_coches = None
database = dict()
try:
for e in product(ascii_uppercase, repeat=3):
matricula = "2860" + "".join(e)
if not run and matricula[-3:] == start:
run = True
if run:
print(matricula[:4] + " " + matricula[-3:], " ----> ", end="")
while True:
good = False
waitForCaptcha()
if len(browser.find_elements_by_class_name("vehicle-selected")) > 0:
change = browser.find_element_by_class_name(
"vehicle-selected").find_element_by_xpath("./div/a")
change.click()
sleep(5)
waitForCaptcha()
if len(browser.find_elements_by_id("vehicle-input-plate")) > 0:
box = browser.find_element_by_id("vehicle-input-plate")
box.clear()
box.send_keys(matricula)
button = box.find_element_by_xpath("../../../button")
button.click()
sleep(5)
waitForCaptcha()
coches = None
if len(browser.find_elements_by_class_name("plate")) > 0:
if len(browser.find_elements_by_class_name("form-message")) > 0:
coches = ["No Info"]
good = True
elif len(browser.find_element_by_class_name("plate").find_elements_by_tag_name("select")) > 0:
coches = [e.get_attribute("innerHTML") for e in browser.find_element_by_class_name(
"plate").find_elements_by_tag_name("option")[1:]]
if coches == old_coches or coches == []:
reload()
continue
good = True
old_coches = coches
else:
reload()
continue
elif len(browser.find_elements_by_class_name("vehicle-selected")) > 0:
coches = [browser.find_element_by_class_name(
"vehicle-selected").find_elements_by_xpath("./div/span")[0].get_attribute("innerHTML")]
good = True
else:
reload()
continue
if good:
print(coches)
database[matricula] = coches
break
if run and matricula[-3:] == end:
run = False
finally:
#with open()
print("\n"*4, "dumping database:\n\n", json.dumps(database, indent=4))
| IllicLanthresh/random-stuff | matricula selenium database.py | matricula selenium database.py | py | 3,786 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "selenium.webdriver.Chrome",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "selenium.webdriver",
"line_number": 11,
"usage_type": "name"
},
{
"api_name": "webdriver_manager.chrome.ChromeDriverManager",
"line_number": 11,
"usage_type": "call"
},
... |
1346226818 | import torch.utils.data as data
from PIL import Image
import os
import pickle as dill
import numpy as np
import torch
from torch.utils.data import TensorDataset
class GetDataset():
def __init__(self, data_root, unseen_index, val_split):
with open(os.path.join(data_root, 'af_normal_data_processed.pkl'), 'rb') as file:
data = dill.load(file)
datasets = ['CSPC_data', 'PTB_XL_data', 'G12EC_data', 'Challenge2017_data']
test_data = []
train_datas = []
val_datas = []
for source in datasets:
af_data, normal_data = data[source]
all_data = np.concatenate((af_data, normal_data), axis=0)
all_label = np.zeros((len(all_data),))
all_label[len(af_data):] = 1
# use all data of this source as test data
permuted_idx = np.random.permutation(len(all_data))
x = all_data[permuted_idx]
y = all_label[permuted_idx]
split_idx = int(val_split * len(all_data))
x_val = all_data[permuted_idx[split_idx:]]
y_val = all_label[permuted_idx[split_idx:]]
x_train = all_data[permuted_idx[:split_idx]]
y_train = all_label[permuted_idx[:split_idx]]
# swap axes
x = x.swapaxes(1, 2)
x_train = x_train.swapaxes(1, 2)
x_val = x_val.swapaxes(1, 2)
test_data.append([x, y])
train_datas.append([x_train, y_train])
val_datas.append([x_val, y_val])
self.train_datas = train_datas
self.val_datas = val_datas
a = [0, 1, 2, 3]
a.remove(unseen_index)
self.unseen_data = test_data[unseen_index]
del self.train_datas[unseen_index]
del self.val_datas[unseen_index]
print(0)
def get_datasets(self):
train_datasets = []
for train_data in self.train_datas:
X_train, Y_train = train_data
X_train = torch.from_numpy(X_train).float()
Y_train = torch.from_numpy(Y_train).long()
dataset = TensorDataset(X_train, Y_train)
train_datasets.append(dataset)
val_datasets = []
for val_data in self.val_datas:
X_val, Y_val = val_data
X_val = torch.from_numpy(X_val).float()
Y_val = torch.from_numpy(Y_val).long()
dataset = TensorDataset(X_val, Y_val)
val_datasets.append(dataset)
X_test, Y_test = self.unseen_data
X_test = torch.from_numpy(X_test).float()
Y_test = torch.from_numpy(Y_test).long()
test_dataset = TensorDataset(X_test, Y_test)
return train_datasets, val_datasets, test_dataset
| Neronjust2017/DANN_ECG | data_loader.py | data_loader.py | py | 2,724 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "os.path.join",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 12,
"usage_type": "attribute"
},
{
"api_name": "torch.utils.data",
"line_number": 13,
"usage_type": "name"
},
{
"api_name": "pickle.load",
"line_nu... |
72921401315 | from datetime import date
from django.conf import settings
from edc_sync_data_report.classes import ClientCollectSummaryData
from edc_sync_data_report.classes.notification import Notification
from edc_sync_data_report.classes.summary_data import SummaryData
def send_sync_report():
sender = Notification()
sender.build()
def prepare_confirmation_ids():
collector = SummaryData()
created_date = date.today()
site_id = settings.SITE_ID
collector.collect_primary_key_and_save(site_id=site_id, created_date=created_date)
def prepare_summary_count_data():
collector = ClientCollectSummaryData()
collector.create_summary_data()
def prepare_end_of_day_detailed_report():
collector = SummaryData()
created_date = date.today()
site_id = settings.SITE_ID
collector.collect_primary_key_and_save(site_id=site_id, created_date=created_date) | botswana-harvard/edc-sync-data-report | edc_sync_data_report/tasks.py | tasks.py | py | 884 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "edc_sync_data_report.classes.notification.Notification",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "edc_sync_data_report.classes.summary_data.SummaryData",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "datetime.date.today",
"line_numb... |
5344438377 | from collections import UserDict
from datetime import datetime
import re
import csv
# ************************* CLASSES *************************
class Field ():
def __init__(self, value) -> None:
self.value = value
def __str__(self) -> str:
return str(self.value)
def __repr__(self) -> str:
return str(self)
class Name (Field):
pass
class Phone (Field):
def __init__(self, value=None):
self.value = value
@property
def value(self):
return self._value
@value.setter
def value(self, value):
if value is None:
self._value = value
else:
self._value = self.number_phone(value)
def number_phone(self, phone:str):
if not re.match(r"^\+[\d]{12}$", phone):
raise ValueError
return phone
class Birthday (Field):
def __init__(self, value) -> None:
# super().__init__(value)
self.__value = None
self.value = value
@property
def value (self):
# return self.__value.strftime('%d-%m-%Y')
return self.__value
@value.setter
def value(self, value):
try:
self.__value = datetime.strptime(value, '%d-%m-%Y')
except ValueError:
raise ValueError('Wrong DATE format. Please enter the DATE in the format - dd-mm-yyyy')
def __str__(self) -> str:
return str(self.value.strftime('%d-%m-%Y'))
def __repr__(self) -> str:
return str(self)
class Record ():
def __init__(self, name:Name, phone:Phone = None, birthday:Birthday = None):
self.name = name
self.phones = [phone] if phone else []
self.birthday = birthday
# Добавление телефона из адресной книги
def add_phone(self, phone:Phone):
self.phones.append(phone)
# Удаление телефона из адресной книги
def remove_record(self, phone:Phone):
# self.phones.remove(phone)
for i, p in enumerate(self.phones):
if p.value == phone.value:
self.phones.pop(i)
return f"Phone {phone} deleted successfully"
return f'Contact has no phone {phone}'
# Изменение телефона в адресной книги
def change_phone(self, old_phone:Phone, new_phone:Phone):
for i, p in enumerate(self.phones):
if p.value == old_phone.value:
self.phones[i] = new_phone
return f'Phone {old_phone} change to {new_phone}'
return f'Contact has no phone {old_phone}'
# день рождения
def set_birthday(self, birthday):
self.birthday = birthday
def get_birthday (self):
return self.birthday.value if self.birthday else None
def days_to_birthday(self):
if self.birthday:
dateB = self.birthday.value
today = datetime.today()
# current_year_dateB = datetime.date(today.year, dateB.month, dateB.day)
current_year_dateB = dateB.replace(year=today.year)
if current_year_dateB < today:
current_year_dateB = datetime.date(today.year+1, dateB.month, dateB.day)
delta =current_year_dateB - today
return delta.days
return None
def __str__(self):
result = ''
phones = ", ".join([str(phone) for phone in self.phones])
if self.birthday:
# date_bd = self.birthday.strftime("%m/%d/%Y, %H:%M:%S")
result += f"{self.name}: {phones}. Birthday: {self.birthday}\n"
else:
result += f"{self.name}: {phones}"
return result
class AddressBook(UserDict):
index = 0
fieldnames = ['Name','Phones','Birthday']
def add_record(self, record: Record):
self.data[record.name.value] = record
def save_csv(self, csv_file):
try:
with open (csv_file, 'w', newline ='') as f:
writer = csv.DictWriter(f, fieldnames = self.fieldnames)
writer.writeheader()
for name in self.data:
record = self.data[name]
# for record in user_contacts:
name = record.name.value
phones = [phone.value for phone in record.phones]
B_day = record.birthday
writer.writerow({'Name': name, 'Phones': phones, "Birthday": B_day})
except:
return ...
def read_csv(self, csv_file):
try:
with open (csv_file, 'r', newline ='') as f:
reader = csv.DictReader(f)
for row in reader:
csv_name = Name(row['Name'])
# csv_phones = [Phone(phone) for phone in eval(row['Phones'])] if row['Phones'] !='[]' else None
# csv_birthday = Birthday(row['Birthday']) if row['Birthday'] != '' else None
csv_phones = [Phone(phone) for phone in eval(row['Phones'])] if row['Phones'] else None
csv_birthday = Birthday(row['Birthday']) if row['Birthday'] else None
rec = Record(csv_name, birthday=csv_birthday)
for phone in csv_phones:
rec.add_phone(phone)
self.add_record(rec)
except (FileNotFoundError, AttributeError, KeyError, TypeError):
pass
def search(self, param):
if len(param) < 3:
return
result = []
for rec in self.data.values():
if param in str (rec):
result.append(str(rec))
str_result = '\n'.join(result)
return f"{str_result}"
def __iter__(self):
if len(self) > 0:
self.keys_list = sorted(self.data.keys())
return self
def __next__(self):
if self.index >=len(self.keys_list):
raise StopIteration
else:
name =self.keys_list[self.index]
self.index +=1
return self[name]
def iterator(self, n=2):
self.keys_list = sorted(self.data.keys())
if self.index < len(self.keys_list):
yield from [self[name] for name in self.keys_list[self.index:self.index+n]]
self.index +=n
else:
self.index = 0
self.keys_list =[]
# ************************* CLASSES ************************* | GievskiyIgor/GoIT_lesson_12 | PhoneBook_classes.py | PhoneBook_classes.py | py | 6,683 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "re.match",
"line_number": 37,
"usage_type": "call"
},
{
"api_name": "datetime.datetime.strptime",
"line_number": 55,
"usage_type": "call"
},
{
"api_name": "datetime.datetime",
"line_number": 55,
"usage_type": "name"
},
{
"api_name": "datetime.dateti... |
19457690233 | import random, copy
from space_objects import Bullet, RocketBaseAction, Asteroid,Rocket, AsteroidSize
from constants import *
import pygame
import time
import math
from dto import collides, Space_object_DTO, copy_object
from enum import Enum
import tensorflow as tf
import numpy as np
class Agent():
def __init__(self, player_number):
super().__init__()
self.input=False
self.player_number = player_number
self.shoot_reload_ticks = 0
self.plan = []
self.target_asteroid = None
self.inactiv_ticks = 0
self.active_ticks = 0
self.finished_plan = False
self.finished_plan_attack = False
self.previous_actions_empty = False
self.attack_count = 0
self.evasion_count = 0
self.defense_count = 0
self.stop_count = 0
def assign_objects_to_agent(self, state):
if self.player_number == 1:
own_rocket = state.player_one_rocket
enemy_rocket = state.player_two_rocket
own_asteroids = state.player_one_asteroids
enemy_asteroids = state.player_two_asteroids
own_bullets = state.player_one_bullets
enemy_bullets = state.player_two_bullets
else:
own_rocket = state.player_two_rocket
enemy_rocket = state.player_one_rocket
own_asteroids = state.player_two_asteroids
enemy_asteroids = state.player_one_asteroids
enemy_bullets = state.player_one_bullets
own_bullets = state.player_two_bullets
return own_rocket, enemy_rocket, state.neutral_asteroids, own_asteroids, enemy_asteroids, own_bullets, enemy_bullets
def finish_plan(self):
if self.finished_plan:
self.previous_actions_empty = True
self.finished_plan = True
self.plan = []
self.target_asteroid = None
def store_plan(self, actions):
self.plan = actions
#self.finished_plan = False
self.finished_plan_attack = False
self.finished_plan_evasion = False
self.finished_plan_gp = False
def choose_action_from_plan(self):
actions = []
if len(self.plan) > 0:
actions = self.plan.pop(0)
else:
if self.finished_plan:
self.previous_actions_empty = True
actions = []
self.plan = []
# TODO: added, check
self.finished_plan = True
self.finished_plan_attack = True
self.finished_plan_evasion = True
self.finished_plan_gp = True
return actions
def reevaluate_plan(self):
if (self.inactiv_ticks > get_inactive_steps_limit()):
#if (self.inactiv_ticks > INACTIV_STEPS_LIMIT):
self.inactiv_ticks = 0
self.previous_actions_empty = False
self.finished_plan = False
return True
if self.finished_plan and not self.previous_actions_empty:
#self.finished_plan = False
self.inactiv_ticks = 0
self.previous_actions_empty = False
return True
self.inactiv_ticks = self.inactiv_ticks + 1
return False
def two_points_distance_squared(self, pointA, pointB):
return int(math.pow(pointA[0]-pointB[0], 2)+math.pow(pointA[1]-pointB[1], 2))
def rocket_asteroid_distance_squared(self, rocket, asteroid):
ast_x = asteroid.centerx
ast_y = asteroid.centery
rocket_x = rocket.centerx
rocket_y = rocket.centery
ast_x_width = ast_x + SCREEN_WIDTH
ast_y_height = ast_y + SCREEN_HEIGHT
min_distance = self.two_points_distance_squared((ast_x, ast_y), (rocket_x, rocket_y))
#shift asteroid to + SCREEN_WIDTH
dist = self.two_points_distance_squared((rocket_x,rocket_y), (ast_x_width, ast_y))
if dist < min_distance:
min_distance = dist
#shift asteroid to + SCREEN_HEIGHT
dist = self.two_points_distance_squared((rocket_x,rocket_y), (ast_x, ast_y_height))
if dist < min_distance:
min_distance = dist
#shift asteroid to + SCREEN_HEIGHT and + SCREEN_WIDTH
dist = self.two_points_distance_squared((rocket_x, rocket_y), (ast_x_width, ast_y_height))
if dist < min_distance:
min_distance = dist
return min_distance
def object_object_vector(self, objA, objB):
return [objA.centerx - objB.centerx, objA.centery - objB.centery]
def number_of_asteroids_in_range(self, rocket, neutral_asteroids, enemy_asteroids, range=ENEMY_ASTEROIDS_RADIUS):
range_squared = range * range
number_of_asteroids = 0
for neutral_asteroid in neutral_asteroids:
if self.rocket_asteroid_distance_squared(rocket, neutral_asteroid) < range_squared:
number_of_asteroids +=1
for enemy_asteroid in enemy_asteroids:
if self.rocket_asteroid_distance_squared(rocket, enemy_asteroid) < range_squared:
number_of_asteroids += 1
return number_of_asteroids
def find_N_closest_asteroids(self, rocket, neutral_asteroids, enemy_asteroids, N=3):
arr = []
for neutral_asteroid in neutral_asteroids:
arr.append([self.object_object_vector(neutral_asteroid, rocket),
self.rocket_asteroid_distance_squared(rocket, neutral_asteroid)])
for enemy_asteroid in enemy_asteroids:
arr.append([self.object_object_vector(enemy_asteroid, rocket),
self.rocket_asteroid_distance_squared(rocket, enemy_asteroid)])
sorted_by_distance = sorted(arr, key=lambda x: x[1])
if len(sorted_by_distance) < N:
for i in range(N-len(sorted_by_distance)):
sorted_by_distance.append([(SCREEN_WIDTH, SCREEN_HEIGHT), SCREEN_FULL_DISTANCE_SQUARED])
return sorted_by_distance[0:N]
def low_level_state_info(self, state, N_nearest_asteroids = 3):
# self speed, self angle, self shoot cooldown, enemy vector, enemy speed, N nearest asteroids vectors
own_rocket, enemy_rocket, neutral_asteroids, own_asteroids, enemy_asteroids, own_bullets, enemy_bullets \
= self.assign_objects_to_agent(state)
own_rocket_speed = [own_rocket.speedx, own_rocket.speedy]
own_rocket_angle = [own_rocket.angle]
own_rocket_shoot_ticks = [self.shoot_reload_ticks]
enemy_rocket_vector = self.object_object_vector(own_rocket, enemy_rocket)
enemy_speed = [enemy_rocket.speedx, enemy_rocket.speedy]
near_asteroids = self.find_N_closest_asteroids(own_rocket, neutral_asteroids, enemy_asteroids, N=3)
asteroids_positions = []
for near_asteroid in near_asteroids:
asteroids_positions.append(near_asteroid[0][0])
asteroids_positions.append(near_asteroid[0][1])
result = np.array(own_rocket_speed +
own_rocket_angle +
own_rocket_shoot_ticks +
enemy_rocket_vector +
enemy_speed +
asteroids_positions)
result = np.reshape(result, newshape=(1, -1))
return result
def evade_asteroid(self, rocket, asteroid):
rocket_copy = copy_object(rocket)
asteroid_copy = copy_object(asteroid)
rotation_limit = 15
for left_turns in range(0, rotation_limit):
evaded, accelerate_steps = self.evade_by_continual_accelerating(rocket_copy, asteroid_copy)
if evaded:
if left_turns == 0:
plan = [[RocketBaseAction.ACCELERATE] for i in range(accelerate_steps)]
return plan, accelerate_steps
elif left_turns < 15:
plan = [[RocketBaseAction.ROTATE_LEFT] for i in range(left_turns)]
plan.extend([[RocketBaseAction.ACCELERATE] for i in range(accelerate_steps)])
return plan, left_turns + accelerate_steps
#if self.evade_by_accelerating(rocket_copy, asteroid_copy):
# if left_turns == 0:
# plan = [[RocketBaseAction.ACCELERATE] for i in range(10)]
# return plan, 5
# elif left_turns < 15:
# plan = [[RocketBaseAction.ROTATE_LEFT] for i in range(left_turns)]
# plan.extend([[RocketBaseAction.ACCELERATE, RocketBaseAction.ROTATE_LEFT] for i in range(10)])
# return plan, left_turns + 5
rocket_copy.rotate_left()
rocket_copy.move()
asteroid_copy.move()
rocket_copy = copy_object(rocket)
asteroid_copy = copy_object(asteroid)
for right_turns in range(0, rotation_limit):
evaded, accelerate_steps = self.evade_by_continual_accelerating(rocket_copy, asteroid_copy)
if evaded:
if right_turns == 0:
plan = [[RocketBaseAction.ACCELERATE] for i in range(accelerate_steps)]
return plan, accelerate_steps
elif right_turns < 15:
plan = [[RocketBaseAction.ROTATE_RIGHT] for i in range(right_turns)]
plan.extend([[RocketBaseAction.ACCELERATE] for i in range(accelerate_steps)])
return plan, right_turns + accelerate_steps
#if self.evade_by_accelerating(rocket_copy, asteroid_copy):
# plan = [[RocketBaseAction.ROTATE_RIGHT] for i in range(right_turns)]
# plan.extend([[RocketBaseAction.ACCELERATE, RocketBaseAction.ROTATE_RIGHT] for i in range(10)])
# return plan, right_turns + 5
rocket_copy.rotate_right()
rocket_copy.move()
asteroid_copy.move()
return [], NOT_FOUND_STEPS_COUNT
def stop_moving(self, rocket):
rocket_copy = copy_object(rocket)
if (math.fabs(rocket_copy.speedx) + math.fabs(rocket_copy.speedy)) < 16:
return False, [], 0
if rocket_copy.speedx == 0:
if rocket_copy.speedy > 0:
move_angle = 270
elif rocket_copy.speedy < 0:
move_angle = 90
else:
move_angle = (math.atan(- rocket_copy.speedy / rocket_copy.speedx) * 180) / math.pi
if rocket_copy.speedx < 0:
move_angle = move_angle + 180
move_angle = move_angle % 360
reverse_angle = (move_angle + 180 - 90) % 360
left_turns = 0
right_turns = 0
if ((reverse_angle + 360 - rocket_copy.angle) % 360) < 180:
left_turns = int(((reverse_angle + 360 - rocket_copy.angle) % 360) // 12)
else:
right_turns = int((360 - ((reverse_angle + 360 - rocket_copy.angle) % 360)) // 12)
rocket_copy.rotate_left(left_turns)
rocket_copy.rotate_right(right_turns)
accelerate_count = 0
while (math.fabs(rocket_copy.speedx) + math.fabs(rocket_copy.speedy)) > 14 and accelerate_count < 10:
rocket_copy.accelerate()
accelerate_count = accelerate_count + 1
actions = []
if left_turns > 0:
actions = [[RocketBaseAction.ROTATE_LEFT] for i in range(left_turns)]
if right_turns > 0:
actions = [[RocketBaseAction.ROTATE_RIGHT] for i in range(right_turns)]
for i in range(accelerate_count):
actions.append([RocketBaseAction.ACCELERATE])
return True, actions, left_turns + right_turns + accelerate_count
def evade_by_continual_accelerating(self, rocket, asteroid):
# how many maximal times can rocket accelerate in attemp to avoid asteroid
accelerate_limit = 20
# how many steps it is checking whether they collided or rocket escaped
evade_steps_limit = 20
for accelerate_count in range(accelerate_limit):
rocket_copy = copy_object(rocket)
asteroid_copy = copy_object(asteroid)
collided = False
for step_number in range(evade_steps_limit):
if collides(rocket_copy, asteroid_copy):
collided = True
break
if step_number < accelerate_count:
rocket_copy.accelerate()
#rocket_copy.health_bar_color = PLAYER_TWO_COLOR
#draw_module.draw_rocket_only(rocket_copy)
#draw_module.draw_circle((rocket_copy.centerx, rocket_copy.centery))
#draw_module.draw_circle((asteroid_copy.centerx, asteroid_copy.centery))
#draw_module.render()
#pygame.draw.circle(self.screen, (0, 0, 0, 0), (rocket_copy.centerx, rocket_copy.centery), 10)
#pygame.draw.circle(self.screen, (0, 0, 0, 0), (asteroid_copy.centerx, asteroid_copy.centery), 10)
#pygame.display.update()
rocket_copy.move()
asteroid_copy.move()
if not collided:
return True, accelerate_count
return False, NOT_FOUND_STEPS_COUNT
def evade_by_accelerating(self, rocket, asteroid):
rocket_copy = copy_object(rocket)
asteroid_copy = copy_object(asteroid)
accelerate_limit = 20
for accelerate_count in range(accelerate_limit):
if collides(rocket_copy, asteroid_copy):
# time.sleep(0.2)
return False
# pygame.draw.circle(self.screen, (255,0,0), (asteroid_copy.centerx, asteroid_copy.centery), asteroid_copy.radius)
# pygame.draw.circle(self.screen, (0, 255, 0), (rocket_copy.centerx, rocket_copy.centery), rocket_copy.radius)
# pygame.display.update()
rocket_copy.accelerate()
rocket_copy.move()
asteroid_copy.move()
# time.sleep(0.2)
return True
def first_impact_neutral_asteroid_numpy(self, rocket, neutral_asteroids, own_bullets):
steps_limit = 60
(ret_ast, ret_count) = (None, steps_limit + 1)
if len(neutral_asteroids) == 0:
return (None, steps_limit + 1)
asteroids_pos = np.array([[neutral_asteroid.centerx, neutral_asteroid.centery] for neutral_asteroid in neutral_asteroids])
asteroids_speed = np.array([[neutral_asteroid.speedx, neutral_asteroid.speedy] for neutral_asteroid in neutral_asteroids])
asteroids_radii = np.array([neutral_asteroid.radius for neutral_asteroid in neutral_asteroids])
own_bullets_pos = np.array([[bullet.centerx, bullet.centery] for bullet in own_bullets])
own_bullets_speed = np.array([[bullet.speedx, bullet.speedy] for bullet in own_bullets])
own_bullets_radii = np.array([bullet.radius for bullet in own_bullets])
# Soucet polomeru Asteroid x strela
radii = np.add(asteroids_radii[:, np.newaxis], own_bullets_radii)
asteroids_rocket_differences = np.zeros((len(neutral_asteroids), 2))
if (len(own_bullets) > 0):
asteroids_bullets_differences = np.zeros((len(neutral_asteroids), len(own_bullets), 2))
for steps_count in range(steps_limit):
# ASTEROID -- ROCKET collisions
# Odecitam to oboustrane, protoze tim, ze se pohybuju v uzavrenem souradnicovem prostoru 0-900 x 0-600,
# tak mi jednostrane odecitani nemusi dat jejich nejmensi rozdily v souradnicich
np.minimum(np.mod(np.subtract(asteroids_pos, [rocket.centerx, rocket.centery]), MOD_VAL),
np.mod(np.subtract([rocket.centerx, rocket.centery], asteroids_pos), MOD_VAL),
out = asteroids_rocket_differences)
ast_rocket_distances = np.linalg.norm(asteroids_rocket_differences, axis=1)
itemindex = np.where(ast_rocket_distances < asteroids_radii + rocket.radius)
if len(itemindex[0]) > 0:
index_of_ast_np = itemindex[0][0]
ret_ast = neutral_asteroids[index_of_ast_np]
ret_count = steps_count
break
# ASTEROID -- BULLET collisions
if (len(own_bullets)>0):
np.minimum(np.mod(np.subtract(asteroids_pos[:, np.newaxis], own_bullets_pos), MOD_VAL),
np.mod(np.subtract(own_bullets_pos, asteroids_pos[:, np.newaxis]), MOD_VAL),
out = asteroids_bullets_differences)
ast_bullets_distances = np.linalg.norm(asteroids_bullets_differences, axis=2)
itemindex = np.where(ast_bullets_distances < radii)
if len(itemindex[0]>0):
# nastavim strele a asteroidu, ktere se srazili, zaporny polomer == uz se nemohou s nicim srazit v dalsim kroku
radii[itemindex[0][0], :] = -100
radii[:, itemindex[1][0]] = -100
asteroids_radii[itemindex[0][0]] = -100
own_bullets_pos = np.add(own_bullets_pos, own_bullets_speed)
own_bullets_pos = np.mod(own_bullets_pos, MOD_VAL)
asteroids_pos = np.add(asteroids_pos, asteroids_speed)
asteroids_pos = np.mod(asteroids_pos, MOD_VAL)
return (ret_ast, ret_count)
def first_impact_neutral_asteroid(self, rocket, neutral_asteroids, own_bullets):
steps_limit = IMPACT_RADIUS
own_bullets_copy = [copy_object(own_bullet) for own_bullet in own_bullets]
neutral_asteroids_copy = [copy_object(neutral_asteroid) for neutral_asteroid in neutral_asteroids]
neutral_asteroids_copy2 = [copy_object(neutral_asteroid) for neutral_asteroid in neutral_asteroids]
rocket_copy = copy_object(rocket)
for neutral_asteroid in neutral_asteroids_copy:
neutral_asteroid.valid = True
for steps_count in range(steps_limit):
# pygame.draw.circle(self.screen, (0, 255, 0), (rocket_copy.centerx, rocket_copy.centery), rocket_copy.radius)
for neutral_asteroid in neutral_asteroids_copy:
# pygame.draw.circle(self.screen, (255, 0, 0), (neutral_asteroid.centerx, neutral_asteroid.centery),
# neutral_asteroid.radius)
if collides(rocket_copy, neutral_asteroid):
for neutral_asteroid_reverse in neutral_asteroids_copy:
neutral_asteroid_reverse.reverse_move(steps_count)
return (neutral_asteroid, steps_count)
for neutral_asteroid in neutral_asteroids_copy:
for bullet in own_bullets_copy:
if collides(neutral_asteroid, bullet):
own_bullets_copy.remove(bullet)
neutral_asteroids_copy.remove(neutral_asteroid)
break
for neutral_asteroid in neutral_asteroids_copy:
neutral_asteroid.move()
for bullet in own_bullets_copy:
bullet.move()
rocket_copy.move()
return (None, steps_limit + 1)
def first_impact_enemy_asteroid(self, rocket, enemy_asteroids, own_bullets):
steps_limit = IMPACT_RADIUS
own_bullets_copy = [copy_object(own_bullet) for own_bullet in own_bullets]
rocket_copy = copy_object(rocket)
enemy_asteroids_copy = [copy_object(enemy_asteroid) for enemy_asteroid in enemy_asteroids]
for steps_count in range(steps_limit):
for enemy_asteroid in enemy_asteroids_copy:
# if rocket.collision_rect.colliderect(enemy_asteroid.collision_rect):
if collides(rocket_copy, enemy_asteroid):
for enemy_asteroid_reverse in enemy_asteroids_copy:
enemy_asteroid_reverse.reverse_move(steps_count)
# rocket.reverse_move(steps_count)
return(enemy_asteroid, steps_count)
for enemy_asteroid in enemy_asteroids_copy:
for bullet in own_bullets_copy:
# if enemy_asteroid.collision_rect.colliderect(bullet.collision_rect):
if collides(enemy_asteroid, bullet):
enemy_asteroids_copy.remove(enemy_asteroid)
own_bullets_copy.remove(bullet)
break
for bullet in own_bullets_copy:
bullet.move()
for enemy_asteroid in enemy_asteroids_copy:
enemy_asteroid.move()
rocket_copy.move()
# rocket.reverse_move(steps_limit - 1)
for enemy_asteroid in enemy_asteroids_copy:
enemy_asteroid.reverse_move(steps_limit - 1)
return(None, steps_limit + 1)
def unshot_enemy_and_neutral_asteroids(self, own_bullets, enemy_bullets, neutral_asteroids, enemy_asteroids):
own_bullets_copy = [copy_object(own_bullet) for own_bullet in own_bullets]
enemy_bullets_copy = [copy_object(enemy_bullet) for enemy_bullet in enemy_bullets]
neutral_asteroids_copy = [copy_object(neutral_asteroid) for neutral_asteroid in neutral_asteroids]
enemy_asteroids_copy = [copy_object(enemy_asteroid) for enemy_asteroid in enemy_asteroids]
for step in range(BULLET_LIFE_COUNT):
for neutral_asteroid in neutral_asteroids_copy:
for own_bullet in own_bullets_copy:
if own_bullet.is_alive():
if collides(own_bullet, neutral_asteroid):
# if own_bullet.collision_rect.colliderect(neutral_asteroid.collision_rect):
neutral_asteroids_copy.remove(neutral_asteroid)
own_bullets_copy.remove(own_bullet)
for enemy_asteroid in enemy_asteroids_copy:
for own_bullet in own_bullets_copy:
if own_bullet.is_alive():
if collides(own_bullet, enemy_asteroid):
# if own_bullet.collision_rect.colliderect(enemy_asteroid.collision_rect):
enemy_asteroids_copy.remove(enemy_asteroid)
own_bullets_copy.remove(own_bullet)
for neutral_asteroid in neutral_asteroids_copy:
for enemy_bullet in enemy_bullets_copy:
if enemy_bullet.is_alive():
if collides(enemy_bullet, neutral_asteroid):
# if enemy_bullet.collision_rect.colliderect(neutral_asteroid.collision_rect):
neutral_asteroids_copy.remove(neutral_asteroid)
enemy_bullets_copy.remove(enemy_bullet)
for own_bullet in own_bullets_copy:
own_bullet.move()
for enemy_bullet in enemy_bullets_copy:
enemy_bullet.move()
for neutral_asteroid in neutral_asteroids_copy:
neutral_asteroid.move()
for enemy_asteroid in enemy_asteroids_copy:
enemy_asteroid.move()
for neutral_asteroid in neutral_asteroids_copy:
neutral_asteroid.reverse_move(BULLET_LIFE_COUNT)
for enemy_asteroid in enemy_asteroids_copy:
enemy_asteroid.reverse_move(BULLET_LIFE_COUNT)
return (neutral_asteroids_copy, enemy_asteroids_copy)
def shoot_in_all_directions_to_hit_enemy(self, own_rocket, enemy_rocket, neutral_asteroids, enemy_asteroids, own_bullets, enemy_bullets):
# incrementalni pohyb prostredi
# mozna bude nutne to postupne vzdy posunout, vratit a zkusit dalsi
own_rocket_copy = copy_object(own_rocket)
enemy_rocket_copy = copy_object(enemy_rocket)
neutral_asteroids_copy = [copy_object(neutral_asteroid) for neutral_asteroid in neutral_asteroids]
# enemy_asteroids_copy = [copy_object(enemy_asteroid) for enemy_asteroid in enemy_asteroids]
enemy_asteroids_copy = [copy_object(enemy_asteroid) for enemy_asteroid in enemy_asteroids if enemy_asteroid.size_index != AsteroidSize.SMALL]
own_bullets_copy = [copy_object(own_bullet) for own_bullet in own_bullets]
enemy_bullets_copy = [copy_object(enemy_bullet) for enemy_bullet in enemy_bullets]
shoot_type = RocketBaseAction.SHOT
left_found = False
# zkouším postupně všechny rotace vlevo
for rotation_count in range(int(360 / 12)):
# if self.try_shoot_some_asteroid_to_enemy_rocket(own_rocket, enemy_rocket, neutral_asteroids, enemy_asteroids, own_bullets, enemy_bullets):
# left_found, left_steps = True, rotation_count
# break
hit, shoot_type = self.try_shoot_some_asteroid_to_enemy_rocket(own_rocket_copy, enemy_rocket_copy, neutral_asteroids_copy, enemy_asteroids_copy, own_bullets_copy, enemy_bullets_copy)
if hit:
left_found, left_steps = True, rotation_count
break
own_rocket_copy.rotate_left()
own_rocket_copy.move()
enemy_rocket_copy.move()
for neutral_asteroid in neutral_asteroids_copy:
neutral_asteroid.move()
for enemy_asteroid in enemy_asteroids_copy:
enemy_asteroid.move()
plan = []
if left_found:
if left_steps == 0:
return True, [[shoot_type]], 1
if left_steps < 15:
for i in range(left_steps):
plan.append([RocketBaseAction.ROTATE_LEFT])
plan.append([shoot_type])
return True, plan, left_steps + 1
else:
for i in range(30 - left_steps):
plan.append([RocketBaseAction.ROTATE_RIGHT])
plan.append([shoot_type])
return True, plan, 30 - left_steps + 1
else:
return False, [], NOT_FOUND_STEPS_COUNT
def try_shoot_some_asteroid_to_enemy_rocket(self, own_rocket, enemy_rocket, neutral_asteroids, enemy_asteroids, own_bullets, enemy_bullets):
# shot, created_asteroid, steps_count = self.shoot_will_hit_asteroid(own_rocket, neutral_asteroids, enemy_asteroids, own_bullets, enemy_bullets)
# if shot and created_asteroid.valid:
# hit, steps_count = self.asteroid_will_hit_rocket(enemy_rocket, created_asteroid)
# return hit
shot, bullet, impact_asteroid, steps_count = self.shoot_will_hit_asteroid(own_rocket, neutral_asteroids, enemy_asteroids, own_bullets, enemy_bullets)
if shot:
created_asteroid_single = Asteroid(None, None, impact_asteroid, own_rocket, bullet)
if created_asteroid_single.valid:
hit, steps_count = self.asteroid_will_hit_rocket(enemy_rocket, created_asteroid_single)
if hit:
return True, RocketBaseAction.SHOT
created_asteroid_split_one, created_asteroid_split_two = Asteroid.split_asteroid(own_rocket, impact_asteroid, bullet)
if created_asteroid_split_one is not None:
hit, steps_count = self.asteroid_will_hit_rocket(enemy_rocket, created_asteroid_split_one)
if hit:
return True, RocketBaseAction.SPLIT_SHOOT
if created_asteroid_split_two is not None:
hit, steps_count = self.asteroid_will_hit_rocket(enemy_rocket, created_asteroid_split_two)
if hit:
return True, RocketBaseAction.SPLIT_SHOOT
return False, RocketBaseAction.SHOT
def asteroid_will_hit_rocket(self, enemy_rocket, shot_asteroid):
steps_limit = 100
for step_count in range(steps_limit):
# if collides_numba(enemy_rocket.centerx, enemy_rocket.centery, shot_asteroid.centerx, shot_asteroid.centery,
# enemy_rocket.radius, shot_asteroid.radius):
if collides(enemy_rocket, shot_asteroid):
enemy_rocket.reverse_move(step_count)
shot_asteroid.reverse_move(step_count)
return (True, step_count)
enemy_rocket.move()
shot_asteroid.move()
enemy_rocket.reverse_move(steps_limit - 1)
shot_asteroid.reverse_move(steps_limit - 1)
return (False, steps_limit + 1)
def shoot_will_hit_explicit_asteroid(self, rocket, asteroid):
bullet = Bullet(rocket)
asteroid_copy = copy_object(asteroid)
for step_count in range(BULLET_LIFE_COUNT):
if collides(bullet, asteroid_copy):
return True
bullet.move()
asteroid_copy.move()
return False
def shoot_will_hit_asteroid(self, own_rocket, neutral_asteroids, enemy_asteroids, own_bullets, enemy_bullets, split = 0):
bullet = Bullet(own_rocket, split=split)
# neutral_asteroids_risk = [neutral_asteroid for neutral_asteroid in neutral_asteroids if self.risk_of_collision(neutral_asteroid, bullet)]
# enemy_asteroids_risk = [enemy_asteroid for enemy_asteroid in enemy_asteroids if self.risk_of_collision(enemy_asteroid, bullet)]
#
# for neutral_asteroid in neutral_asteroids_risk:
# pygame.draw.circle(self.screen, (255, 255, 255), (neutral_asteroid.centerx, neutral_asteroid.centery), 30, 3)
#
# for enemy_asteroid in enemy_asteroids_risk:
# pygame.draw.circle(self.screen, (255, 255, 255), (enemy_asteroid.centerx, enemy_asteroid.centery), 30,
# 3)
#
# pygame.draw.line(self.screen, (255,255,255), (bullet.centerx, bullet.centery), (bullet.centerx + 10*bullet.speedx, bullet.centery + 10* bullet.speedy),5)
#
# events = pygame.event.get(pygame.KEYDOWN)
# all_keys = pygame.key.get_pressed()
# if all_keys[pygame.K_d] and self.player_number == 1:
# pygame.display.update()
# time.sleep(0.5)
# own_rocket_copy = Space_object_DTO(own_rocket.radius, own_rocket.centerx, own_rocket.centery, own_rocket.speedx,
# own_rocket.speedy, own_rocket.angle, own_rocket.size_index, own_rocket.player)
own_rocket_copy = copy_object(own_rocket)
neutral_asteroids_copy = [copy_object(neutral_asteroid) for neutral_asteroid in neutral_asteroids]
enemy_asteroids_copy = [copy_object(enemy_asteroid) for enemy_asteroid in enemy_asteroids]
own_bullets_copy = [copy_object(own_bullet) for own_bullet in own_bullets]
enemy_bullets_copy = [copy_object(enemy_bullet) for enemy_bullet in enemy_bullets]
# neutral_asteroids_copy = [copy_object(neutral_asteroid) for neutral_asteroid in neutral_asteroids if self.risk_of_collision(neutral_asteroid, bullet)]
# enemy_asteroids_copy = [copy_object(enemy_asteroid) for enemy_asteroid in enemy_asteroids if self.risk_of_collision(enemy_asteroid, bullet)]
for step_count in range(BULLET_LIFE_COUNT):
for neutral_asteroid in neutral_asteroids_copy:
if collides(bullet, neutral_asteroid):
return (True, bullet, neutral_asteroid, step_count)
for own_bullet in own_bullets_copy:
if collides(own_bullet, neutral_asteroid):
own_bullets_copy.remove(own_bullet)
neutral_asteroids_copy.remove(neutral_asteroid)
break
for enemy_asteroid in enemy_asteroids_copy:
if collides(bullet, enemy_asteroid):
# return(True, Asteroid(self.screen, None, None, enemy_asteroid, own_rocket_copy, bullet), step_count)
return(True, bullet, enemy_asteroid, step_count)
for own_bullet in own_bullets_copy:
# if collides_numba(own_bullet.centerx, own_bullet.centery, enemy_asteroid.centerx, enemy_asteroid.centery,
# own_bullet.radius, enemy_asteroid.radius):
if collides(own_bullet, enemy_asteroid):
own_bullets_copy.remove(own_bullet)
enemy_asteroids_copy.remove(enemy_asteroid)
break
bullet.move()
own_rocket_copy.move()
for neutral_asteroid in neutral_asteroids_copy:
neutral_asteroid.move()
for enemy_asteroid in enemy_asteroids_copy:
enemy_asteroid.move()
for own_bullet in own_bullets_copy:
own_bullet.move()
for enemy_bullet in enemy_bullets_copy:
enemy_bullet.move()
return(False, None, None, BULLET_LIFE_COUNT + 1)
def first_impact_asteroid(self, own_rocket, neutral_asteroids, own_bullets, enemy_asteroids):
impact_neutral_asteroid, impact_neutral_asteroid_steps = self.first_impact_neutral_asteroid(own_rocket, neutral_asteroids, own_bullets)
impact_enemy_asteroid, impact_enemy_asteroid_steps = self.first_impact_enemy_asteroid(own_rocket,
enemy_asteroids,
own_bullets)
if impact_neutral_asteroid_steps < impact_enemy_asteroid_steps:
impact_asteroid = impact_neutral_asteroid
impact_steps = impact_neutral_asteroid_steps
elif impact_neutral_asteroid_steps > impact_enemy_asteroid_steps:
impact_asteroid = impact_enemy_asteroid
impact_steps = impact_enemy_asteroid_steps
elif impact_neutral_asteroid is None and impact_enemy_asteroid is None:
return False, None, IMPACT_RADIUS + 1
else:
impact_asteroid = impact_enemy_asteroid
impact_steps = impact_enemy_asteroid_steps
return True, impact_asteroid, impact_steps
def recalculate_target_position(self, rocket, asteroid):
a1 = [rocket.centerx, rocket.centery]
a2 = [rocket.centerx + rocket.speedx, rocket.centery + rocket.speedy]
b1 = [asteroid.centerx, asteroid.centery]
b2 = [asteroid.centerx + asteroid.speedx, asteroid.centery + asteroid.speedy]
if a1 == a2 or b1 == b2:
(target_x, target_y) = b1
else:
(intersection_x, intersection_y), found = self.get_intersect(a1, a2, b1, b2)
target_x = int(intersection_x * 0.15 + asteroid.centerx * 0.85)
target_y = int(intersection_y * 0.15 + asteroid.centery * 0.85)
temp_x, temp_y = target_x, target_y
# Try
distance = self.distance(temp_x, rocket.centerx, temp_y, rocket.centery)
# -x
temp_x = temp_x - SCREEN_WIDTH
temp_distance = self.distance(temp_x, rocket.centerx, temp_y, rocket.centery)
if temp_distance < distance:
target_x = temp_x
distance = temp_distance
temp_x = temp_x + SCREEN_WIDTH
# -y
temp_y = temp_y - SCREEN_HEIGHT
temp_distance = self.distance(temp_x, rocket.centerx, temp_y, rocket.centery)
if temp_distance < distance:
target_y = temp_y
distance = temp_distance
temp_y = temp_distance + SCREEN_HEIGHT
# -x -y
temp_x = temp_x - SCREEN_WIDTH
temp_y = temp_y - SCREEN_HEIGHT
temp_distance = self.distance(temp_x, rocket.centerx, temp_y, rocket.centery)
if temp_distance < distance:
target_y = temp_y
target_x = temp_x
asteroid.centerx, asteroid.centery = target_x, target_y
def distance(self,x1, x2, y1, y2):
return math.sqrt(math.pow(x1-x2, 2) + math.pow(y1 - y2, 2))
def risk_of_collision(self, objectA, objectB):
found, (pointx, pointy) = self.intersect_point(objectA, objectB)
if found:
if objectA.speedx == 0:
steps_A = 1000
else:
steps_A = (pointx - objectA.centerx) / objectA.speedx
if objectB.speedx == 0:
steps_B = - 1000
else:
steps_B = - (pointx - objectB.centerx) / objectB.speedx
if math.fabs(steps_A - steps_B) < 60:
return True
return False
return True
def intersect_point(self,objectA, objectB):
c1 = objectA.speedy * objectA.centerx - objectA.speedx * objectA.centery
a1 = -objectA.speedy
b1 = objectA.speedx
c2 = objectB.speedy * objectB.centerx - objectB.speedx * objectB.centery
a2 = -objectB.speedy
b2 = objectB.speedx
if a1 == 0:
if (a1*b2 - a2*b1 != 0):
x = objectB.centerx
y = (-a1*c2 + a2*c1)/(a1*b2 - a2*b1)
return True, (int(x),int(y))
return False, (0,0)
if (a1*b2 - a2*b1 == 0):
return False, (0,0)
x = (-c1 - b1*((-a1*c2 + a2*c1)/(a1*b2 - a2*b1))) / a1
y = (-a1*c2 + a2*c1)/(a1*b2 - a2*b1)
return True, (int(x), int(y))
def get_intersect(self, a1, a2, b1, b2):
"""
Returns the point of intersection of the lines passing through a2,a1 and b2,b1.
a1: [x, y] a point on the first line
a2: [x, y] another point on the first line
b1: [x, y] a point on the second line
b2: [x, y] another point on the second line
"""
s = np.vstack([a1, a2, b1, b2]) # s for stacked
h = np.hstack((s, np.ones((4, 1)))) # h for homogeneous
l1 = np.cross(h[0], h[1]) # get first line
l2 = np.cross(h[2], h[3]) # get second line
x, y, z = np.cross(l1, l2) # point of intersection
if z == 0: # lines are parallel
return (float('inf'), float('inf')), False
return (x / z, y / z), True
def defense_shoot_asteroid_actions(self, rocket, asteroid):
if self.shoot_will_hit_explicit_asteroid(rocket, asteroid):
return [[RocketBaseAction.SHOT]], 1
else:
return self.face_asteroid(rocket, asteroid)
def face_asteroid(self, rocket, asteroid):
asteroid_angle = asteroid.angle
target_angle = int(math.atan2(-(asteroid.centery - rocket.centery), (asteroid.centerx - rocket.centerx)) * 180 / math.pi - 90) % 360
# Difference in angles is small enough to shoot
# Rotation would only increase the difference
difference = (rocket.angle + 360 - target_angle) % 360
if difference > 7:
difference = difference - 360
if math.fabs(difference) < 7:
return [], 0
temp_rocket_angle = rocket.angle
number_of_rotation = 0
actions = []
# Decide rotation direction
if ((rocket.angle + 360 - target_angle) % 360) < 180:
while (rocket.angle + 360 - target_angle) % 360 > 11:
rocket.rotate_right()
number_of_rotation = number_of_rotation + 1
for i in range(number_of_rotation):
actions.append([RocketBaseAction.ROTATE_RIGHT])
actions.append([RocketBaseAction.SHOT])
rocket.angle = temp_rocket_angle
return actions, number_of_rotation + 1
else:
while (rocket.angle + 360 - target_angle) % 360 > 11:
rocket.rotate_left()
number_of_rotation = number_of_rotation + 1
for i in range(number_of_rotation):
actions.append([RocketBaseAction.ROTATE_LEFT])
actions.append([RocketBaseAction.SHOT])
rocket.angle = temp_rocket_angle
return actions, number_of_rotation + 1
def simple_shot(self):
return [RocketBaseAction.SHOT]
def can_shoot(self):
return self.shoot_reload_ticks >= 5
def convert_actions(self, actions):
self.shoot_reload_ticks = self.shoot_reload_ticks + 1
# Automatic agents cannot shoot all the time
if(RocketBaseAction.SHOT in actions):
if self.shoot_reload_ticks < 5:
actions.remove(RocketBaseAction.SHOT)
else:
self.shoot_reload_ticks = 0
if (RocketBaseAction.SPLIT_SHOOT in actions):
if self.shoot_reload_ticks < 5:
actions.remove(RocketBaseAction.SPLIT_SHOOT)
else:
self.shoot_reload_ticks = 0
return actions
def get_state_info(self, state):
# Return action_plan_lengths (attack, deffense, evasion, stop), and their corresponding action_plans
own_rocket, enemy_rocket, neutral_asteroids, own_asteroids, enemy_asteroids, own_bullets, enemy_bullets = self.assign_objects_to_agent(state)
impact, impact_asteroid, impact_steps_count = self.first_impact_asteroid(own_rocket, neutral_asteroids,
own_bullets, enemy_asteroids)
number_of_close_asteroids = self.number_of_asteroids_in_range(own_rocket, neutral_asteroids, enemy_asteroids)
total_number_of_dangerous_asteroids = len(neutral_asteroids) + len(enemy_asteroids)
attack_actions = []
attack_steps_count = NOT_FOUND_STEPS_COUNT
evade_actions = []
evade_steps_count = NOT_FOUND_STEPS_COUNT
defense_shoot_actions = []
defense_steps_count = NOT_FOUND_STEPS_COUNT
stop_actions = []
stop_steps_count = NOT_FOUND_STEPS_COUNT
_, stop_actions, stop_steps_count = self.stop_moving(own_rocket)
if impact:
evade_actions, evade_steps_count = self.evade_asteroid(own_rocket, impact_asteroid)
defense_shoot_actions, defense_steps_count = self.defense_shoot_asteroid_actions(own_rocket,
impact_asteroid)
hit, attack_actions, attack_steps_count = self.shoot_in_all_directions_to_hit_enemy(own_rocket,
enemy_rocket,
state.neutral_asteroids,
enemy_asteroids,
own_bullets,
enemy_bullets)
return (attack_steps_count,
defense_steps_count,
evade_steps_count,
stop_steps_count,
impact_steps_count,
number_of_close_asteroids,
total_number_of_dangerous_asteroids,
own_rocket.health,
enemy_rocket.health),\
(attack_actions, defense_shoot_actions, evade_actions, stop_actions)
class Attacking_agent(Agent):
def __init__(self, player_number):
super().__init__(player_number)
# self.screen = screen
self.shoot_reload_ticks = 0
self.active_steps = 0
self.inactive_steps = 0
self.inactiv_ticks = 0
self.plan = []
self.finished_plan = True
def choose_actions(self, state, opposite_agent_actions):
own_rocket, enemy_rocket, neutral_asteroids, own_asteroids, enemy_asteroids, own_bullets, enemy_bullets = super().assign_objects_to_agent(state)
if self.reevaluate_plan():
self.active_steps = self.active_steps + 1
hit, actions, count = super().shoot_in_all_directions_to_hit_enemy(own_rocket, enemy_rocket,
state.neutral_asteroids, enemy_asteroids,
own_bullets, enemy_bullets)
if hit:
super().store_plan(actions)
else:
self.inactive_steps = self.inactive_steps + 1
actions = super().choose_action_from_plan()
return super().convert_actions(actions)
def reevaluate_plan(self):
if self.inactiv_ticks > 0:
self.inactiv_ticks = 0
return True
if not self.finished_plan_attack:
return False
self.inactiv_ticks = self.inactiv_ticks + 1
return False
class Random_agent(Agent):
def __init__(self, player_number):
super().__init__(player_number)
self.steps = 0
def choose_actions(self):
self.steps = self.steps + 1
actions_numbers = []
number_of_actions = random.randint(0,3)
for i in range(number_of_actions):
action_number = random.randint(1,5)
while action_number in actions_numbers:
action_number = random.randint(1, 5)
actions_numbers.append(action_number)
if 4 in actions_numbers:
if self.steps % 4 != 0:
actions_numbers.remove(4)
if 5 in actions_numbers:
if self.steps % 4 != 0:
actions_numbers.remove(5)
if self.player_number == 2:
for i in range(len(actions_numbers)):
actions_numbers[i] = actions_numbers[i] + 5
actions = []
for action_number in actions_numbers:
actions.append(RocketBaseAction(int(action_number)))
return actions
class Evasion_agent(Agent):
def __init__(self, player_number, draw_modul = None):
super().__init__(player_number)
self.shoot_reload_ticks = 0
self.inactive_steps = 0
self.finished_plan_evasion = True
self.draw_modul = draw_modul
def choose_actions(self, state):
own_rocket, enemy_rocket, neutral_asteroids, own_asteroids, enemy_asteroids, own_bullets, enemy_bullets = super().assign_objects_to_agent(state)
#COOL
#closest_asteroids = super().find_N_closest_asteroids(own_rocket, neutral_asteroids, enemy_asteroids, 3)
#for close_ast in closest_asteroids:
# self.draw_modul.draw_line((own_rocket.centerx, own_rocket.centery),
# (own_rocket.centerx + close_ast[0][0], own_rocket.centery + close_ast[0][1]))
#enemy_vector = super().object_object_vector(enemy_rocket, own_rocket)
#self.draw_modul.draw_line((own_rocket.centerx, own_rocket.centery),
# (own_rocket.centerx + enemy_vector[0], own_rocket.centery + enemy_vector[1]))
#self.draw_modul.save_image()
#self.draw_modul.render()
if self.reevaluate_plan():
impact, impact_asteroid, impact_steps = super().first_impact_asteroid(own_rocket, state.neutral_asteroids, own_bullets, enemy_asteroids)
#with stopping agent it looks less chaotic, but shows similar results
stop_found, stop_actions, stop_actions_count = super().stop_moving(own_rocket)
if impact_asteroid is None:
if stop_found:
super().store_plan(stop_actions)
else:
super().finish_plan()
return super().convert_actions([])
if impact_asteroid is not None and impact_steps < 25:
actions, steps_count = super().evade_asteroid(own_rocket, impact_asteroid)
super().store_plan(actions)
else:
self.inactive_steps = self.inactive_steps + 1
actions = super().choose_action_from_plan()
return super().convert_actions(actions)
def reevaluate_plan(self):
if self.inactiv_ticks > INACTIV_STEPS_LIMIT:
self.inactiv_ticks = 0
return True
if not self.finished_plan_evasion:
self.inactiv_ticks = self.inactiv_ticks + 1
return False
self.inactiv_ticks = self.inactiv_ticks + 1
return False
class Stable_defensive_agent(Agent):
def __init__(self, player_number):
super().__init__(player_number)
# self.screen = screen
self.shoot_reload_ticks = 0
self.python_time = 0
self.numpy_time = 0
self.asteroids_arr = []
self.bullets_arr = []
self.target_asteroid = None
self.inactive_steps = 0
self.active_steps = 0
def choose_actions(self, state):
own_rocket, enemy_rocket, neutral_asteroids, own_asteroids, enemy_asteroids, own_bullets, enemy_bullets = super().assign_objects_to_agent(state)
if super().reevaluate_plan():
self.active_steps = self.active_steps + 1
self.active_ticks = 1
impact_neutral_asteroid, impact_neutral_asteroid_steps = super().first_impact_neutral_asteroid(own_rocket, state.neutral_asteroids, own_bullets)
self.asteroids_arr.append(len(state.neutral_asteroids))
self.bullets_arr.append(len(own_bullets))
impact_enemy_asteroid, impact_enemy_asteroid_steps = super().first_impact_enemy_asteroid(own_rocket, enemy_asteroids, own_bullets)
if impact_neutral_asteroid_steps < impact_enemy_asteroid_steps:
impact_asteroid = impact_neutral_asteroid
elif impact_neutral_asteroid_steps > impact_enemy_asteroid_steps:
impact_asteroid = impact_enemy_asteroid
elif impact_neutral_asteroid is None and impact_enemy_asteroid is None:
self.finish_plan()
return super().convert_actions([])
else:
impact_asteroid = impact_enemy_asteroid
if super().shoot_will_hit_explicit_asteroid(own_rocket, impact_asteroid):
actions = super().simple_shot()
super().finish_plan()
return super().convert_actions(actions)
self.target_asteroid = impact_asteroid
super().recalculate_target_position(own_rocket, impact_asteroid)
actions, actions_steps = super().face_asteroid(own_rocket, impact_asteroid)
if not actions:
actions = [super().simple_shot()]
super().store_plan(actions)
else:
self.inactive_steps = self.inactive_steps + 1
if self.target_asteroid is not None:
self.target_asteroid.move()
if super().shoot_will_hit_explicit_asteroid(own_rocket, self.target_asteroid):
actions = super().simple_shot()
super().finish_plan()
return super().convert_actions(actions)
actions = super().choose_action_from_plan()
return super().convert_actions(actions)
class Genetic_agent(Agent):
def __init__(self, player_number, decision_function):
super().__init__(player_number)
# self.screen = screen
self.inactiv_ticks = 0
self.attack_count = 0
self.defense_count = 0
self.evasion_count = 0
self.active_choose_steps = 0
self.inactive_choose_steps = 0
self.stop_count = 0
self.odd = 0
self.decision_function = decision_function
self.penalty = 0
self.finished_plan_gp = False
self.history=[0,0,0,0]
def choose_actions(self, state):
actions = []
#if self.reevaluate_plan():
if super().reevaluate_plan():
self.active_choose_steps += 1
(attack_actions, attack_steps_count), (defense_shoot_actions, defense_steps_count), (evade_actions, evade_steps_count), (stop_actions, stop_steps_count), impact_steps_count = self.get_state_stats(state)
###
action_plans = (attack_actions, defense_shoot_actions, evade_actions, stop_actions)
if action_plans != ([],[],[],[]):
actions_index = self.decision_function(attack_steps_count, defense_steps_count, evade_steps_count,
stop_steps_count, impact_steps_count)
if actions_index() == ActionPlanEnum.ATTACK:
actions = attack_actions
self.history[int(ActionPlanEnum.ATTACK.value)] += 1
self.attack_count += 1
elif actions_index() == ActionPlanEnum.DEFFENSE:
actions = defense_shoot_actions
self.history[int(ActionPlanEnum.DEFFENSE.value)] += 1
self.defense_count += 1
elif actions_index() == ActionPlanEnum.EVASION:
actions = evade_actions
self.history[int(ActionPlanEnum.EVASION.value)] += 1
self.evasion_count += 1
elif actions_index() == ActionPlanEnum.STOP:
actions = stop_actions
self.history[int(ActionPlanEnum.STOP.value)] += 1
self.stop_count += 1
###
super().store_plan(actions)
else:
self.inactive_choose_steps += 1
return super().convert_actions(super().choose_action_from_plan())
def get_state_stats(self, state):
own_rocket, enemy_rocket, neutral_asteroids, own_asteroids, enemy_asteroids, own_bullets, enemy_bullets = super().assign_objects_to_agent(state)
impact, impact_asteroid, impact_steps_count = super().first_impact_asteroid(own_rocket, neutral_asteroids,
own_bullets, enemy_asteroids)
attack_actions = []
attack_steps_count = NOT_FOUND_STEPS_COUNT
evade_actions = []
evade_steps_count = NOT_FOUND_STEPS_COUNT
defense_shoot_actions = []
defense_steps_count = NOT_FOUND_STEPS_COUNT
stop_actions = []
stop_steps_count = NOT_FOUND_STEPS_COUNT
_, stop_actions, stop_steps_count = super().stop_moving(own_rocket)
if impact:
evade_actions, evade_steps_count = super().evade_asteroid(own_rocket, impact_asteroid)
defense_shoot_actions, defense_steps_count = super().defense_shoot_asteroid_actions(own_rocket,
impact_asteroid)
#if self.odd < 1:
# self.odd = self.odd + 1
#else:
# self.odd = 0
hit, attack_actions, attack_steps_count = super().shoot_in_all_directions_to_hit_enemy(own_rocket,
enemy_rocket,
state.neutral_asteroids,
enemy_asteroids,
own_bullets,
enemy_bullets)
return (attack_actions, attack_steps_count), (defense_shoot_actions, defense_steps_count), (evade_actions, evade_steps_count), (stop_actions, stop_steps_count), impact_steps_count
class DQAgent(Agent):
def __init__(self, player_number, num_inputs, num_outputs, batch_size = 32, num_batches = 64, model = None, extended = False):
super().__init__(player_number)
self.num_inputs = num_inputs
self.num_outputs = num_outputs
self.batch_size = batch_size
self.num_batches = num_batches
self.eps = 1.0
self.eps_decay = 0.9989
self.gamma = 0.95
self.exp_buffer = []
self.active_choose_steps = 0
self.inactive_choose_steps = 0
self.inactiv_ticks = 0
self.attack_count = 0
self.defense_count = 0
self.evasion_count = 0
self.stop_count = 0
self.penalty = 0
self.odd = 0
self.history=[0,0,0,0]
self.extended = extended
if model is None:
self.build_model()
else:
self.model = model
# vytvari model Q-site
def build_model(self):
self.model = tf.keras.models.Sequential([tf.keras.layers.Dense(24, activation=tf.nn.relu, input_dim=self.num_inputs, name='dense_1'),
tf.keras.layers.Dense(24, activation=tf.nn.relu, name = 'dense_02'),
tf.keras.layers.Dense(self.num_outputs, activation='linear', name='dense_03')])
opt = tf.keras.optimizers.Adam(lr=0.001)
self.model.compile(optimizer=opt, loss='mse')
def reevaluate_plan(self, train):
if train:
return True
return super().reevaluate_plan()
# copied from GP and to ancestor
def get_state_stats(self, state):
own_rocket, enemy_rocket, neutral_asteroids, own_asteroids, enemy_asteroids, own_bullets, enemy_bullets = super().assign_objects_to_agent(state)
impact, impact_asteroid, impact_steps_count = super().first_impact_asteroid(own_rocket, neutral_asteroids,
own_bullets, enemy_asteroids)
number_of_close_asteroids = self.number_of_asteroids_in_range(own_rocket, neutral_asteroids, enemy_asteroids)
total_number_of_dangerous_asteroids = len(neutral_asteroids) + len(enemy_asteroids)
attack_actions = []
attack_steps_count = NOT_FOUND_STEPS_COUNT
evade_actions = []
evade_steps_count = NOT_FOUND_STEPS_COUNT
defense_shoot_actions = []
defense_steps_count = NOT_FOUND_STEPS_COUNT
stop_actions = []
stop_steps_count = NOT_FOUND_STEPS_COUNT
_, stop_actions, stop_steps_count = super().stop_moving(own_rocket)
if impact:
evade_actions, evade_steps_count = super().evade_asteroid(own_rocket, impact_asteroid)
defense_shoot_actions, defense_steps_count = super().defense_shoot_asteroid_actions(own_rocket,
impact_asteroid)
if self.odd < 1 and not self.extended:
self.odd = self.odd + 1
else:
self.odd = 0
hit, attack_actions, attack_steps_count = super().shoot_in_all_directions_to_hit_enemy(own_rocket,
enemy_rocket,
state.neutral_asteroids,
enemy_asteroids,
own_bullets,
enemy_bullets)
return (attack_actions, attack_steps_count), \
(defense_shoot_actions, defense_steps_count), \
(evade_actions, evade_steps_count), \
(stop_actions, stop_steps_count), \
impact_steps_count, \
number_of_close_asteroids, \
total_number_of_dangerous_asteroids, \
own_rocket.health, \
enemy_rocket.health
def choose_random_action_plan(self):
val = np.random.randint(self.num_outputs)
self.history[val] += 1
return val
def choose_action_plan_index(self, state):
if np.random.uniform() < self.eps:
return self.choose_random_action_plan()
else:
val = np.argmax(self.model.predict(state)[0])
self.history[val] += 1
return val
def get_action_from_action_plan(self, plan_index, action_plans):
action_plan = action_plans[plan_index]
super().store_plan(action_plan)
return super().convert_actions(super().choose_action_from_plan())
def choose_actions(self, state, train=False):
if train:
(attack_actions, attack_steps_count), (defense_shoot_actions, defense_steps_count), (
evade_actions, evade_steps_count), (stop_actions, stop_steps_count), impact_steps_count = self.get_state_stats(state)
transformed_state = (attack_steps_count, defense_steps_count, evade_steps_count, stop_steps_count, impact_steps_count)
if np.random.uniform() < self.eps:
actions_index = np.random.randint(self.num_outputs)
else:
actions_index = np.argmax(self.model.predict(transformed_state)[0])
else:
if self.reevaluate_plan(train=False):
self.active_choose_steps += 1
(attack_actions, attack_steps_count), \
(defense_shoot_actions, defense_steps_count), \
(evade_actions, evade_steps_count), \
(stop_actions, stop_steps_count), \
impact_steps_count, \
number_of_close_asteroids, \
total_number_of_dangerous_asteroids, \
own_rocket_health, \
enemy_rocket_health = self.get_state_stats(state)
action_plans = [attack_actions, defense_shoot_actions, evade_actions, stop_actions]
if self.extended:
transformed_state = (attack_steps_count, defense_steps_count, evade_steps_count, stop_steps_count, impact_steps_count, number_of_close_asteroids, total_number_of_dangerous_asteroids, own_rocket_health, enemy_rocket_health)
else:
transformed_state = (attack_steps_count, defense_steps_count, evade_steps_count, stop_steps_count, impact_steps_count)
transformed_state = np.array([transformed_state])
if action_plans != [[],[],[],[]]:
not_empty = 0
valid_index = 0
for index in range(4):
if action_plans[index] != []:
not_empty += 1
valid_index = index
if not_empty == 1:
actions = action_plans[valid_index]
self.history[valid_index] +=1
else:
actions_index = np.argmax(self.model.predict(transformed_state)[0])
actions = action_plans[actions_index]
self.history[actions_index] += 1
super().store_plan(actions)
else:
self.inactive_choose_steps += 1
return super().convert_actions(super().choose_action_from_plan())
# vraci akci agenta - pokud trenujeme tak epsilon-greedy, jinak nejlepsi podle site
def action(self, state, train=False):
if train and np.random.uniform() < self.eps:
return np.random.randint(self.num_outputs)
else:
return np.argmax(self.model.predict(state)[0])
# ulozeni informaci do experience bufferus
def record_experience(self, exp):
self.exp_buffer.append(exp)
if len(self.exp_buffer) > 10000:
self.exp_buffer = self.exp_buffer[-10000:]
# trenovani z bufferu
def train(self, input_buffer = None):
if input_buffer is not None:
self.exp_buffer = input_buffer
if (len(self.exp_buffer) <= self.batch_size):
return
for _ in range(self.num_batches):
batch = random.sample(self.exp_buffer, self.batch_size)
states = np.array([s for (s, _, _, _, _) in batch])
next_states = np.array([ns for (_, _, _, ns, _) in batch])
states = states.reshape((-1, self.num_inputs))
next_states = next_states.reshape((-1, self.num_inputs))
pred = self.model.predict(states)
next_pred = self.model.predict(next_states)
# spocitame cilove hodnoty
for i, (s, a, r, ns, go) in enumerate(batch):
pred[i][a] = r
if not go:
pred[i][a] = r + self.gamma*np.amax(next_pred[i])
self.model.fit(states, pred, epochs=1, verbose=0)
# snizime epsilon pro epsilon-greedy strategii
if self.eps > 0.01:
self.eps = self.eps*self.eps_decay
class Low_level_sensor_DQAgent(Agent):
def __init__(self, player_number, num_inputs, num_outputs, batch_size = 32, num_batches = 64, model = None, draw_module = None):
super().__init__(player_number)
self.num_inputs = num_inputs
self.num_outputs = num_outputs
self.batch_size = batch_size
self.num_batches = num_batches
self.buffer_size = 3000
self.eps = 1.0
self.eps_decay = 0.9998
self.gamma = 0.95
self.exp_buffer = []
self.inactiv_ticks = 0
self.attack_count = 0
self.defense_count = 0
self.evasion_count = 0
self.stop_count = 0
self.penalty = 0
self.odd = 0
self.history = [0, 0, 0, 0, 0, 0]
self.draw_module = draw_module
if model is None:
self.build_model()
else:
self.model = model
# vytvari model Q-site
def build_model(self):
self.model = tf.keras.models.Sequential([tf.keras.layers.Dense(24, activation=tf.nn.relu, input_dim=self.num_inputs
#, name='dense_1'
),
tf.keras.layers.Dense(24, activation=tf.nn.relu
#, name = 'dense_02'
),
tf.keras.layers.Dense(24, activation=tf.nn.relu),
tf.keras.layers.Dense(self.num_outputs, activation='linear')])
opt = tf.keras.optimizers.Adam(lr=0.001)
self.model.compile(optimizer=opt, loss='mse')
def train(self):
if (len(self.exp_buffer) <= self.batch_size):
return
for _ in range(self.num_batches):
batch = random.sample(self.exp_buffer, self.batch_size)
states = np.array([s for (s, _, _, _, _) in batch])
next_states = np.array([ns for (_, _, _, ns, _) in batch])
states = states.reshape((-1, self.num_inputs))
next_states = next_states.reshape((-1, self.num_inputs))
pred = self.model.predict(states)
next_pred = self.model.predict(next_states)
# spocitame cilove hodnoty
for i, (s, a, r, ns, go) in enumerate(batch):
pred[i][a] = r
if not go:
pred[i][a] = r + self.gamma*np.amax(next_pred[i])
self.model.fit(states, pred, epochs=1, verbose=0)
#gc.collect()
# snizime epsilon pro epsilon-greedy strategii
if self.eps > 0.01:
self.eps = self.eps*self.eps_decay
def record_experience(self, exp):
self.exp_buffer.append(exp)
if len(self.exp_buffer) > self.buffer_size:
self.exp_buffer = self.exp_buffer[-self.buffer_size:]
def get_simple_actions_from_action_value(self, value):
if value == 0:
actions = [RocketBaseAction.ROTATE_LEFT]
if value == 1:
actions = [RocketBaseAction.ROTATE_RIGHT]
if value == 2:
actions = [RocketBaseAction.ACCELERATE]
if value == 3:
actions = [RocketBaseAction.SHOT]
if value == 4:
actions = [RocketBaseAction.SPLIT_SHOOT]
if value == 5:
actions = []
return actions
def choose_action_index(self, state, train=False):
if train and np.random.uniform() < self.eps:
val = np.random.randint(self.num_outputs)
actions = self.get_simple_actions_from_action_value(val)
if not self.can_shoot():
while actions == [RocketBaseAction.SHOT] or actions == [RocketBaseAction.SPLIT_SHOOT]:
val = np.random.randint(self.num_outputs)
actions = self.get_simple_actions_from_action_value(val)
self.history[val] += 1
else:
predictions = self.model.predict(state)[0]
best_args = predictions.argsort()[-3:][::-1]
val = best_args[0]
ticks = self.shoot_reload_ticks
if not self.can_shoot():
for i in range(3):
val = best_args[i]
actions = self.get_simple_actions_from_action_value(val)
if actions != [RocketBaseAction.SHOT] and actions != [RocketBaseAction.SPLIT_SHOOT]:
break
#val = np.argmax(self.model.predict(state)[0])
self.history[val] +=1
return val
def choose_actions(self, state):
state = self.low_level_state_info(state)
action_index = self.choose_action_index(state, train=False)
actions = self.get_simple_actions_from_action_value(action_index)
actions = super().convert_actions(actions)
return actions
# vytvorime agenta (4 vstupy, 2 akce)
class Input_agent(Agent):
def __init__(self, screen, player_number):
super().__init__(player_number)
self.input=True
self.screen = screen
def choose_actions(self, state):
actions_one = []
actions_two = []
actions = []
events = pygame.event.get(pygame.KEYDOWN)
for event in events:
if(event.key == pygame.K_f):
#actions.append(Rocket_action.ROCKET_ONE_SHOOT)
# actions_one.append(Rocket_action.ROCKET_ONE_SHOOT)
actions_two.append(RocketBaseAction.SHOT)
if(event.key == pygame.K_g):
#actions.append(Rocket_action.ROCKET_ONE_SPLIT_SHOOT)
# actions_one.append(Rocket_action.ROCKET_ONE_SPLIT_SHOOT)
actions_two.append(RocketBaseAction.SPLIT_SHOOT)
if(event.key == pygame.K_o):
#for second player switch back to action_two
actions_one.append(RocketBaseAction.SHOT)
if(event.key == pygame.K_p):
# for second player switch back to action_two
actions_one.append(RocketBaseAction.SPLIT_SHOOT)
all_keys = pygame.key.get_pressed()
if all_keys[pygame.K_UP]:
#actions.append(Rocket_action.ROCKET_ONE_ACCELERATE)
# actions_one.append(Rocket_action.ROCKET_ONE_ACCELERATE)
actions_one.append(RocketBaseAction.ACCELERATE)
if all_keys[pygame.K_LEFT]:
#actions.append(Rocket_action.ROCKET_ONE_ROTATE_LEFT)
# actions_one.append(Rocket_action.ROCKET_ONE_ROTATE_LEFT)
actions_one.append(RocketBaseAction.ROTATE_LEFT)
if all_keys[pygame.K_RIGHT]:
#actions.append(Rocket_action.ROCKET_ONE_ROTATE_RIGHT)
# actions_one.append(Rocket_action.ROCKET_ONE_ROTATE_RIGHT)
actions_one.append(RocketBaseAction.ROTATE_RIGHT)
if all_keys[pygame.K_a]:
#actions.append(Rocket_action.ROCKET_TWO_ROTATE_LEFT)
# actions_two.append(Rocket_action.ROCKET_TWO_ROTATE_LEFT)
actions_two.append(RocketBaseAction.ROTATE_LEFT)
if all_keys[pygame.K_d]:
#actions.append(Rocket_action.ROCKET_TWO_ROTATE_RIGHT)
# actions_two.append(Rocket_action.ROCKET_TWO_ROTATE_RIGHT)
actions_two.append(RocketBaseAction.ROTATE_RIGHT)
if all_keys[pygame.K_w]:
#actions.append(Rocket_action.ROCKET_TWO_ACCELERATE)
# actions_two.append(Rocket_action.ROCKET_TWO_ACCELERATE)
actions_two.append(RocketBaseAction.ACCELERATE)
# clearing it apparently prevents from stucking
pygame.event.clear()
return actions_one\
, actions_two
class ActionPlanEnum(Enum):
ATTACK = 0
DEFFENSE = 1
EVASION = 2
STOP = 3
| PremekBasta/Asteroids | agents.py | agents.py | py | 72,666 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "math.pow",
"line_number": 106,
"usage_type": "call"
},
{
"api_name": "numpy.array",
"line_number": 190,
"usage_type": "call"
},
{
"api_name": "numpy.reshape",
"line_number": 197,
"usage_type": "call"
},
{
"api_name": "dto.copy_object",
"line_num... |
19719510621 | #!/usr/bin/env python3
import sys
from functools import partial
from simplifier import setUp
from common import adbSetValue, adbGetValue, alternator
"""
adb -s __DEVICE__ shell settings put system accelerometer_rotation 0
adb -s __DEVICE__ shell settings get system user_rotation
adb -s __DEVICE__ shell settings put system user_rotation $VALUE
"""
flip_usage="""
flip [-s DEVICE] [-t (default) | --toggle | -p | --portrait | -l | --landscape]
"""
def validateArgs(arguments=None):
if arguments == None:
return None
if len(arguments) > 0:
if "-s" in arguments:
pos = arguments.index("-s")
del arguments[pos + 1]
arguments.remove("-s")
if len(arguments) > 1:
raise ValueError("Illegal combination of arguments. Usage: " + flip_usage)
if len(arguments) == 0 or "-t" in arguments or "--toggle" in arguments:
return None
if "-l" in arguments or "--landscape" in arguments:
return 1
if "-p" in arguments or "--portrait" in arguments:
return 0
raise ValueError("Illegal argument: " + arguments[0] + ". Usage: " + flip_usage)
return None
def modifier(new_value):
adbSetValue("system", "user_rotation", new_value, device)
def get_orientation(device):
return int(adbGetValue("system", "user_rotation", device))
def flip_dictionary(device):
return {
0: lambda: modifier("0"), #change from LANDSCAPE to PORTRAIT
1: lambda: modifier("1") #change from PORTRAIT to LANDSCAPE
}
if __name__ == "__main__":
options = setUp(ui_required = False)
device = options.get("device")
args = sys.argv
del args[0]
direction = validateArgs(args)
#always required
adbSetValue("system", "accelerometer_rotation", "0", device)
alternator(lambda: get_orientation(device), flip_dictionary(device), direction)
| qbalsdon/talos | python/flip.py | flip.py | py | 1,904 | python | en | code | 4 | github-code | 1 | [
{
"api_name": "common.adbSetValue",
"line_number": 37,
"usage_type": "call"
},
{
"api_name": "common.adbGetValue",
"line_number": 40,
"usage_type": "call"
},
{
"api_name": "simplifier.setUp",
"line_number": 49,
"usage_type": "call"
},
{
"api_name": "sys.argv",
... |
16803284319 | #!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
def f(y, t, params):
P, lamb = y # unpack current values of y
r, M, alpha, z0, z1 = params # unpack parameters
derivs = [P, -r*lamb] # list of dy/dt=f functions
return derivs
# Parameters
r = 0.8 # quality factor (inverse damping)
M = 780500.0 # forcing amplitude
alpha = 0.5 # drive frequency
# Initial values
P0 = 389482.0 # initial Popultation
lamb0 = r*M/4 # initial angular velocity
# Bundle parameters for ODE solver
params = [r, M, alpha, np.sin, np.cos]
# Bundle initial conditions for ODE solver
y0 = [P0, lamb0]
# Make time array for solution
tStop = 200.
tInc = 0.05
t = np.arange(0., tStop, tInc)
# Call the ODE solver
psoln = odeint(f, y0, t, args=(params,))
# Plot results
fig = plt.figure(1, figsize=(8,8))
# Plot theta as a function of time
ax1 = fig.add_subplot(311)
ax1.plot(t, psoln[:,0])
ax1.set_xlabel('time')
ax1.set_ylabel('theta')
# Plot omega as a function of time
ax2 = fig.add_subplot(312)
ax2.plot(t, psoln[:,1])
ax2.set_xlabel('time')
ax2.set_ylabel('omega')
# Plot omega vs theta
ax3 = fig.add_subplot(313)
twopi = 2.0*np.pi
ax3.plot(psoln[:,0]%twopi, psoln[:,1], '.', ms=1)
ax3.set_xlabel('theta')
ax3.set_ylabel('omega')
ax3.set_xlim(0., twopi)
plt.tight_layout()
plt.show()
| oscarram/Optimal-Harvesting | Numerical_Solutions/InitialPythonSimulations/NumericalODE.py | NumericalODE.py | py | 1,381 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "numpy.sin",
"line_number": 24,
"usage_type": "attribute"
},
{
"api_name": "numpy.cos",
"line_number": 24,
"usage_type": "attribute"
},
{
"api_name": "numpy.arange",
"line_number": 32,
"usage_type": "call"
},
{
"api_name": "scipy.integrate.odeint",
... |
1905685024 | import sys
from pymongo import MongoClient
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import psycopg2 as pg2
from psycopg2.errors import UniqueViolation
def run_pipe(print_count=1000):
"""
Converts a mongoDB open on localhost:27017 to a postgreSQL
DB open on localhost:5432.
Args:
print_count: prints progress after every number of this inserts
Raises:
any exception during insertion with extra information to identify the troublesome record
"""
#initialize mongo connection
client = MongoClient('localhost', 27017)
inmates = client.tdcj.inmates
unassigned = client.tdcj.unassigned
#query mongo
results = inmates.find({'_id': {'$exists':'true'}})
#initalize postgres connection
conn = pg2.connect(dbname='tdcj', host='localhost', port=5432, user='postgres')
cur = conn.cursor()
#insert every inmate into the postgres DB
try:
count = 0
for inmate in results:
insert_offender(conn, cur, inmate)
count += 1
if count % print_count == 0:
print(f'{count} documents cleared pipe')
except Exception as e:
raise type(e)(f'{str(e)} problematic entry: {inmate}')\
.with_traceback(sys.exc_info()[2])
cur.close()
conn.close()
def _reset_tdcj_pgdb():
"""
Deletes and recreates the tdcj SQL database.
"""
conn = pg2.connect(host='localhost', port=5432, user='postgres')
conn.set_session(autocommit=True)
cur = conn.cursor()
cur.execute('DROP DATABASE IF EXISTS tdcj')
cur.execute('CREATE DATABASE tdcj')
cur.close()
conn.close()
def _create_tables():
"""
Creates the 3 tables for the postgres DB.
"""
conn = pg2.connect(dbname='tdcj', host='localhost', port=5432, user='postgres')
cur = conn.cursor()
commands = (
'''
CREATE TABLE offenders (
sid_number INTEGER UNIQUE,
tdcj_number INTEGER PRIMARY KEY,
name VARCHAR(30) NOT NULL,
race CHAR(1) NOT NULL,
gender BOOLEAN NOT NULL,
date_of_birth DATE NOT NULL,
max_sentence_date DATE,
msd_category SMALLINT,
current_facility VARCHAR(30) NOT NULL,
projected_release_date DATE,
parole_eligibility_date DATE,
visitation_eligible VARCHAR(4),
last_accessed TIMESTAMP NOT NULL
)
''',
'''
CREATE TABLE offenses (
tdcj_number INTEGER,
offense_number SERIAL,
offense_date DATE NOT NULL,
offense VARCHAR(32) NOT NULL,
sentence_date DATE NOT NULL,
county VARCHAR(13) NOT NULL,
case_number VARCHAR(18),
sentence INTEGER NOT NULL,
PRIMARY KEY (tdcj_number, offense_number),
FOREIGN KEY (tdcj_number)
REFERENCES offenders (tdcj_number)
)
''',
'''
CREATE TABLE offender_pipe_err (
sid_number INTEGER UNIQUE,
tdcj_number INTEGER PRIMARY KEY,
name VARCHAR(30) NOT NULL,
race CHAR(1) NOT NULL,
gender BOOLEAN NOT NULL,
date_of_birth DATE NOT NULL,
max_sentence_date DATE,
msd_category SMALLINT,
current_facility VARCHAR(30) NOT NULL,
projected_release_date DATE,
parole_eligibility_date DATE,
visitation_eligible VARCHAR(4),
last_accessed TIMESTAMP NOT NULL
)
'''
)
for c in commands:
cur.execute(c)
conn.commit()
cur.close()
conn.close()
def prep_offender_data(entry):
"""
Cleans data to insert into SQL database.
Args:
entry: 1 offender's info and offense history
Returns:
tuple: (cleaned offender info dict, cleaned offense history array)
"""
offense_dict = entry.pop('offensetable')
tdcj_num = entry['_id']
entry['Maximum Sentence Date'], entry['MSD_cat'] = split_msd_cat(\
entry['Maximum Sentence Date'])
if abs(entry['MSD_cat']) > 1:
entry['Projected Release Date'] = None
if abs(entry['MSD_cat']) > 2:
entry['Parole Eligibility Date'] = None
if entry['Parole Eligibility Date'] == 'NOT AVAILABLE':
entry['Parole Eligibility Date'] = None
if entry['Projected Release Date'] == 'NOT AVAILABLE':
entry['Projected Release Date'] = None
entry['Gender'] = entry['Gender'] == 'F'
offenses = [\
{k:offense_dict[k][i] for k in offense_dict.keys()}\
for i in offense_dict['Offense'].keys()\
]
for offense in offenses:
offense['tdcj_num'] = tdcj_num
offense['Sentence'] = sentence_str_to_days_int(\
offense.pop('Sentence (YY-MM-DD)'))
return entry, offenses
def insert_offender(conn, cur, entry):
"""
Cleans and inserts the information and offense history of a single offender.
Args:
conn: connection to the postgres DB
cur: cursor for the postgres DB
entry: entry to clean and insert
Raises:
Any exception that occurs during insertion with extra info
to assist identifying the problematic record.
"""
#clean data
offender_info, offenses = prep_offender_data(entry)
#query template
command=\
"""
INSERT INTO {} (
sid_number,
tdcj_number,
name,
race,
gender,
date_of_birth,
max_sentence_date,
msd_category,
current_facility,
projected_release_date,
parole_eligibility_date,
visitation_eligible,
last_accessed
)
VALUES (
%(SID Number)s,
%(_id)s,
%(Name)s,
%(Race)s,
%(Gender)s,
%(DOB)s,
%(Maximum Sentence Date)s,
%(MSD_cat)s,
%(Current Facility)s,
%(Projected Release Date)s,
%(Parole Eligibility Date)s,
%(Offender Visitation Eligible)s,
%(accessed)s
);
"""
#insert a record
try:
cur.execute(command.format('offenders'), offender_info)
conn.commit()
#for the SID or TDCJ number, insert the record in an error table instead.
except UniqueViolation:
conn.rollback()
cur.execute(command.format('offender_pipe_err'), offender_info)
return
#for a different exception, re-raise it with information about the problematic record.
except Exception as e:
raise type(e)(f'{str(e)} tdcj_num={offender_info["_id"]}')\
.with_traceback(sys.exc_info()[2])
#insert the offender's offense history
insert_offenses(cur, offenses)
def insert_offenses(cur, offenses):
"""
Inserts a list of dicts containing cleaned offense history into the SQL DB.
Args:
cur: cursor to the SQL DB
offenses: a list of cleaned offense dicts
"""
for offense in offenses:
cur.execute(
"""
INSERT INTO offenses (
tdcj_number,
offense_date,
offense,
sentence_date,
county,
case_number,
sentence
)
VALUES (
%(tdcj_num)s,
%(Offense Date)s,
%(Offense)s,
%(Sentence Date)s,
%(County)s,
%(Case No)s,
%(Sentence)s
);
""", offense)
def split_msd_cat(msd):
"""
Splits the date portion and codifies occasional accompanying text
into a tuple
Args:
msd: maximum sentence date
Raises:
ValueError for unhandled value cases
"""
mode = 1
if msd.endswith('CUMULATIVE OFFENSES'):
mode = -1
msd = msd[:-19].strip()
if msd == 'LIFE SENTENCE':
return (None, 2*mode)
elif msd == 'LIFE WITHOUT PAROLE':
return (None, 3*mode)
elif msd == 'NOT AVAILABLE':
return (None, 4*mode)
elif msd == 'DEATH ROW':
return (None, 5*mode)
else:
try:
return (datetime.strptime(msd, '%Y-%m-%d'), mode)
except ValueError as e:
raise type(e)(f'{str(e)} value: msd={msd}')\
.with_traceback(sys.exc_info()[2])
def sentence_str_to_days_int(string):
"""
Turns two formats of sentence lengths into a timedelta object in order to
be cast as an INTERVAL type in the future.
Args:
string: string containing the length of the sentence in either
'Y-M-D' or 'DDD Days' formats
Returns:
timedelta object
"""
if string.endswith('Days'):
return int(string[:-4])
vals = [int(i) for i in string.split('-')]
return vals[0]*365 + vals[1]*30 + vals[2]
if __name__ == '__main__':
_reset_tdcj_pgdb()
_create_tables()
run_pipe()
| Greenford/tdcj | src/pgpipe.py | pgpipe.py | py | 9,224 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "pymongo.MongoClient",
"line_number": 23,
"usage_type": "call"
},
{
"api_name": "psycopg2.connect",
"line_number": 31,
"usage_type": "call"
},
{
"api_name": "sys.exc_info",
"line_number": 44,
"usage_type": "call"
},
{
"api_name": "psycopg2.connect",
... |
4914466088 | from typing import List, Dict
import networkx as nx
def best_route(G: nx.Graph, start_node: int) -> List[int]:
if G is None or start_node not in G.nodes:
return None
for node in G.nodes():
if 'depth' not in G.nodes[node]:
G.nodes[node]['depth'] = 0
if 'full' not in G.nodes[node]:
G.nodes[node]['full'] = False
current_depth = G.nodes[start_node]['depth']
visited_nodes = [start_node]
while True:
comp_data = [(n, G.nodes[n]['full']) for n in G.nodes()]
next_comp_idx = find_next_empty_component(comp_data, visited_nodes[-1])
if next_comp_idx == -1:
return visited_nodes
neighbors = list(G.neighbors(visited_nodes[-1]))
candidates = [n for n in neighbors if G.nodes[n]['depth'] > current_depth and not G.nodes[n]['full']]
if not candidates:
return visited_nodes
next_node = min(candidates, key=lambda x: G.nodes[x]['depth'])
visited_nodes.append(next_node)
G.nodes[next_node]['full'] = True
current_depth = G.nodes[next_node]['depth']
def find_next_empty_component(components: List[Dict[int, bool]], start_idx: int) -> int:
for idx, comp in enumerate(components[start_idx:], start=start_idx):
if not comp[1]:
return idx
return -1
| andreza-vilar/Teoria-dos-Grafos | EP01/src/Q04.py | Q04.py | py | 1,348 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "networkx.Graph",
"line_number": 4,
"usage_type": "attribute"
},
{
"api_name": "typing.List",
"line_number": 4,
"usage_type": "name"
},
{
"api_name": "typing.List",
"line_number": 38,
"usage_type": "name"
},
{
"api_name": "typing.Dict",
"line_num... |
20581426977 | # mongoDB使用案例
import pymongo
client = pymongo.MongoClient(host='127.0.0.1', port=27017, username="root", password="123456", authSource="test", authMechanism='SCRAM-SHA-1')
# 获取数据库
db = client['test']
# 获取集合
# collection = db['aaa']
# 或
# collection = db.aaa
for i in db.aaa.find({'by': '菜鸟教程'}):
print("data = %s" %(i))
# 插入数据库
json = {
'title': 'Python教程',
'description': 'Python是一门脚本语言',
'by': '小橙子',
'url': 'http://www.baidu.com',
'tags': ['python', 'script'],
'likes': 101
}
res = db['aaa'].insert_one(json)
print(res, res.inserted_id)
# 查询一条符合条件的数据
data = db['aaa'].find_one({'by': '小橙子'})
print("data = %s" %(data))
# 修改数据
res = db.aaa.update_one({'by': '小橙子'}, {'$set': {'title': 'Python基础教程'}})
# modified_count,返回更新的条数
print(res, res.modified_count)
# 更新数据
#res = db.chat.update_many({"age": {"$gte": 0}}, {"$set": {"age": 888}})
# print(res, res.modified_count)
# 查询一条符合条件的数据
data = db['aaa'].find_one({'by': '小橙子'})
print("data = %s" %(data))
# 关闭数据库
client.close()
| qugemingzizhemefeijin/python-study | ylspideraction/chapter04/_005mongodb.py | _005mongodb.py | py | 1,207 | python | zh | code | 1 | github-code | 1 | [
{
"api_name": "pymongo.MongoClient",
"line_number": 4,
"usage_type": "call"
}
] |
15779411139 | # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# Import data provided by Towne et al. and perform Spectral-POD #
# #
# do it in Python and train yourself #
# #
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# import libraries -------------
#import sys
import h5py
import time
import numpy as np
import matplotlib
matplotlib.use('TkAgg') # do this before importing pylab
import matplotlib.pyplot as plt
from pod import pod_time
# beginning of the program -----
print('\n Start of the program.\n')
# read data --------------------
filen = '/home/davide/PROJECTS/SpectralPOD/spod-towne/spod_matlab-master/jet_data/jetLES.mat'
f = h5py.File(filen, 'r') # h5py.File acts like a Python dictionary
print('list(f.keys()):', list(f.keys()))
print('f:', f)
for i1 in range(0,len(f)):
print(' field', i1,'. key: ',list(f.keys())[i1], \
' shape: ',f[list(f.keys())[i1]].shape)
# plot mean pressure field -----
cmap = plt.get_cmap('PiYG')
fig, ax = plt.subplots()
ax.axis('equal')
ax.autoscale(enable=True, axis='y', tight=True)
cs = ax.contourf(f["x"],f["r"],f["p_mean"])
# Proper Orthogoanl Decomposition of p
pres = f["p"]
dt = f['dt'][0,0]
print('dt:', dt)
# only on the first 100 snapshots
pres = pres[:,:,0:2000]
# uPOD, s, vh = pod_time(pres,dt)
# # Show some PODs
# for ipod in range(0,2):
# fig, ax = plt.subplots()
# ax.axis('equal')
# ax.autoscale(enable=True, axis='y', tight=True)
# cs = ax.contourf(f["x"],f["r"],uPOD[:,:,ipod])
# plt.show()
# FFT --------------------------
# fft of a block
# Reshape the input as a 2-dimensional array:
n = len(pres.shape)-1 # n. of 'non-time' dimensions
# 1st index for the unravelled 'non-time' dimensions
# 2nd index for the time variable
p2D = np.reshape(pres, (np.product(pres.shape[0:n]),pres.shape[n]) )
n2D = p2D.shape[1]
print(' len(p2D.shape): ', len(p2D.shape))
print(' p2D.shape : ', p2D.shape)
Nf = 512
q1 = p2D[:,0:Nf]
meanq1 = np.mean(q1,axis=1)
#
# Reshape POD mode back to the original dimensions
meanq13D = np.reshape(meanq1, pres.shape[0:2])
cmap = plt.get_cmap('PiYG')
fig, ax = plt.subplots()
ax.axis('equal')
ax.autoscale(enable=True, axis='y', tight=True)
cs = ax.contourf(f["x"],f["r"],meanq13D)
print(' meanq1.shape : ', meanq1.shape)
for i in range(0,q1.shape[1]): # remove mean value
q1[:,i] = q1[:,i] - meanq1
Q1 = np.fft.fft(q1)
print(' q1.shape : ', q1.shape)
print(' Q1.shape : ', Q1.shape)
normQ1 = np.zeros(q1.shape[1])
for i in range(0,q1.shape[1]):
normQ1[i] = np.sqrt(np.sum(np.conjugate(Q1[:,i]) * Q1[:,i]))
print(' normQ1[',i,']:',normQ1[i])
T = dt * Nf # observation period
dOm = 2*np.pi / T # frequency resolution
om = np.arange(0,Q1.shape[1]) * dOm
plt.figure(101)
plt.plot(om,normQ1)
plt.show()
# find dominant mode
indmax = np.argmax(normQ1)
print(' indmax: ', indmax)
print(' indmax: ', indmax, '. omega: ', indmax*dOm)
# Reshape dominant mode back to the original dimensions
mode = np.reshape(Q1[:,indmax], pres.shape[0:2])
cmap = plt.get_cmap('PiYG')
plt.figure(102)
plt.subplot(211)
plt.contourf(f["x"],f["r"],np.real(mode))
plt.axis('scaled')
plt.subplot(212)
plt.contourf(f["x"],f["r"],np.imag(mode))
plt.axis('scaled')
plt.show()
# # low-dimensional example ----------------------
# data = np.array( [[[0, 1],
# [2, 3],
# [4, 5]],
# [[6, 7],
# [8, 9],
# [10, 11]]] )
# datav_C = np.ravel(data,order='C')
# datav_F = np.ravel(data,order='F')
# print('data.shape: ', data.shape)
# print('datav_C.shape: ', datav_C.shape)
# print('datav_C : ', datav_C )
# print('datav_F.shape: ', datav_F.shape)
# print('datav_F : ', datav_F )
# pod_time(data)
# # low-dimensional example ----------------------
# # plt.show()
#
# # plot movie pressure time evolution ----
# dt = f['dt'][0][0]
# nt = f['p'].shape[2] # f['nt'][0][0]
# print('nt: ',f['p'].shape[2],', dt: ',dt)
# pmin = 4.33963 # np.amin(f['p'])
# pmax = 4.51078 # np.amax(f['p'])
# print('min(p):', pmin)
# print('max(p):', pmax)
#
# fig_mov = plt.figure()
# nclevs = 30
# #plt.ion()
# def animate():
# for i in range(0,int(nt),20):
# print('i: ',i,'. t = ',i*f['dt'][0,0])
# # im=plt.imshow(f["p"][:,:,i])
# im=plt.contourf(f["x"],f["r"],f["p"][:,:,i], nclevs, \
# vmin=pmin, vmax=pmax , \
# cmap=plt.cm.bone )
# fig_mov.canvas.draw()
# # time.sleep(1.0)
#
# win = fig_mov.canvas.manager.window
# fig_mov.canvas.manager.window.after(1000, animate)
# #plt.axis('equal')
# plt.axis([0, 20, 0, 2.9],'equal')
# plt.gca().set_aspect('equal', adjustable='box')
# plt.show()
#
#
#
# print('\n End of the program. Bye!\n')
# # end of the program -----
| licia13/project-polimi | projects/SpectralPOD/spod-python/old_py/towne_data2.py | towne_data2.py | py | 4,981 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "matplotlib.use",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "h5py.File",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "matplotlib.pyplot.get_cmap",
"line_number": 34,
"usage_type": "call"
},
{
"api_name": "matplotlib.pyplot... |
12600495568 | import shutil
import subprocess
import os, sys
from utils import Platforms, fsl_assert, Stages, ShaderTarget, StageFlags, ShaderBinary, fsl_platform_assert
import tempfile, struct
fsl_basepath = os.path.dirname(__file__)
_config = {
Platforms.DIRECT3D11: ('FSL_COMPILER_FXC', 'fxc.exe'),
Platforms.DIRECT3D12: ('FSL_COMPILER_DXC', 'dxc.exe'),
Platforms.VULKAN: ('VULKAN_SDK', 'Bin/glslangValidator.exe'),
Platforms.ANDROID: ('VULKAN_SDK', 'Bin/glslangValidator.exe'),
Platforms.SWITCH: ('VULKAN_SDK', 'Bin/glslangValidator.exe'),
Platforms.QUEST: ('VULKAN_SDK', 'Bin/glslangValidator.exe'),
Platforms.MACOS: ('FSL_COMPILER_MACOS', 'metal.exe'),
Platforms.IOS: ('FSL_COMPILER_IOS', 'metal.exe'),
Platforms.ORBIS: ('SCE_ORBIS_SDK_DIR', 'host_tools/bin/orbis-wave-psslc.exe'),
Platforms.PROSPERO: ('SCE_PROSPERO_SDK_DIR', 'host_tools/bin/prospero-wave-psslc.exe'),
Platforms.XBOX: ('GXDKLATEST', 'bin/XboxOne/dxc.exe'),
Platforms.SCARLETT: ('GXDKLATEST', 'bin/Scarlett/dxc.exe'),
Platforms.GLES: ('VULKAN_SDK', 'Bin/glslangValidator.exe'),
}
def get_available_compilers():
available = []
for lang, compiler_path in _config.items():
if get_compiler_from_env(*compiler_path, _assert=False):
available += [lang.name]
return available
def get_status(bin, params):
# For some reason calling subprocess.getstatusoutput on these platforms fails
if sys.platform == "darwin" or sys.platform == "linux":
result = subprocess.run([bin] + params, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return result.returncode, result.stderr.decode() + result.stdout.decode()
else:
return subprocess.getstatusoutput([bin] + params)
def get_compiler_from_env(varname, subpath = None, _assert=True):
if os.name == 'posix' and 'metal.exe' in subpath:
return 'xcrun'
if sys.platform == "linux" and 'VULKAN_SDK' in varname:
return "glslangValidator"
if not varname in os.environ:
print('WARN: {} not in env vars'.format(varname))
if _assert: assert False
return None
compiler = os.environ[varname]
if subpath: compiler = os.path.join(compiler, subpath)
if not os.path.exists(compiler):
print('WARN: {} doesn\'t exist'.format(compiler))
if _assert: assert False
return None
return os.path.abspath(compiler)
def util_shadertarget_dx(stage, shader_target):
stage_dx = {
Stages.VERT: 'vs',
Stages.FRAG: 'ps',
Stages.COMP: 'cs',
Stages.GEOM: 'gs',
Stages.TESC: 'hs',
Stages.TESE: 'ds',
}
return stage_dx[stage] + shader_target.name[2:]
def util_shadertarget_metal(shader_target):
return shader_target.name[4:].replace("_",".")
def compile_binary(platform: Platforms, debug: bool, binary: ShaderBinary, src, dst):
# remove any existing binaries
if os.path.exists(dst): os.remove(dst)
if sys.platform == 'win32': # todo
if src.startswith("//"):
src = src.replace("//", "\\\\", 1)
if dst.startswith("//"):
dst = dst.replace("//", "\\\\", 1)
bin = get_compiler_from_env(*_config[platform])
class CompiledDerivative:
def __init__(self):
self.hash = 0
self.code = b''
compiled_derivatives = []
for derivative_index, derivative in enumerate(binary.derivatives[platform]):
compiled_filepath = os.path.join(tempfile.gettempdir(), next(tempfile._get_candidate_names()))
params = []
if platform in [Platforms.VULKAN, Platforms.QUEST, Platforms.SWITCH, Platforms.ANDROID]:
if debug: params += ['-g']
params += ['-V', src, '-o', compiled_filepath, '-I'+fsl_basepath]
params += ['-S', binary.stage.name.lower()]
params += ['--target-env', 'vulkan1.1']
elif platform == Platforms.DIRECT3D11:
if debug: params += ['/Zi']
params += ['/T', util_shadertarget_dx(binary.stage, ShaderTarget.ST_5_0)] # d3d11 doesn't support other shader targets
params += ['/I', fsl_basepath, '/Fo', compiled_filepath, src]
elif platform == Platforms.DIRECT3D12:
if debug: params += ['/Zi', '-Qembed_debug']
params += ['/T', util_shadertarget_dx(binary.stage, binary.target)]
params += ['/I', fsl_basepath, '/Fo', compiled_filepath, src]
elif platform == Platforms.ORBIS:
# todo: if debug: ...
params = ['-DGNM', '-O4', '-cache', '-cachedir', os.path.dirname(dst)]
shader_profile = {
Stages.VERT: 'sce_vs_vs_orbis',
Stages.FRAG: 'sce_ps_orbis',
Stages.COMP: 'sce_cs_orbis',
Stages.GEOM: 'sce_gs_orbis',
Stages.TESC: 'sce_hs_off_chip_orbis',
Stages.TESE: 'sce_ds_vs_off_chip_orbis',
}
profile = shader_profile[binary.stage]
# Vertex shader is local shader in tessellation pipeline and domain shader is the vertex shader
if binary.stage == Stages.VERT:
if StageFlags.ORBIS_TESC in binary.flags:
profile = 'sce_vs_ls_orbis'
elif StageFlags.ORBIS_GEOM in binary.flags:
profile = 'sce_vs_es_orbis'
params += ['-profile', profile]
params += ['-I'+fsl_basepath, '-o', compiled_filepath, src]
elif platform == Platforms.PROSPERO:
# todo: if debug: ...
params = ['-DGNM', '-O4']
shader_profile = {
Stages.VERT: 'sce_vs_vs_prospero',
Stages.FRAG: 'sce_ps_prospero',
Stages.COMP: 'sce_cs_prospero',
Stages.GEOM: 'sce_gs_prospero',
Stages.TESC: 'sce_hs_prospero',
Stages.TESE: 'sce_ds_vs_prospero',
}
params += ['-profile', shader_profile[binary.stage]]
params += ['-I'+fsl_basepath, '-o', compiled_filepath, src]
elif platform == Platforms.XBOX:
if debug: params += ['/Zi', '-Qembed_debug']
params += ['/T', util_shadertarget_dx(binary.stage, binary.target)]
params += ['/I', fsl_basepath, '/D__XBOX_DISABLE_PRECOMPILE', '/Fo', compiled_filepath, src]
elif platform == Platforms.SCARLETT:
if debug: params += ['/Zi', '-Qembed_debug']
params += ['/T', util_shadertarget_dx(binary.stage, binary.target)]
params += ['/I', fsl_basepath, '/D__XBOX_DISABLE_PRECOMPILE', '/Fo', compiled_filepath, src]
elif platform == Platforms.GLES:
params = [src, '-I'+fsl_basepath]
params += ['-S', binary.stage.name.lower()]
with open(compiled_filepath, "wb") as dummy:
dummy.write(b'NULL')
elif platform == Platforms.MACOS:
# todo: if debug: ...
if os.name == 'nt':
params = ['-I', fsl_basepath]
params += ['-dD', '-o', compiled_filepath, src]
else:
params = '-sdk macosx metal '.split(' ')
params += [f"-std=macos-metal{util_shadertarget_metal(binary.target)}"]
params += ['-I', fsl_basepath]
params += ['-dD', src, '-o', compiled_filepath]
elif platform == Platforms.IOS:
# todo: if debug: ...
if os.name == 'nt':
params = ['-I', fsl_basepath]
params += ['-dD','-std=ios-metal2.2', '-mios-version-min=8.0', '-o', compiled_filepath, src]
else:
params = '-sdk iphoneos metal'.split(' ')
params += [f"-std=ios-metal{util_shadertarget_metal(binary.target)}"]
params += ['-mios-version-min=11.0']
params += ['-I', fsl_basepath]
params += ['-dD', src, '-o', compiled_filepath]
params += ['-D' + define for define in derivative ]
cp = subprocess.run([bin] + params, stdout=subprocess.PIPE)
fsl_platform_assert(platform, cp.returncode == 0, binary.fsl_filepath, message=cp.stdout.decode())
with open(compiled_filepath, 'rb') as compiled_binary:
cd = CompiledDerivative()
cd.hash = derivative_index # hash(''.join(derivative)) #TODO If we use a hash it needs to be the same as in C++
cd.code = compiled_binary.read()
compiled_derivatives += [ cd ]
with open(dst, 'wb') as combined_binary:
# Needs to match:
#
# struct FSLMetadata
# {
# uint32_t mUseMultiView;
# };
#
# struct FSLHeader
# {
# char mMagic[4];
# uint32_t mDerivativeCount;
# FSLMetadata mMetadata;
# };
num_derivatives = len(compiled_derivatives)
combined_binary.write(struct.pack('=4sI', b'@FSL', num_derivatives) )
combined_binary.write(struct.pack('=I', StageFlags.VR_MULTIVIEW in binary.flags))
data_start = combined_binary.tell() + 24 * num_derivatives
for cd in compiled_derivatives:
combined_binary.write(struct.pack('=QQQ', cd.hash, data_start, len(cd.code)))
data_start += len(cd.code)
for cd in compiled_derivatives:
combined_binary.write(cd.code)
return 0 | ConfettiFX/The-Forge | Common_3/Tools/ForgeShadingLanguage/compilers.py | compilers.py | py | 9,468 | python | en | code | 4,045 | github-code | 1 | [
{
"api_name": "os.path.dirname",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 7,
"usage_type": "attribute"
},
{
"api_name": "utils.Platforms.DIRECT3D11",
"line_number": 10,
"usage_type": "attribute"
},
{
"api_name": "utils.Plat... |
1058797528 | import mtbot.protocol as p
from hashlib import sha1
from base64 import b64encode
from time import time
# Class for seqnums
# And Packetbuffer later
class Seqnum:
"""docstring for Seqnum.
Managing mt seqnums"""
def __init__(self):
self.seqs = {}
self.next = p.seqnum_initial
def pop(self, seq):
key = str(int.from_bytes(seq, "big") - p.seqnum_initial)
if key in self.seqs:
self.seqs.pop(key)
def get(self):
s = self.next
self.next += 1
if self.next > p.seqnum_max:
self.next = p.seqnum_initial
return s.to_bytes(2, byteorder="big")
def buffer(self, seq, buf):
self.seqs[str((int.from_bytes(seq, "big") - p.seqnum_initial))] = (buf, time())
def toresend(self):
out = []
for i in self.seqs:
buf, t = self.seqs[i]
if t+2 < time():
out.append(buf)
self.seqs[i] = (buf, time())
return out
def translate_password(name, password):
if len(password) == 0:
return ""
sr = name + password
sh = sha1(sr).digest()
return b64encode(sh)
def std_string(sr):
n = sr
if isinstance(sr, str):
n = sr.encode()
return numbtobyte(len(n), 2) + n
def from_std_wstring(string):
newstring = ""
for i in range(len(string[2:])):
s = string[i + 2]
if s != 0:
newstring += chr(s)
return newstring
def to_std_wstring(string):
newbyte = b""
len = 0
for i in string:
len += 1
newbyte += b"\x00" + i.encode()
return numbtobyte(len, 2) + newbyte
def std_stringtobyte(bytes):
return bytes[2:]
def bytetonumb(bytes):
return int.from_bytes(bytes, "big")
def numbtobyte(numb, size=1):
return numb.to_bytes(size, byteorder="big")
# access the bytes in the array using byt[4:5] instead of byt[4] to get binary data.
def makePacket(peer_id, channel, data):
byt = p.protocol_id
byt += peer_id
byt += p.channel[channel]
byt += data
return byt
def makeDataControl(controltype, cdata=b""):
byt = p.packagetype["control"]
byt += controltype
if cdata != -1:
byt += cdata
return byt
def makeDataOriginal(command, data=-1):
byt = p.packagetype["original"]
byt += command
if data != -1:
byt += data
return byt
def makeDataReliable(seqnum, data):
byt = p.packagetype["reliable"]
byt += seqnum
byt += data
return byt
def readPacket(data):
if len(data) >= 9:
if data[:4] == p.protocol_id:
peer_id = data[4:6]
channel = data[6]
type = data[7:8]
reliable = False
seqnum = b"\x00"
if type == p.packagetype["control"]:
type, data = "control", readControl(data[7:])
elif type == p.packagetype["original"]:
type, data = "original", readOriginal(data[7:])
elif type == p.packagetype["split"]:
type, data = "split", data[7:]
elif type == p.packagetype["reliable"]:
reliable = True
seqnum, type, data = readReliable(data[7:])
return peer_id, channel, type, reliable, seqnum, data
return False
def readControl(data):
controltype = data[1:2]
if controltype == p.controltype["ack"]:
seqnum = data[2:4]
return "ack", seqnum
elif controltype == p.controltype["set_peer_id"]:
peer_id = data[2:4]
return "set_peer_id", peer_id
elif controltype == p.controltype["disco"]:
return "disco", "a"
def readOriginal(data):
command = data[1:3]
data = data[3:]
return command, data
def readReliable(data):
seqnum = data[1:3]
type = data[3:4]
if type == p.packagetype["control"]:
return seqnum, "control", readControl(data[3:])
elif type == p.packagetype["original"]:
return seqnum, "original", readOriginal(data[3:])
elif type == p.packagetype["split"]:
return seqnum, "split", data[3:]
| Lejo1/mtmodule | mtbot/botpackage.py | botpackage.py | py | 4,096 | python | en | code | 1 | github-code | 1 | [
{
"api_name": "mtbot.protocol.seqnum_initial",
"line_number": 16,
"usage_type": "attribute"
},
{
"api_name": "mtbot.protocol",
"line_number": 16,
"usage_type": "name"
},
{
"api_name": "mtbot.protocol.seqnum_initial",
"line_number": 19,
"usage_type": "attribute"
},
{
... |
25088177569 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 2 18:44:36 2020
@author: czhang
"""
# this is to create B0 map from 3D phases of 3D fully sampled images.
## delete h5 variables
import h5py
import numpy as np
import torch
from fastMRI.data import transforms
from training_utils import helpers
from training_utils.linear_mapping import LeastSquares
from pdb import set_trace as bp
import time
from skimage.restoration import unwrap_phase
from matplotlib import pyplot as plt
fname = '/home/czhang/lood_storage/divh/BMEPH/Henk/STAIRS/other/Chaoping/raw_data/phases.h5'
with h5py.File(fname, 'r') as data:
data.keys()
phases = data['phases'][:]
mask_brain = data['mask_brain'][:]
phase_unwrapped = np.zeros(phases.shape)
for i in range(phases.shape[0]):
phase_unwrapped[i] = unwrap_phase(np.ma.array(phases[i], mask=np.zeros(phases[i].shape)))
TEs = (3.0, 11.5, 20.0, 28.5)
phase_diff_set = []
TE_diff = []
TEnotused = 3
# obtain phase differences and TE differences
testplot = []
for i in range(0, phase_unwrapped.shape[0] - TEnotused):
phase_diff_set.append((phase_unwrapped[i + 1] - phase_unwrapped[i]).flatten())
phase_diff_set[i] = phase_diff_set[i] - np.round(np.sum(phase_diff_set[i] * mask_brain.flatten())/np.sum(mask_brain.flatten())/2/np.pi) *2*np.pi
TE_diff.append(TEs[i + 1] - TEs[i])
phase_diff_set = np.stack(phase_diff_set, 0)
TE_diff = np.stack(TE_diff, 0)
# least squares fitting to obtain phase map
scaling = 1e-3
ls = LeastSquares()
B0_map_tmp = ls.lstq_pinv(torch.from_numpy(np.transpose(np.expand_dims(phase_diff_set, 2), (1, 0, 2))), torch.from_numpy(np.expand_dims(TE_diff, 1) * scaling))
B0_map = B0_map_tmp.reshape(phase_unwrapped.shape[1:4])
B0_map = B0_map.numpy()
data = h5py.File(fname, 'r+')
data.__delitem__('B0_map')
data.create_dataset('B0_map', data=B0_map)
| chaopingzhang/qRIM | preprocess/B0mapping.py | B0mapping.py | py | 1,945 | python | en | code | 5 | github-code | 1 | [
{
"api_name": "h5py.File",
"line_number": 25,
"usage_type": "call"
},
{
"api_name": "numpy.zeros",
"line_number": 29,
"usage_type": "call"
},
{
"api_name": "skimage.restoration.unwrap_phase",
"line_number": 31,
"usage_type": "call"
},
{
"api_name": "numpy.ma.array... |
40797678122 | from cx_Freeze import setup, Executable
exe=Executable(
script="client.py",
)
includefiles=["config.txt"]
includes=[]
excludes=[]
packages=['requests']
setup(
version = "1.1",
description = "No Description",
author = "Name",
name = "App name",
options = {'build_exe': {'excludes':excludes,'packages':packages,'include_files':includefiles}},
executables = [exe]
)
# from cx_Freeze import setup, Executable
# setup(name='client',
# version='1.1',
# options={'build.exe':{'packages': ['requests'],
# 'include_files': ['config.txt'],}},
# executables = [Executable('client.py')]
# )
# options = {
# 'build_exe': {
# 'include_msvcr': True,
# # 'excludes': excludes,
# 'includes': includes,
# 'zip_include_packages': zip_include_packages,
# 'build_exe': 'build_windows',
# 'include_files': include_files,
# }
# } | Ovsienko023/VTerminale | Application-VT/client/setup.py | setup.py | py | 972 | python | en | code | 2 | github-code | 1 | [
{
"api_name": "cx_Freeze.Executable",
"line_number": 3,
"usage_type": "call"
},
{
"api_name": "cx_Freeze.setup",
"line_number": 10,
"usage_type": "call"
}
] |
39999918194 | '''Build the vocabulary for the yelp dataset'''
import json
from collections import Counter
# stop words are words that occur very frequently,
# and that don't seem to carry information
# about the quality of the review.
# we decide to keep 'not', for example, as negation is an important info.
# I also keep ! which I think might be more frequent in negative reviews, and which is
# typically used to make a statement stronger (in good or in bad).
# the period, on the other hand, can probably be considered neutral
# this could have been done at a later stage as well,
# but we can do it here as this stage is fast
stopwords = set(['.','i','a','and','the','to', 'was', 'it', 'of', 'for', 'in', 'my',
'that', 'so', 'do', 'our', 'the', 'and', ',', 'my', 'in', 'we', 'you',
'are', 'is', 'be', 'me'])
def process_file(fname, options):
'''process a review JSLON lines file and count the occurence
of each words in all reviews.
returns the counter, which will be used to find the most frequent words
'''
print(fname)
with open(fname) as ifile:
counter = Counter()
for i,line in enumerate(ifile):
if i==options.lines:
break
if i%10000==0:
print(i)
data = json.loads(line)
# extract what we want
words = data['text']
for word in words:
if word in stopwords:
continue
counter[word]+=1
return counter
def parse_args():
from optparse import OptionParser
from base import setopts
usage = "usage: %prog [options] <file_pattern>"
parser = OptionParser(usage=usage)
setopts(parser)
parser.add_option("-n", "--nwords",
dest="nwords", default=20000, type=int,
help="max number of words in vocabulary, default 20000")
(options, args) = parser.parse_args()
if len(args)!=1:
parser.print_usage()
sys.exit(1)
pattern = args[0]
return options, pattern
if __name__ == '__main__':
import os
import glob
import pprint
from vocabulary import Vocabulary
import parallelize
options, pattern = parse_args()
olddir = os.getcwd()
os.chdir(options.datadir)
fnames = glob.glob(pattern)
nprocesses = len(fnames) if options.parallel else None
results = parallelize.run(process_file, fnames, nprocesses, options)
full_counter = Counter()
for counter in results:
full_counter.update(counter)
vocabulary = Vocabulary(full_counter, n_most_common=options.nwords)
vocabulary.save('index')
pprint.pprint(full_counter.most_common(200))
print(len(full_counter))
print(vocabulary)
os.chdir(olddir) | cbernet/maldives | yelp/yelp_vocabulary.py | yelp_vocabulary.py | py | 2,865 | python | en | code | 3 | github-code | 1 | [
{
"api_name": "collections.Counter",
"line_number": 26,
"usage_type": "call"
},
{
"api_name": "json.loads",
"line_number": 32,
"usage_type": "call"
},
{
"api_name": "optparse.OptionParser",
"line_number": 45,
"usage_type": "call"
},
{
"api_name": "base.setopts",
... |
24589467623 | import os
import json
g = {
"max-processes": 128,
"output-size": 16,
"compile-time": 5000,
"compile-memory": 256,
"mem-bonus": {
},
"time-bonus": {
},
"enabled": ['.c', '.cpp', '.py'],
}
def loadConfig():
global g
try:
with open(os.path.dirname(__file__) + '/config.json') as f:
fileconf = json.loads(f.read())
for key in fileconf:
g[key] = fileconf[key]
print('Config loaded from config.json')
except FileNotFoundError:
print('Warning: config.json not found. Default config used.')
def generateConfig():
with open(os.path.dirname(__file__) + '/Backend/config.sh', "w") as f:
f.write('RAMDISKSIZE={}\n'.format(g['output-size'] + 8))
| taoky/OJSandbox | config.py | config.py | py | 761 | python | en | code | 3 | github-code | 1 | [
{
"api_name": "os.path.dirname",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 19,
"usage_type": "attribute"
},
{
"api_name": "json.loads",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "os.path.dirname",
"line_n... |
32023785821 | import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import rcParams
from matplotlib import style
import datetime
from os import path
style.use('ggplot')
rcParams.update({'font.size': 9})
fig, ax = plt.subplots(sharex=True, figsize=(8.5, 4.8))
fig_size = plt.rcParams["figure.figsize"]
df = pd.read_csv('U.S._Natural_Gas_Exports.csv')
df.dropna()
df = df.iloc[::-1]
print(df.columns)
mycolors = ['saddlebrown', '#3b5998', '#ffbf00']
a = df.plot(x = 'Month', y=['U.S. LNG Exports',\
'U.S. Natural Gas Pipeline Exports to Mexico',\
'U.S. Natural Gas Pipeline Exports to Canada',\
], kind="area", color=mycolors, alpha=0.88, ax=ax)
for line in a.lines:
line.set_linewidth(0)
a.xaxis.grid(False)
handles, labels = a.get_legend_handles_labels()
a.legend(reversed(handles), reversed(labels), bbox_to_anchor=(.85, -0.115), loc='best', ncol=1, fontsize='x-large')
plt.tick_params(axis='x', labelsize=8)
plt.xlabel("Date", color='black')
plt.ylabel("Billion Cubic Feet per Day (Bcf/d)",color='black')
plt.savefig(path.basename(__file__)+".png",bbox_inches='tight')
# plt.show()
| nshahr/Data-Visualization | U.S._Natural_Gas_Exports_and_Re-Exports_by_Country.py | U.S._Natural_Gas_Exports_and_Re-Exports_by_Country.py | py | 1,194 | python | en | code | 0 | github-code | 1 | [
{
"api_name": "matplotlib.style.use",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "matplotlib.style",
"line_number": 8,
"usage_type": "name"
},
{
"api_name": "matplotlib.rcParams.update",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "matplot... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.