I'm need of help parsing a custom file structured file. As you can see below is the structure. The issue is that I can't seem to parse the structure correctly, namely myOriginalFormula & myBonusType in the same group when I want them seperated for example.
AttributeDictionary SomeDictName
{
myAttributeDefinitionCategories
{
AttributeDefinitionList SomeList
{
AttributeDefinition SomeDefinitioName < uid=8972789HHDUAI7 >
{
myOriginalFormula "(A_Variable) * 10"
myBonusType FlatValue
}
AttributeDefinition UIBlankAttribute < uid=JIAIODJ7899 >
{
}
AttributeDefinition SomeOtherDefinitionName < uid=17837HHJAJ7788 >
{
myOriginalFormula 1
mySpecializations
{
Specialization "Some_Specialization 1"
{
myCondition "Something.MustEqual = 1"
myFormula 0
}
Specialization "SomeSpecialization 2"
{
myCondition "Something.MustEqual = 2"
myFormula 0.026
}
}
myBonusType FlatValue
}
AttributeDefinition SomeReal_Other_definition < uid=6768GYAG//() >
{
myOriginalFormula "(Some_Formula / Other_Variable) - 1"
myBonusType Percentage
myUINumDecimals 1
myHasAddSignUI FALSE
}
}
}
}
My try is blow. Could someone help me parse this structure correctly?
def syntaxParser():
# constants
left_bracket = Literal("{").suppress()
right_bracket = Literal("}").suppress()
semicolon = Literal(";").suppress()
space = White().suppress()
key = Word(alphanums + '_/"')
value = CharsNotIn("{};,")
# rules
assignment = Group(key + Optional(space + value))
block = Forward()
specialblock = Forward()
subblock = ZeroOrMore(Group(assignment) | specialblock)
specialblock = (
Keyword("Specialization")
+ key
+ left_bracket
+ subblock
+ right_bracket)
block << Group(
Optional(Group(key + Optional(space + value)))
+ left_bracket
+ Group(ZeroOrMore(assignment | Group(block) | Group(specialblock)))
+ right_bracket)
script = block
return script
Your definition of value is too greedy:
value = CharsNotIn("{};,")
I don't know how this works with the format you are parsing, but I get better results with this:
value = quotedString | CharsNotIn("{};,\n")
Related
My goal is to recheck variable coolFeature boolean value from it's else
if (coolFeature) { // want to run this again after value becomes true in else below
$("#Editor").data("kendoWindow").width = '600';
$("#Editor").data("kendoWindow").title("Format Feature - " + Type + ' #' + graphic.attributes.OBJECTID);
$('#ndt').hide();
} else {
$("#Editor").data("kendoWindow").title("Edit Attributes - " + Type + ' #' + graphic.attributes.OBJECTID);
$('#ndt').show();
$("#ndt").click(function() {
$(this).data('clicked', true);
$("#Editor").data("kendoWindow").hide();
coolFeature = "true"; // want to reset to True here, then run the actions under initial if
});
}
I think you need simple recursion, I can't see the entire code so I can't tell exactly.
var myFunction = function(coolFeature) {
if(coolFeature) {
console.log("Cool");
} else {
myFunction(true);
}
};
myFunction(false);
How I can add thousand separators for number input fields in a ModelForm. I am using 'load humanize' and '|intcomma' in templates to format some numbers.but How I could do that for fields in modelforms.
You can do that by setting USE_THOUSAND_SEPARATOR=True as described here.
Actually I think you should try and handle it on the client side with JS. This was also my solution.
This is how I solved the problem:
create general number format JS function:
function number_format (number, decimals, dec_point, thousands_sep) {
number = (number + '').replace(/[^0-9+-Ee.]/g, '');
var n = !isFinite(+number) ? 0 : +number,
prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
s = '',
toFixedFix = function (n, prec) {
var k = Math.pow(10, prec);
return '' + Math.round(n * k) / k;
};
// Fix for IE parseFloat(0.55).toFixed(0) = 0;
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || '';
s[1] += new Array(prec - s[1].length + 1).join('0');
}
return s.join(dec);
}
create thousand separator specific code:
function thousand_sep(tagID, x_value) {
if (x_value == "") {
document.getElementById(tagID).value = "";
return;
}
document.getElementById(tagID).value = number_format(x_value, 0, ',', ' ');
}
Add the code to your ModelForm in your Django forms.py:
class AnyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(AnyForm, self).__init__(*args, **kwargs)
self.fields['numeric_field'].widget.attrs = {
'oninput': "thousand_sep(this.id, this.value)",
}
This works for me. Hope it helps. (sorry for the JS code format, it did not highlight it as code for some reason)
I have this file called ab.exe it contains this in hexadecimal
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000BBAAE8CAFDFFFF83C408000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000054AAE8CAFDFFFF83C40800000000000000000000000000000000000000000000000000000000000000000000000000AAE8CAFDFFFF83C4088D000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
I have this code in c++ that is suppose to detect if a string of hexadecimal is in a file or not and if it is add it to the list box.
array<Byte>^ target1 = { 0xAA,0xE8,0xCA,0xFD,0xFF,0xFF,0x83,0xC4,0x08,0x8D };
array<Byte>^ target2 = { 0x54,0xAA,0xE8,0xCA,0xFD,0xFF,0xFF,0x83,0xC4,0x08 };
array<Byte>^ target3 = { 0xBB,0xAA,0xE8,0xCA,0xFD,0xFF,0xFF,0x83,0xC4,0x08 };
int matched1 = 0;
int matched2 = 0;
int matched3 = 0;
FileStream^ fs2 = gcnew FileStream(line, FileMode::Open, FileAccess::Read, FileShare::ReadWrite);
int value;
do
{
value = fs2->ReadByte();
if (value == target1[matched1]) {
matched1++;
}
else
matched1 = 0;
if (value == target2[matched2]) {
matched2++;
}
else
matched2 = 0;
if (value == target3[matched3]) {
matched3++;
}
else
matched3 = 0;
if(matched1 == target1->Length)
{
listBox1->Items->Add(line + "1");
}
if(matched2 == target2->Length)
{
listBox1->Items->Add(line + "2");
}
if(matched3 == target3->Length)
{
listBox1->Items->Add(line + "3");
}
} while (value != -1);
fs2->Close();
the problem is that it only adds line + 3 to the list box and not line + 1 or line + 2 to the list box
I do not know why that is because all 3 of the strings are in the file so they all should be added to the list box. for some reason only the last one is being added because I tried just having 2 and the second one got added.can someone show me why they are not all being added to the list box.
thanks
Update1
after playing around with it some more it is not the last target that gets added each time, It is the first string that appears in the file that gets added. I stepped through the program using message boxes and what is happening is lets say 54AAE8CAFDFFFF83C408 is the first string to appear in the file then line + 2 will be added, but then for some reason the matched integer for all 3 stop counting they just = 0 the rest of the file. can someone explain to me why that is and how to fix it.
Update2
here is the answer to the problem. all I needed to do was just add a matched = 0; after each add to list box command.
listBox1->Items->Add(line + "1");
matched1 = 0;
listBox1->Items->Add(line + "2");
matched2 = 0;
listBox1->Items->Add(line + "3");
matched3 = 0;
It seems to me that after the first matching of one pattern (here target3) you read beyond last byte of target3 (because of matched3++), this may cause undesired behavior.
Update1:
if(matched1 == target1->Length)
{
matched1 = 0; // pattern matched so reset counter
...
}
Having trouble with a list function I wrote using CouchApp to take items from a view that are name, followed by a hash list of id and a value to create a CSV file for the user.
function(head, req) {
// set headers
start({ "headers": { "Content-Type": "text/csv" }});
// set arrays
var snps = {};
var test = {};
var inds = [];
// get data to associative array
while(row = getRow()) {
for (var i in row.value) {
// add individual to list
if (!test[i]) {
test[i] = 1;
inds.push(i);
}
// add to snps hash
if (snps[row.key]) {
if (snps[row.key][i]) {
// multiple call
} else {
snps[row.key][i] = row.value[i];
}
} else {
snps[row.key] = {};
snps[row.key][i] = row.value[i];
}
//send(row.key+" => "+i+" => "+snps[row.key][i]+'\n');
}
}
// if there are individuals to write
if (inds.length > 0) {
// sort keys in array
inds.sort();
// print header if first
var header = "variant,"+inds.join(",")+"\n";
send(header);
// for each SNP requested
for (var j in snps) {
// build row
var row = j;
for (var k in inds) {
// if snp[rs_num][individual] is set, add to row string
// else add ?
if (snps[j][inds[k]]) {
row = row+","+snps[j][inds[k]];
} else {
row = row+",?";
}
}
// send row
send(row+'\n');
}
} else {
send('No results found.');
}
}
If I request _list/mylist/myview (where mylist is the list function above and the view returns as described above) with ?key="something" or ?keys=["something", "another] then it works, but remove the query string and I get the error below:
{"code":500,"error":"render_error","reason":"function raised error: (new SyntaxError(\"JSON.parse\", \"/usr/local/share/couchdb/server/main.js\", 865)) \nstacktrace: getRow()#/usr/local/share/couchdb/server/main.js:865\n([object Object],[object Object])#:14\nrunList(function (head, req) {var snps = {};var test = {};var inds = [];while ((row = getRow())) {for (var i in row.value) {if (!test[i]) {test[i] = 1;inds.push(i);}if (snps[row.key]) {if (snps[row.key][i]) {} else {snps[row.key][i] = row.value[i];}} else {snps[row.key] = {};snps[row.key][i] = row.value[i];}}}if (inds.length > 0) {inds.sort();var header = \"variant,\" + inds.join(\",\") + \"\\n\";send(header);for (var j in snps) {var row = j;for (var k in inds) {if (snps[j][inds[k]]) {row = row + \",\" + snps[j][inds[k]];} else {row = row + \",?\";}}send(row + \"\\n\");}} else {send(\"No results found.\");}},[object Object],[object Array])#/usr/local/share/couchdb/server/main.js:979\n(function (head, req) {var snps = {};var test = {};var inds = [];while ((row = getRow())) {for (var i in row.value) {if (!test[i]) {test[i] = 1;inds.push(i);}if (snps[row.key]) {if (snps[row.key][i]) {} else {snps[row.key][i] = row.value[i];}} else {snps[row.key] = {};snps[row.key][i] = row.value[i];}}}if (inds.length > 0) {inds.sort();var header = \"variant,\" + inds.join(\",\") + \"\\n\";send(header);for (var j in snps) {var row = j;for (var k in inds) {if (snps[j][inds[k]]) {row = row + \",\" + snps[j][inds[k]];} else {row = row + \",?\";}}send(row + \"\\n\");}} else {send(\"No results found.\");}},[object Object],[object Array])#/usr/local/share/couchdb/server/main.js:1024\n(\"_design/kbio\",[object Array],[object Array])#/usr/local/share/couchdb/server/main.js:1492\n()#/usr/local/share/couchdb/server/main.js:1535\n#/usr/local/share/couchdb/server/main.js:1546\n"}
Can't say for sure since you gave little detail, however, a probable source of problems, is the use of arrays to collect data from every row: it consumes an unpredictable amount of memory. This may explain why it works when you query for a few records, and fails when you query for all records.
You should try to arrange data in a way that eliminates the need to collect all values before sending output to the client. And keep in mind that while map and reduce results are saved on disk, list functions are executed on every single query. If you don't keep list function fast and lean, you'll have problems.
I am asking for advice and opition as of the code to use with groovy templates.
All template examples on the web used a very limited logic but I simply cannot overcome that barrier and the code in my template is substantial.
Is this acceptable? What could be a better way to do this?
Thanks
Peter
The task is to generate TCL type code - specifically if then/elsif/else type contraint
if { [streq $pm_enrichment('a1') "'aaaa2'"] && [strlen $pm_enrichment('aaaa3')] &&\
[strlen $pm_enrichment('aaaa4') ] } {
set pm_enrichment('ResultAAA') 0
}
elseif { [streq $pm_enrichment('b1') "'bb2'"] && [strlen $pm_enrichment('bbb3')] &&\
[strlen $pm_enrichment('bbbb4') ] } {
set pm_enrichment('ResultBBB') 1
}
else { [streq $pm_enrichment('c1') "'cc2'"] && [strlen $pm_enrichment('ccc3')] &&\
[strlen $pm_enrichment('cccc4') ] } {
set pm_enrichment('ResultCCC') 2G
}
//////////////////////////////////////
def dataCasesClosure= {->
pos=0
arrSorted = []
mapStmt.each{arrSorted.add(it.key) }
arrSorted = arrSorted.sort()
outStr=''''''
arrSorted.each { i ->
tmpStatement = statement
tmpResultStmt = resultStmt
list=mapStmt[i]
resultList=mapResultStmt[i]
pos=0
int index = tmpStatement.indexOf(keyword);
while (index >=0){
val = list[pos].replaceAll(~'"','')
pos +=1
tmpStatement=tmpStatement.replaceFirst( ~/#/,/${val}/)
index = tmpStatement.indexOf(keyword, index+keyword.length()) ;
}
if (tmpStatement ==~/\W+$/) {
tmpStatement=tmpStatement[0..-2]
}
pos=0
index = tmpResultStmt.indexOf(keyword);
while (index >=0){
val = resultList[pos]
pos +=1
tmpResultStmt=tmpResultStmt.replaceFirst( ~/#/,/${val}/)
index = tmpResultStmt.indexOf(keyword, index+keyword.length()) ;
}
if (i==0) {
outStr= "if {${tmpStatement} } { \n\t\t ${tmpResultStmt} \n }"
} else if (i < arrSorted.size()-1 ){
outStr += "elseif {${tmpStatement} } { \n\t\t ${tmpResultStmt} \n }"
} else {
outStr += "else {${tmpStatement} } { \n\t\t ${tmpResultStmt} \n }"
}
}
outStr
} // ### dataCasesClosure
def valuesIfThenStmt= [
"statement":dataCasesClosure
]
tplIfThenStmt = '''
##############################
${statement}
'''
def engine = new SimpleTemplateEngine()
templateResult = engine.createTemplate(tplIfThenStmt).make(valuesIfThenStmt)
println templateResult.toString()
If this is all you have to generate, the template is overkill. You could have just called the dataCasesClosure directly to get its output.
Assuming it is part of a larger template then, I think it is very reasonable to use closures to produce output for a particularly complex parts, just as you have done. I have personally done this on an extreme scale with good results.