how to dynamically reload watail_hooks.py in wagtail admin? - wagtail

I rebuild the main menu in wagtail admin with the file wagtail_hooks.py. When I update the database, the main menu will change according to the new content in the database. Part of the file wagtail_hooks.py are as follows:
factories = DicFactory.objects.all()
num = len(factories)
factoryMenus = []
equipmentMenus = []
simulationMenus = []
equipmentNum = []
simulationNum = []
for fac in factories:
partURL = '/admin/home/dicequipment/?factory_id='
fullURL = partURL + str(fac.id)
factoryMenus.append(MenuItem(fac.name, fullURL, classnames='icon icon-pilcrow', order=10000))
equipments = DicEquipment.objects.filter(factory_id = fac.id)
equipmentNum.append(len(equipments))
for eq in equipments:
partURL = '/admin/home/simulation/?equipment_id='
fullURL = partURL + str(eq.id)
equipmentMenus.append(MenuItem(eq.name, fullURL, classnames='icon icon-chain-broken', order=10000))
simulations = Simulation.objects.filter(equipment_id = eq.id)
simulationNum.append(len(simulations))
for sim in simulations:
partURL = '/admin/home/simulation/inspect/'
fullURL = partURL + str(sim.id) +'/?integrityCheck=true'
simulationMenus.append(MenuItem(sim.name, fullURL, classnames='icon icon-list-ol', order=10000))
#construct the main menu
#hooks.register('construct_main_menu')
def hide_images_menu_item(request, menu_items):
menu_items[:] = [item for item in menu_items if item.name != 'images']
menu_items[:] = [item for item in menu_items if item.name != 'documents']
menu_items[:] = [item for item in menu_items if item.name != 'reports']
menu_items[:] = [item for item in menu_items if item.name != 'settings']
menu_items[:] = [item for item in menu_items if item.name != 'explorer']
menu_items[:] = [item for item in menu_items if item.label != '工厂']
menu_items[:] = [item for item in menu_items if item.label != '装置']
menu_items[:] = [item for item in menu_items if item.label != '数字模型']
menu_items[:] = [item for item in menu_items if item.label != '算例列表']
menu_items[:] = [item for item in menu_items if item.label != '算例输入']
menu_items[:] = [item for item in menu_items if item.label != '硬件环境']
menu_items[:] = [item for item in menu_items if item.label != '模拟软件']
menu_items[:] = [item for item in menu_items if item.label != '人员列表']
menu_items[:] = [item for item in menu_items if item.label != '算例输入']
menu_items.append(MenuItem('工厂', '/admin/home/dicfactory/', classnames='icon icon-folder-open-inverse', order=10000))
equipmentMenuIndex = 0
simulationMenuIndex = 0
factoryIndex = 0
equipmentIndex = 0
for i in range(num):
menu_items.append(factoryMenus[i])
for j in range(equipmentNum[factoryIndex]):
menu_items.append(equipmentMenus[equipmentMenuIndex])
equipmentMenuIndex = equipmentMenuIndex +1
for k in range(simulationNum[equipmentIndex]):
menu_items.append(simulationMenus[simulationMenuIndex])
simulationMenuIndex = simulationMenuIndex +1
equipmentIndex = equipmentIndex + 1
factoryIndex = factoryIndex + 1
How to automatically reload the file wagtail_hooks.py when database changed? Wish for your answer and help. Thank you.
This is the admin page in my website. When I add a factory, the new factory name should appear in the main menu.

Move all of your code into the hide_images_menu_item hook function. This will then be run on every page request - code that's not in a function but just in the body of wagtail_hooks.py will only be run once, at startup.

Related

How to pass loop and dynamic task id in jinja template in Airflow BashOperator and SSHOperator

I am trying to create multiple task in loop and pass the dynamically generated task ids of PythonOperator in the BashOperator and SSHOperator for XCOM pull.
for group_key in range(1,5):
dag = create_dag(group_key)
globals()[dag.dag_id] = dag
for i in range(2):
delete_xcom_task = PostgresOperator(
task_id='delete-xcom-task_'+str(i),
postgres_conn_id='pg_airflow_db',
sql= "delete from xcom where dag_id= '" + dag.dag_id + "' ",
dag=dag)
t0_get_next = PythonOperator(
task_id='load_hist_pkg_to_ts_'+ str(i),
provide_context=True,
python_callable=load_hist_pkg_to_ts,
xcom_push=True,
op_kwargs={'pg_conn_id':pg_conn_id,
'pg_conn_schema': pg_conn_schema,
},
dag=dag)
t1_check_file=ShortCircuitOperator(
task_id='check_if_file_exist_'+str(i),
python_callable=_check_files,
provide_context=True,
op_kwargs={'load_hist_pkg_to_ts_cnt':'load_hist_pkg_to_ts_'+str(i),
},
dag=dag,
)
t0_move_file = BashOperator(
task_id='bash_move_file_'+str(i),
bash_command= "{{ ti.xcom_pull(key = 't0_bash_move_file' , task_ids = 'load_hist_pkg_to_ts_~i~' , dag_id = ti.dag_id) }}",
dag=dag)
t1_copyfile = SSHOperator(
ssh_conn_id='ssh_execute_rempte',
task_id='ssh_file_to_postgres_'+str(i),
xcom_push=True,
command= "{{ ti.xcom_pull(key = 't1_bash_copy' , task_ids = 'load_hist_pkg_to_ts_~i~' , dag_id = ti.dag_id) }}",
dag=dag)
t2_archive_file = BashOperator(
task_id='bash_archive_file_'+str(i),
bash_command= "{{ ti.xcom_pull(key = 't2_bash_remove_file' , task_ids = 'load_hist_pkg_to_ts_~i~' , dag_id = ti.dag_id) }}",
dag=dag)
delete_xcom_task>>t0_get_next >>t1_check_file>>t0_move_file>>t1_copyfile>>t2_archive_file
Solved -- had to do like below
bash_command= "{{{{ ti.xcom_pull(key = 't2_bash_remove_file' , task_ids = 'load_hist_pkg_to_ts_{}' , dag_id = ti.dag_id)}}}}".format(i),

Problem in php array is not work with while

I have a php code when I want to show info to the browser it show me : Notice: Array to string conversion in
Can You Help Me Please I want to show this information from function because I don't want to create new while one every request.
function get_school($school_code){
global $conn,$Lang;
$school_select = $conn->query("SELECT * FROM schools WHERE code='$school_code'");
$school_exs = $school_select->num_rows;
if ($school_exs != 0) {
$show = array();
while ($school_info = mysqli_fetch_array($school_select)) {
$nestedData = array();
$nestedData[] = $school_info['id'];
$nestedData[] = $school_info['name'];
$nestedData[] = $school_info['code'];
$nestedData[] = $school_info['type'];
$nestedData[] = $school_info['wilaya'];
$nestedData[] = $school_info['baladiya'];
$nestedData[] = $school_info['capacity'];
$nestedData[] = $school_info['phone'];
$nestedData[] = $school_info['email'];
$nestedData[] = $school_info['adress'];
$nestedData[] = $school_info['arabic_name'];
$nestedData[] = $school_info['direction'];
$nestedData[] = $school_info['language'];
$show[] = $nestedData;
}
}else{
}
return $show;
}
echo get_school($admin_school_code);
You are returning an array therefore you cannot use echo.
Try to var_dump(get_school($admin_school_code)) or print_r(get_school($admin_school_code))

How to get all selected Checkbox values into a sql query

I have a multiple filter query like this:
I want to make the checkboxes be selected and then added to the following query:
var db = Database.Open("RMS") ;
var selectCommand = "SELECT * FROM RMS";
var formSSO = "";
var formCase_Status= "";
var fromDate = "";
var toDate = "";
var SQLSELECT = "SELECT * FROM Admins WHERE Email = #0";
var Email = WebSecurity.CurrentUserName;
var data1 = db.QuerySingle(SQLSELECT, Email);
var Name = data1.Name;
formSSO = Request.QueryString["formSSO"];
formCase_Status = Request["formCase_Status[]"];
fromDate = Request.QueryString["fromDate"];
toDate = Request.QueryString["toDate"];
selectCommand = "SELECT * FROM RMS WHERE Assigned_To = #4";
if(!Request.QueryString["formSSO"].IsEmpty() ) {
selectCommand +=" AND SSO LIKE #0";
}
if(!Request.QueryString["formCase_Status"].IsEmpty() ) {
selectCommand +=" AND Case_Status = #1";
}
if(!Request.QueryString["fromDate"].IsEmpty() ) {
selectCommand +=" AND Created >= #2";
}
if(!Request.QueryString["toDate"].IsEmpty() ) {
selectCommand +=" AND Created <= #3";
}
I can get it working if only one checkbox is selected but my main point is to allow multiple checkboxes to be checked. How can I do this either with JS or Jquery I have tried answers on other qts but they don't quite go with what I am doing. I don't want an alert but a way that I can call all checked values in the select statement.
This is the checkbox:
<li class="form-line form-line-column" id="id_20">
<label class="form-label-top" id="label_20" for="input_20"> Status </label>
<div id="cid_20" class="form-input-wide">
<input type="checkbox" checked="#(Request["formCase_Status[]"] == "In Progress")" name="formCase_Status[]" value="In Progress"> In Progress<br>
<input type="checkbox" checked="#(Request["formCase_Status[]"] == "Pending")" name="formCase_Status[]" value="Pending"> Pending<br>
<input type="checkbox" checked="#(Request["formCase_Status[]"] == "Closed")" name="formCase_Status[]" value="Closed"> Closed<br>
</div>
</li>

Query Slow in Linq, Fast in LinqPad, SQL Management Studio and SQL Profiler

I have this linq query i'm using and it's taking 50 seconds to run when i am running it my asp.net application, however the same query executes in 500ms in LinqPad and Sql Management Studio.
I even took the query from the SQL Profiler and ran it again in SQL Management Studio and it takes around 500ms. What overhead Linq could be doing, that an extra 49s??
Below is the code for reference, thanks for your help.
var rCampaign =
(from a in db.AdCreative
join h in db.AdHit on a.ID equals h.AdID into gh
join l in db.AdGroup_Location on a.AdGroupID equals l.AdGroupID into gj
from subloc in gj.DefaultIfEmpty()
from subhits in gh.DefaultIfEmpty()
where a.AdGroup.AdHost.Select(q => q.ID).Contains(rPlatform.ID) &&
a.AdGroup.AdPublisher.Select(q => q.ID).Contains(rPublisher.ID) &&
a.AdDimensionID == AdSize &&
a.AdGroup.Campaign.Starts <= rNow &&
a.AdGroup.Campaign.Ends >= rNow &&
subhits.HitType == 1 &&
(subloc == null || subloc.LocationID == rLocationID)
select new {
ID = a.ID,
Name = a.Name,
Spent = (subhits.AdDimension != null) ? ((double)subhits.AdDimension.Credit / 1000) : 0,
CampaignID = a.AdGroup.Campaign.ID,
CampaignName = a.AdGroup.Campaign.Name,
CampaignBudget = a.AdGroup.Campaign.DailyBudget
}).GroupBy(adgroup => adgroup.ID)
.Select(adgroup => new {
ID = adgroup.Key,
Name = adgroup.FirstOrDefault().Name,
Spent = adgroup.Sum(q => q.Spent),
CampaignID = adgroup.FirstOrDefault().CampaignID,
CampaignName = adgroup.FirstOrDefault().CampaignName,
CampaignBudget = adgroup.FirstOrDefault().CampaignBudget,
})
.GroupBy(q => q.CampaignID)
.Select(campaigngroup => new {
CampaignID = campaigngroup.Key,
DailyBudget = campaigngroup.FirstOrDefault().CampaignBudget,
Consumed = campaigngroup.Sum(q => q.Spent),
RemainningCredit = campaigngroup.FirstOrDefault().CampaignBudget - campaigngroup.Sum(q => q.Spent),
Ads = campaigngroup.Select(ag => new {
ID = ag.ID,
Name = ag.Name,
Spent = ag.Spent
}).OrderBy(q => q.Spent)
})
.Where(q => q.Consumed <= q.DailyBudget).OrderByDescending(q => q.RemainningCredit).First();
There are a few ways you can simplify that query:
select into lets you keep it all in query syntax.
The join ... into/from/DefaultIfMany constructs implementing left joins can be replaced with join ... into construcs representing group joins.
Some of the groups near the end cannot be empty, so FirstOrDefault is unnecessary.
Some of the where conditions can be moved up to the top before the query gets complicated.
Here's the stab I took at it. The revisions were significant, so it might need a little debugging:
var rCampaign = (
from a in db.AdCreative
where a.AdDimensionID == AdSize &&
a.AdGroup.Campaign.Starts <= rNow &&
a.AdGroup.Campaign.Ends >= rNow &&
a.AdGroup.AdHost.Select(q => q.ID).Contains(rPlatform.ID) &&
a.AdGroup.AdPublisher.Select(q => q.ID).Contains(rPublisher.ID)
join hit in db.AdHit.Where(h => h.HitType == 1 && h.LocationID == rLocationID)
on a.ID equals hit.AdID
into hits
join loc in db.AdGroup_Location
on a.AdGroupID equals loc.AdGroupID
into locs
where !locs.Any() || locs.Any(l => l.LocationID == rLocationID)
select new {
a.ID,
a.Name,
Spent = hits.Sum(h => h.AdDimension.Credit / 1000) ?? 0,
CampaignID = a.AdGroup.Campaign.ID,
CampaignName = a.AdGroup.Campaign.Name,
CampaignBudget = a.AdGroup.Campaign.DailyBudget,
} into adgroup
group adgroup by adgroup.CampaignID into campaigngroup
select new
{
CampaignID = campaigngroup.Key,
DailyBudget = campaigngroup.First().CampaignBudget,
Consumed = campaigngroup.Sum(q => q.Spent),
RemainingCredit = campaigngroup.First().CampaignBudget - campaigngroup.Sum(q => q.Spent),
Ads = campaigngroup.Select(ag => new {
ag.ID,
ag.Name,
ag.Spent,
}).OrderBy(q => q.Spent)
} into q
where q.Consumed <= q.DailyBudget
orderby q.RemainingCredit desc)
.First()
I refactored using Query syntax (Not sure if it improved readability). Removed one group by. Made some minor adjustments (replaced FirstOrDefault with Key property, changed Contains to Any). Hopefully it has some effect of speed.
var rCampaign = (from cg in
(from a in db.AdCreative
from subhits in db.AdHit.Where(h => a.ID == h.AdID)
.DefaultIfEmpty()
from subloc in db.AdGroup_Location.Where(l => a.AdGroupID == l.AdGroupID)
.DefaultIfEmpty()
where a.AdGroup.AdHost.Any(q => q.ID == rPlatform.ID) &&
a.AdGroup.AdPublisher.Any(q => q.ID == rPublisher.ID) &&
a.AdDimensionID == AdSize &&
a.AdGroup.Campaign.Starts <= rNow &&
a.AdGroup.Campaign.Ends >= rNow &&
subhits.HitType == 1 &&
(subloc == null || subloc.LocationID == rLocationID)
group new { a, subhits } by new { ID = a.ID, a.Name, CampaignID = a.AdGroup.Campaign.ID, CampaignName = a.AdGroup.Campaign.Name, CampaignBudget = a.AdGroup.Campaign.DailyBudget } into g
select new
{
ID = g.Key.ID,
Name = g.Key.Name,
Spent = g.Sum(x => (x.subhits.AdDimension != null) ? ((double)subhits.AdDimension.Credit / 1000) : 0),
CampaignID = g.Key.CampaignID,
CampaignName = g.Key.CampaignName,
CampaignBudget = g.Key.CampaignBudget
})
group cg by new { cg.CampaignID, cg.CampaignBudget } into cg
let tempConsumed = cg.Sum(q => q.Spent)
let tempRemainningCredit = cg.Key.CampaignBudget - tempConsumed
where tempConsumed <= cg.Key.CampaignBudget
orderby tempRemainningCredit desc
select new
{
CampaignID = cg.Key.CampaignID,
DailyBudget = cg.Key.CampaignBudget,
Consumed = tempConsumed,
RemainningCredit = tempRemainningCredit,
Ads = from ag in cg
orderby ag.Spent
select new
{
ID = ag.ID,
Name = ag.Name,
Spent = ag.Spent
}
}).First();

How do i correct jqgrid footer information?

I am using jqgrid in one of my application.
Right now i am facing a strange problem and do not know how to rectify it?
Actually in one of the reports (having multiple link) jqgrid is showing wrong footer information that is its showing Page 0 of 0 even if there are records in the table.
This is the code which runs:
if( isset($this->params['named']['ajax']) && $this->params['named']['ajax'] == '1' )
{
$this->autoRender = false;
// get how many rows we want to have into the grid - rowNum parameter in the grid
$limit = $this->params['url']['rows'];
// get index row - i.e. user click to sort. At first time sortname parameter -
// after that the index from colModel
$sidx = $this->params['url']['sidx'];
// sorting order - at first time sortorder
$sord = $this->params['url']['sord'];
$page = $this->params['url']['page'];
// if we not pass at first time index use the first column for the index or what you want
if( !$sidx ) $sidx = 1;
// calculate the number of rows for the query. We need this for paging the result
$findconditions = array();
if(!empty($this->params['named']['batch']))
array_push(&$findconditions, array('Batch.id' => $this->params['named']['batch'] ));
$row = $this->Placement->find('count',array(
'link' => array(
'Student' => array(
'Batch'
)
),
'conditions'=> $findconditions
));
$count = $row;
// calculate the total pages for the query
if( $count > 0 )
{
$total_pages = ceil($count / $limit);
}
else
{
$total_pages = 0;
}
// if for some reasons the requested page is greater than the total
// set the requested page to total page
if( $page > $total_pages ) $page = $total_pages;
// calculate the starting position of the rows
$start = $limit * $page - $limit;
// if for some reasons start position is negative set it to 0
// typical case is that the user type 0 for the requested page
if( $start < 0 ) $start = 0;
// the actual query for the grid data
$limit_range = $start . "," . $limit;
$sort_range = $this->modelClass . '.' . $sidx . " " . $sord;
$this->Placement->recursive = -1;
$where='';
if( $this->params['url']['_search'] == 'true' )
{
//pr($this->params);
$searchconditions = array();
if( isset($this->params['named']['batch']) && !empty($this->params['named']['batch']) )
{
$where.= " Batch.id =".$this->params['named']['batch'];
}
if( isset($this->params['url']['isstillworking']) && !empty($this->params['url']['isstillworking']) )
{
$where.= " AND Placement.isstillworking ='".$this->params['url']['isstillworking']."'";
}
if( isset($this->params['url']['studentname']) && !empty($this->params['url']['studentname']) )
{
$where.=" AND Student.fullname LIKE '" .$this->params['url']['studentname'] . "%'";
}
if( isset($this->params['url']['companyname']) && !empty($this->params['url']['companyname']) )
{
$where.=" AND Company.name LIKE '" .$this->params['url']['companyname'] . "%'";
}
if( isset($this->params['url']['salary']) && !empty($this->params['url']['salary']) )
{
$where.= " AND Placement.salary =".$this->params['url']['salary'];
}
if( isset($this->params['url']['contactnumber1']) && !empty($this->params['url']['contactnumber1']) )
{
$where.= " AND Student.contactnumber1 =".$this->params['url']['contactnumber1'];
}
if( isset($this->params['url']['batchname']) && !empty($this->params['url']['batchname']) )
{
$where.=" AND Batch.name LIKE '" .$this->params['url']['batchname'] . "%'";
}
$sql="SELECT Student.fullname,
Placement.isstillworking,
Company.id,
Company.name,
Placement.id,
Placement.salary,
Placement.created,
Student.id,
Student.contactnumber1,
Batch.id,
Batch.name
FROM placements Placement
INNER JOIN (
SELECT student_id, isstillworking, max( created ) AS other_col
FROM placements
GROUP BY student_id
) AS b ON Placement.student_id = b.student_id
AND Placement.created = b.other_col
INNER JOIN students Student ON ( Student.id = Placement.student_id )
INNER JOIN batches Batch ON ( Student.batch_id = Batch.id )
INNER JOIN companies Company ON ( Company.id = Placement.company_id )
WHERE ".$where.
" AND Student.type='student'
AND Student.trainingcompleted=1
ORDER BY ".$sort_range."
LIMIT ".$limit_range
;
$result=$this->Placement->query($sql);
}
else
{
$sql="SELECT Student.fullname,
Placement.isstillworking,
Company.id,
Company.name,
Placement.id,
Placement.salary,
Placement.created,
Student.id,
Student.contactnumber1,
Batch.id,
Batch.name
FROM placements Placement
INNER JOIN (
SELECT student_id, isstillworking, max( created ) AS other_col
FROM placements
GROUP BY student_id
) AS b ON Placement.student_id = b.student_id
AND Placement.created = b.other_col
INNER JOIN students Student ON ( Student.id = Placement.student_id )
INNER JOIN batches Batch ON ( Student.batch_id = Batch.id )
INNER JOIN companies Company ON ( Company.id = Placement.company_id )
WHERE Batch.id =
".$this->params['named']['batch'].
" AND Student.type='student'
AND Student.trainingcompleted=1
ORDER BY ".$sort_range."
LIMIT ".$limit_range
;
$result=$this->Placement->query($sql);
}
$i = 0;
$response->page = $page;
$response->total = $total_pages;
$response->records = $count;
//pr($result);
foreach($result as $result)
{
$response->rows[$i]['id'] = $result['Placement']['id'];
$student = "<a href='" . APP_URL . "placements/report18/studentid:" . $result['Student']['id']."'>" . $result['Student']['fullname'] . "</a>";
$company = "<a href='" . APP_URL . "companies/view/" . $result['Company']['id'] . "'>" . $result['Company']['name'] . "</a>";
$batch = "<a href='" . APP_URL . "batches/view/" . $result['Batch']['id'] . "'>" . $result['Batch']['name'] . "</a>";
$contactnumber1 =$result['Student']['contactnumber1'];
$response->rows[$i]['cell'] = array($student, $result['Placement']['isstillworking'], $result['Company']['name'], $result['Placement']['salary'], $contactnumber1, $batch);
$i++;
}
echo json_encode($response);
}
I am also attaching the screen shot for reference.
Please help me on this.
Regards,
Pankaj
Why on earth would you not use Cake's ORM layer and Pagination class? If you use Model->query() you have to escape input yourself!

Resources