When I try to put form = SQLFORM.grid(db.mytable) in my controller the request changes to my/web/site/view?_signature=520af19b1095db04dda2f1b6cbea3a03c3551e13 which causes my if statement in controller to collapse. Can smbd please explain why this happens?
If I put user_signature=False then on view load the grid is shown (though the looks is awful, and I still need to find out how to change the view of my table), but on search,edit, etc. click, the same thing happens again. The url is changed and I get an error
Any suggestions?
thank you
EDIT
This is my edit function
#auth.requires_login()
def edit():
#Load workers
workers = db(db.worker.w_organisation == 10).select(db.worker.w_id_w, db.worker.w_organisation, db.worker.w_first_name, db.worker.w_last_name,db.worker.w_nick_name,db.worker.w_email,db.worker.w_status,db.worker.w_note).as_list()
#Define the query object. Here we are pulling all contacts having date of birth less than 18 Nov 1990
query = ((db.worker.w_organisation == 10) & (db.worker.w_status==db.status.s_id_s))
#Define the fields to show on grid. Note: (you need to specify id field in fields section in 1.99.2
fields = (db.worker.w_first_name, db.worker.w_last_name,db.worker.w_nick_name,db.worker.w_email,db.status.s_code,db.worker.w_note)
#Define headers as tuples/dictionaries
headers = { 'worker.w_first_name' : 'Ime',
'worker.w_last_name' : 'Priimek',
'worker.w_nick_name' : 'Vzdevek',
'worker.w_email' : 'E-posta',
'status.s_code': 'Status',
'worker.w_note' : 'Komentar' }
#Let's specify a default sort order on date_of_birth column in grid
default_sort_order=[db.worker.w_last_name]
#Creating the grid object
form = SQLFORM.grid(query=query, fields=fields, headers=headers,searchable=True, orderby=default_sort_order,create=True, \
deletable=True, editable=True, maxtextlength=64, paginate=25,user_signature=False
)
form = SQLFORM.grid(db.worker,user_signature=False)
workersDb = db((db.worker.w_organisation == 10) & (db.worker.w_status==db.status.s_id_s)).select(db.worker.w_id_w, \
db.worker.w_organisation, db.worker.w_first_name, \
db.worker.w_last_name,db.worker.w_nick_name,db.worker.w_email,\
db.status.s_code,db.worker.w_note).as_list()
workersList = []
for rec in workersDb:
status = rec['status']['s_code']
workers = rec['worker']
if not rec["worker"]["w_first_name"]:
polno_ime = rec["worker"]["w_last_name"]
elif not rec["worker"]["w_last_name"]:
polno_ime = rec["worker"]["w_first_name"]
else:
polno_ime = rec["worker"]["w_first_name"] + " " + rec["worker"]["w_last_name"]
rec["worker"]['w_full_name'] = polno_ime
rec["worker"]["w_status"] = status
data = rec["worker"]
#print rec
#print data
workersList.append(rec["worker"])
# If type of arg is int, we know that user wants to edit a script with an id of the argument
if(request.args[0].isdigit()):
script = db(getDbScript(request.args[0])).select(db.script.sc_lls, db.script.sc_name, db.script.id, db.script.sc_menu_data).first()
formData = str(script["sc_menu_data"])
#form = SQLFORM.grid(db.auth_user)
#print formData
# If we dont get any results that means that user is not giving proper request and we show him error
#print script
#Parsing script to be inserted into view
if not script:
return error(0)
return dict(newScript = False, script = script, formData = formData, workers = workersList, form = form)
# If the argument is new we prepare page for new script
elif request.args[0] == 'new':
scripts = db((auth.user.organization == db.script.sc_organization)).select(db.script.sc_name, db.script.id, workers = workersList, form = form)
return dict(newScript = True, scripts = scripts, workers = workersList, form = form)
# Else error
else:
return error(0)
also not to mention the sqlgrid looks awful, here is link to the picture https://plus.google.com/103827646559093653557/posts/Bci4PCG4BQQ
Related
I have the below model for a my dynamodb table using pynamodb :
from pynamodb.models import Model
from pynamodb.attributes import (
UnicodeAttribute, UTCDateTimeAttribute, UnicodeSetAttribute, BooleanAttribute
)
class Reminders(Model):
"""Model class for the Reminders table."""
# Information on global secondary index for the table
# user_id (hash key) + reminder_id+reminder_title(sort key)
class Meta:
table_name = 'Reminders'
region = 'eu-central-1'
reminder_id = UnicodeAttribute(hash_key=True)
user_id = UnicodeAttribute(range_key=True)
reminder_title = UnicodeAttribute()
reminder_tags = UnicodeSetAttribute()
reminder_description = UnicodeAttribute()
reminder_frequency = UnicodeAttribute(default='Only once')
reminder_tasks = UnicodeSetAttribute(default=set())
reminder_expiration_date_time = UTCDateTimeAttribute(null=True)
reminder_title_reminder_id = UnicodeAttribute()
next_reminder_date_time = UTCDateTimeAttribute()
should_expire = BooleanAttribute()
When i want to create a new reminder i do it through the below code :
class DynamoBackend:
#staticmethod
def create_a_new_reminder(new_reminder: NewReminder) -> Dict[str, Any]:
"""Create a new reminder using pynamodb."""
new_reminder = models.Reminders(**new_reminder.dict())
return new_reminder.save()
In this case the NewReminder is an instance of pydantic base model like so :
class NewReminder(pydantic.BaseModel):
reminder_id: str
user_id: str
reminder_title: str
reminder_description: str
reminder_tags: Sequence[str]
reminder_frequency: str
should_expire: bool
reminder_expiration_date_time: Optional[datetime.datetime]
next_reminder_date_time: datetime.datetime
reminder_title_reminder_id: str
when i call the save method on the model object i receive the below response:
{
"ConsumedCapacity": {
"CapacityUnits": 2.0,
"TableName": "Reminders"
}
}
Now my question is the save method is directly being called by a lambda function which is in turn called by an API Gateway POST endpoint so ideally the response should be a 201 created and instead of returning the consumed capacity and table name , would be great if it returns the item inserted in the database. Below is my route code :
def create_a_new_reminder():
"""Creates a new reminder in the database."""
request_context = app.current_request.context
request_body = json.loads(app.current_request.raw_body.decode())
request_body["reminder_frequency"] = data_structures.ReminderFrequency[request_body["reminder_frequency"]]
reminder_details = data_structures.ReminderDetailsFromRequest.parse_obj(request_body)
user_details = data_structures.UserDetails(
user_name=request_context["authorizer"]["claims"]["cognito:username"],
user_email=request_context["authorizer"]["claims"]["email"]
)
reminder_id = str(uuid.uuid1())
new_reminder = data_structures.NewReminder(
reminder_id=reminder_id,
user_id=user_details.user_name,
reminder_title=reminder_details.reminder_title,
reminder_description=reminder_details.reminder_description,
reminder_tags=reminder_details.reminder_tags,
reminder_frequency=reminder_details.reminder_frequency.value[0],
should_expire=reminder_details.should_expire,
reminder_expiration_date_time=reminder_details.reminder_expiration_date_time,
next_reminder_date_time=reminder_details.next_reminder_date_time,
reminder_title_reminder_id=f"{reminder_details.reminder_title}-{reminder_id}"
)
return DynamoBackend.create_a_new_reminder(new_reminder=new_reminder)
I am very new to REST API creation and best practices so would be great if someone would guide me here . Thanks in advance !
I'm tweaking my bosun.conf to allow my os.cpu.high alert to use a lookup when determining which duration to to use depending on the host:
lookup high_cpu {
entry host=* {
time = 5m
}
entry host=*graylog* {
time = 1h
}
}
alert os.cpu.high {
template = generic.graph
macro = host.based.contacts
$notes = Find CPU usage that is continually high
$duration = lookup("high_cpu", "time")
$host = *
$metric = "sum:rate{counter,,1}:os.cpu{host=$host}"
$q_cpu = q($metric, "$duration", "")
$q = avg($q_cpu)
warn = $q > 95
crit = $q > 99
ignoreUnknown = true
$q_format = %f
$unit_string = %
$generic_graph = $q_cpu
$graph_unit = %
}
This is the error I get when testing:
conf: Test Config:424:4: at <warn = $q > 95>: expr: unexpected "high" in func
I am not very familiar with bosun and this is probably an easy fix, but I'm at my wit's end. Any help would be appreciated
You can't do this, as lookups don't support a string return type.
This particular scenario would be problematic anyways since what you are trying to do is query different amount of times based on the result of the query, so you have a chicken and egg problem.
What you can do is query the max amount of time you want to query and then shorten some results in the set using the crop function. However the crop function is not in a release yet so you would have to get it in master. You can see the documentation with an example of what you are trying to do in this commit for now, i.e.:
lookup test {
entry host=ny-bosun01 {
start = 30
}
entry host=* {
start = 60
}
}
alert test {
template = test
$q = q("avg:rate:os.cpu{host=ny-bosun*}", "5m", "")
$c = crop($q, lookup("test", "start") , 0)
crit = avg($c)
}
Firstly I am getting some informations from a text file, later these informations are added to pdf files' meta data. In the "Producer" section an error was occured about Turkish characters as ğ, ş. And I solved the problem via using UTF-16 like this:
write.Info.Put(new PdfName("Producer"), new PdfString("Ankara Üniversitesi Hukuk Fakültesi Dergisi (AÜHFD), C.59, S.2, y.2010, s.309-334.", "UTF-16"));
Here is the screenshot:
Then, I am getting all pdf files with foreach loop and reading meta data and insert into SQLite database file. The problem occurs right here. Because when I want to get from pdf file and set to database file UTF-16 encoded string (Producer data), it arises strange characters like this:
I don't understand, why it occurs error.
EDIT: Here is my all codes. The following codes get meta data from text file and insert pdf files' meta meta section:
var articles = Directory.GetFiles(FILE_PATH, "*.pdf");
foreach (var article in articles)
{
var file_name = Path.GetFileName(article);
var read = new PdfReader(article);
var size = read.GetPageSizeWithRotation(1);
var doc = new Document(size);
var write = PdfWriter.GetInstance(doc, new FileStream(TEMP_PATH + file_name, FileMode.Create, FileAccess.Write));
// Article file names like, 1.pdf, 2.pdf, 3.pdf....
// article_meta_data.txt file content like this:
//1#Article 1 Tag Number#Article 1 first - last page number#Article 1 Title#Article 1 Author#Article 1 Subject#Article 1 Keywords
//2#Article 2 Tag Number#Article 2 first - last page number#Article 2 Title#Article 2 Author#Article 2 Subject#Article 2 Keywords
//3#Article 3 Tag Number#Article 3 first - last page number#Article 3 Title#Article 3 Author#Article 3 Subject#Article 3 Keywords
var pdf_file_name = Convert.ToInt32(Path.GetFileNameWithoutExtension(article)) - 1;
var line = File.ReadAllLines(FILE_PATH + #"article_meta_data.txt");
var info = line[pdf_file_name].Split('#');
var producer = Kunye(info); // It returns like: Ankara Üniversitesi Hukuk Fakültesi Dergisi (AÜHFD), C.59, S.2, y.2010, s.309-334.
var keywords = string.IsNullOrEmpty(info[6]) ? "" : info[6];
doc.AddTitle(info[3]);
doc.AddSubject(info[5]);
doc.AddCreator("UzPDF");
doc.AddAuthor(info[4]);
write.Info.Put(new PdfName("Producer"), new PdfString(producer, "UTF-16"));
doc.AddKeywords(keywords);
doc.Open();
var cb = write.DirectContent;
for (var page_number = 1; page_number <= read.NumberOfPages; page_number++)
{
doc.NewPage();
var page = write.GetImportedPage(read, page_number);
cb.AddTemplate(page, 0, 0);
}
doc.Close();
read.Close();
File.Delete(article);
File.Move(TEMP_PATH + file_name, FILE_PATH + file_name);
}
And the following codes get data from files and insert SQLite database file. For database operation, I am using Devart - dotConnect for SQLite.
var files = Directory.GetFiles(FILE_PATH, "*.pdf");
var connection = new Linq2SQLiteDataContext();
TruncateTable(connection);
var i = 1;
foreach (var file in files)
{
var read = new PdfReader(file);
var title = read.Info["Title"].Trim();
var author = read.Info["Author"].Trim();
var producer = read.Info["Producer"].Trim();
var file_name = Path.GetFileName(file)?.Trim();
var subject = read.Info["Subject"].Trim();
var keywords = read.Info["Keywords"].Trim();
var art = new article
{
id = i,
title = (title.Length > 255) ? title.Substring(0, 255) : title,
author = (author.Length > 100) ? author.Substring(0, 100) : author,
producer = (producer.Length > 255) ? producer.Substring(0, 255) : producer,
filename = file_name != null && (file_name.Length > 50) ? file_name.Substring(0, 50) : file_name,
subject = (subject.Length > 50) ? subject.Substring(0, 50) : subject,
keywords = (keywords.Length > 500) ? keywords.Substring(0, 500) : keywords,
createdate = File.GetCreationTime(file),
update = File.GetLastWriteTime(file)
};
connection.articles.InsertOnSubmit(art);
i++;
}
connection.SubmitChanges();
Instead of:
new PdfString(producer, "UTF-16")
Use:
new PdfString(producer, PdfString.TEXT_UNICODE)
UTF-16 is a specific way to store Unicode values but you don't need to worry about that, iText will take care of everything for you.
i'm wondering if anyone can help me figure out how to programatically set the document number and date in the general journal trans, under the tab invoice. I'm trying to post to the general journal in ax 2012 with x++. I currently have this code that works but there is no method under the ledgerjournal trans to set the document no or date. infact alot of the setters are missing and only has linenum account type, journal num etc etc.
How can i set these fields? below i have some code
static void TestLedgerJournalImport(Args _args)
{
// Set these variables.
LedgerJournalNameId journalName = 'GenJrn';
SelectableDataArea company = '019';
TransDate transactionDate = 30\6\2012;
str line1MainAccount = '131310';
str line1FullAccount = '131310--';
str line2MainAccount = '131310';
str line2FullAccount = '131310-10-';
str line2Dimension1Name = 'Department';
str line2Dimension1Value = 'ACCT';
LedgerGeneralJournalService ledgerGeneralJournalService;
LedgerGeneralJournal ledgerGeneralJournal;
AfStronglyTypedDataContainerList journalHeaderCollection;
LedgerGeneralJournal_LedgerJournalTable journalHeader;
AifEntityKeyList journalHeaderCollectionKeyList;
RecId journalHeaderRecId;
AfStronglyTypedDataContainerList journalLineCollection;
LedgerGeneralJournal_LedgerJournalTrans journalLine1;
AifMultiTypeAccount journalLine1LedgerDimension;
LedgerGeneralJournal_LedgerJournalTrans journalLine2;
AifMultiTypeAccount journalLine2LedgerDimension;
AifDimensionAttributeValue journalLine2Dim1;
AfStronglyTypedDataContainerList journalLine2DimensionCollection;
;
ledgerGeneralJournalService = LedgerGeneralJournalService::construct();
ledgerGeneralJournal = new LedgerGeneralJournal();
// Create journal header.
journalHeaderCollection = ledgerGeneralJournal.createLedgerJournalTable();
journalHeader = journalHeaderCollection.insertNew(1);
journalHeader.parmJournalName(journalName);
// Create journal lines.
journalLineCollection = journalHeader.createLedgerJournalTrans();
// Line 1
journalLine1 = journalLineCollection.insertNew(1);
journalLine1.parmLineNum(1.00);
journalLine1.parmCompany(company);
journalLine1.parmTransDate(transactionDate);
journalLine1.parmAccountType(LedgerJournalACType::Ledger);
journalLine1.parmTxt('Test journal transaction');
journalLine1.parmAmountCurDebit(100.00);
journalLine1LedgerDimension = journalLine1.createLedgerDimension();
journalLine1LedgerDimension.parmAccount(line1MainAccount);
journalLine1LedgerDimension.parmDisplayValue(line1FullAccount);
journalLine1.parmLedgerDimension(journalLine1LedgerDimension);
// Line 2
journalLine2 = journalLineCollection.insertNew(2);
journalLine2.parmLineNum(2.00);
journalLine2.parmCompany(company);
journalLine2.parmTransDate(transactionDate);
journalLine2.parmAccountType(LedgerJournalACType::Ledger);
journalLine2.parmTxt('Test journal transaction');
journalLine2.parmAmountCurCredit(100.00);
journalLine2LedgerDimension = journalLine2.createLedgerDimension();
journalLine2DimensionCollection = journalLine2LedgerDimension.createValues();
journalLine2Dim1 = new AifDimensionAttributeValue();
journalLine2Dim1.parmName(line2Dimension1Name);
journalLine2Dim1.parmValue(line2Dimension1Value);
journalLine2DimensionCollection.add(journalLine2Dim1);
journalLine2LedgerDimension.parmAccount(line2MainAccount);
journalLine2LedgerDimension.parmDisplayValue(line2FullAccount);
journalLine2LedgerDimension.parmValues(journalLine2DimensionCollection);
journalLine2.parmLedgerDimension(journalLine2LedgerDimension);
// Insert records.
journalHeader.parmLedgerJournalTrans(journalLineCollection);
ledgerGeneralJournal.parmLedgerJournalTable(journalHeaderCollection);
journalHeaderCollectionKeyList =
LedgerGeneralJournalService.create(ledgerGeneralJournal);
journalHeaderRecId =
journalHeaderCollectionKeyList.getEntityKey(1).parmRecId();
info(strFmt("LedgerJournalTable.Recid = %1", int642str(journalHeaderRecId)));
}
Don't do it like that, you're making more work for yourself. I just wrote this example for you. I hacked up a more complex piece of code I wrote, so the offsetDefaultDimension I just left in for some example code.
static void Job3(Args _args)
{
AxLedgerJournalTable journalTable = AxLedgerJournalTable::construct();
LedgerJournalTable ledgerJournalTable;
LedgerJournalName ledgerJournalName = LedgerJournalName::find('GenJrn');
AxLedgerJournalTrans journalTrans = AxLedgerJournalTrans::construct();
DimensionAttribute dimensionAttribute;
DimensionAttributeValue dimensionAttributeValue;
DimensionAttributeValueSetStorage dimStorage;
LedgerDimensionAccount ledgerDimension = DimensionDefaultingService::serviceCreateLedgerDimension(DimensionStorage::getDefaultAccountForMainAccountNum('131310'));
journalTable.parmJournalName(ledgerJournalName.JournalName);
journalTable.parmJournalType(ledgerJournalName.JournalType);
journalTable.save();
ttsBegin;
ledgerJournalTable = LedgerJournalTable::findByRecId(journalTable.ledgerJournalTable().RecId, true);
// The name gets reset if no journal number is provided, so we can just update afterwords
ledgerJournalTable.Name = 'My Custom Journal Name/Description';
ledgerJournalTable.update();
ttsCommit;
journalTrans.parmJournalNum(journalTable.ledgerJournalTable().JournalNum);
journalTrans.parmTransDate(today());
journalTrans.parmCurrencyCode('USD');
journalTrans.parmTxt('AlexOnDAX.blogspot.com');
journalTrans.parmDocumentNum('MyDocNumber');
journalTrans.parmDocumentDate(today() - 1);
journalTrans.parmAccountType(LedgerJournalACType::Ledger);
journalTrans.parmLedgerDimension(DimensionAttributeValueCombination::find(ledgerDimension).RecId);
journalTrans.parmAmountCurDebit(100.00);
journalTrans.save();
info("Done");
}
I have a SQL output like
TotalLeave Status
---------- ------
3 PaidLeave
5 MedicalLave
and I need to show this value in my label controls like,
lblMedicalLeave.text = 5
lblPaidLeave.text = 3
for this I just created objects for my dataset in my code like,
StaffAttendanceStatusTableAdapters.StaffTypesTableAdapter staffAttendanceStatus =
new StaffAttendanceStatusTableAdapters.StaffTypesTableAdapter();
StaffAttendanceStatus.StaffTypesDataTable StaffDataTable =
staffAttendanceStatus.GetDataStaffAttendanceStatus(staff.StaffId);
if (StaffDataTable[0] != null)
{
StaffAttendanceStatus.StaffTypesRow StaffRow = StaffDataTable[0];
lblTotalMedicalLeave.Text = StaffRow.TotalLeave.ToString();
lblTotalPaidLeave.Text = StaffRow.TotalLeave.ToString();
}
its showing the same value(3), is it possible to get the TotalLeave value for corresponding Status? can anyone help me here
You are accessing the same row both times. Use StaffDataTable[1] to access the second row. Anyway you should check if there is a result before access any values!
using StaffAttendanceStatusTableAdapters;
....
StaffTypesTableAdapter staffAttendanceStatus = new StaffTypesTableAdapter();
StaffAttendanceStatus.StaffTypesDataTable StaffDataTable =
staffAttendanceStatus.GetDataStaffAttendanceStatus(staff.StaffId);
if (StaffDataTable != null && StaffDataTable.Count > 1)
{
lblTotalMedicalLeave.Text = StaffDataTable[0].TotalLeave.ToString();
lblTotalPaidLeave.Text = StaffDataTable[1].TotalLeave.ToString();
}
hth
Since you need to get TotalLeave from two rows, you need to fetch data from two rows.
if (StaffDataTable != null && StaffDataTable.Rows.Count > 1)
{
StaffAttendanceStatus.StaffTypesRow StaffRow1 = StaffDataTable[0];
StaffAttendanceStatus.StaffTypesRow StaffRow2 = StaffDataTable[1];
lblTotalMedicalLeave.Text = StaffRow1.TotalLeave.ToString();
lblTotalPaidLeave.Text = StaffRow2.TotalLeave.ToString();
}
if there is no order of PaidLeave and MedicalLave status, just check row.Status and assign total value to corresponding label