Indentation based syntax -> AST [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
Let's say i'd like to re-invent CoffeeScript :) Or Python. Or Stylus, or YAML :)
I need some tool, which will turn my indentation-base syntax into abstract syntax tree. Google unfortunately knowns nothing about [indentation-based sytntax to AST]. Do you guys know any tool like this?
To be more specific, what I have
===source===
Lorem ipsum:
dolor sit amet:
consectetuer adipiscing elit
sed diam nonummy
nibh euismod tincidunt:
ut laoreet dolore
...and what I need:
===result===
[
{
directive: "Lorem ipsum",
content: [
{
directive: "dolor sit amet",
content: [
{directive: "consectetuer adipiscing elit", content: []}
]
},
{directive: "sed diam nonummy", content: []}
]
}, {
directive: "nibh euismod tincidunt",
content: [
{directive:"ut laoreet dolore", content: []}
]
}
]
It would be great, if you could recommend some tool like this. It would be awesome if this tool is written on python/javascript and display result as JSON.
It would be also cool if you can give a piece of advice about how to create this tool-of-a-dream by myself :)
Thanx!

It's simple enough to write this yourself using recursion. Here is one that creates a list -- I'll leave the dict version as an exercise for you.
import sys
import re
def DentArthurDent(fp, dents = 0, nextline = None):
'''Read from FP until EOF or an exdent
Return dict and next line'''
tree = []
while True:
line, nextline = nextline or fp.readline(), None
if not line:
return tree, ''
parts = re.match(r'(^ *)(.*)', line).group(1,2)
dent = len(parts[0])
if dent == dents:
tree.append(parts[1])
elif dent > dents:
child_tree, nextline = DentArthurDent(fp, dent, line)
tree.append(child_tree)
else:
return tree,line
import json
tree, _ = DentArthurDent(sys.stdin)
print json.dumps(tree, indent=4)
This input:
line 1
line 2
line 3
line 4
line 5
line 6
yields this output:
[
"line 1",
"line 2",
[
"line 3",
[
"line 4",
"line 5"
],
"line 6"
]
]

Related

Mongoose partial text search with sorting by revelance

I'm trying to query my mongodb database via mongoose, sorting the most relevant items first.
The following code works, but only returns results that contain the search parameter as a full word.
E.g. example will return items that include fields such as, ⁣ but{name: "example-item", description: "this is an example description"} but examp won't return that same item. I'd also like for it to search across multiple fields, as my current code does.
I'm aware you can do this partial search using regex but then you're not able to sort by textScore. Is there any way to do both? Sorting after each request is not possible as it will be paginated and handling somewhat large data.
let searchValue = "examp";
let matchingItems = await Items.find(
{
$text: {
$search: searchValue,
}
},
{
score: {
$meta: "textScore"
}
},
{
sort: {
score: {
$meta: "textScore"
}
}
}
);
Example DB data:
[
{name: "dignissim", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit."},
{name: "Fusce eget.", description: "Nullam malesuada ex sit amet diam ultrices"},
{name: "Duis nec", description: "Proin at dolor at est porta aliquet. Proin viverra imperdiet orci, a ornare tortor"},
{name: "Mauris.", description: "Aenean tristique ante et eros porttitor, ut sodales ipsum pulvinar."},
{name: "Pellentesque", description: "Nam dignissim ipsum a elit fermentum"},
{name: "facilisis augue", description: "Etiam sit amet dolor sed sapien rutrum sodales."},
{name: "erat suscipit", description: "this is an example description"},
]
My schema is defined as below:
const mongoose = require("mongoose");
const schema = new mongoose.Schema({
name: String,
description: String
});
schema.index({ name: "text", description: "text" });
const Items = mongoose.model("Item", schema);

filter data on multiple fields

I am trying to build a filter for JSON object at the moment, the json object looks like this,
created_at: null
deleted_at: null
id: 3
listings: Array(3)
0: {id: 3, name: "Learn the basics of the guitar from the anatomy of the guitar to scales, chords", slug: "learn-the-basics-of-the-guitar-from-the-anatomy-of-the-guitar-to-scales-chords", description: "We live in a unique and wonderful time where elect… going to give you a lifetime of awesome rockin’.", booking_details: "undefined", …}
1: {id: 8, name: "Advanced guitar skills with William Topa", slug: "advanced-guitar-skills-with-william-topa", description: "We live in a unique and wonderful time where elect… going to give you a lifetime of awesome rockin’.", booking_details: "Lorem ipsum dolor sit amet, consectetur adipiscing… laboris nisi ut aliquip ex ea commodo consequat.", …}
2: {id: 9, name: "Music production simplified", slug: "music-production-simplified", description: "We live in a unique and wonderful time where elect… going to give you a lifetime of awesome rockin’.", booking_details: "Lorem ipsum dolor sit amet, consectetur adipiscing… laboris nisi ut aliquip ex ea commodo consequat.", …}
length: 3
__proto__: Array(0)
tag: "Music"
updated_at: null
weight: null
This is part of a bigger object, the hierarchy looks like
[{ data, listings }, {data, listings}]
What I am wanting to do, is filter through the listings array and hide any listings that don't have a cost of "0.00"
Here is what i am trying,
<input type="checkbox" v-model="priceFilter" value="0.00" />
data() {
return {
this.priceFilter: []
}
},
computed: {
filteredTags() {
return this.tags.filter(tag => {
tag.listings.filter(listing => "0.00" === listing.cost);
//console.log(this.checkedPrice, listing.cost);
});
},
},
In the above I just trying to return the listings where the cost matches 0.00 with trigger it via the checkbox being checked but even that does not filter as I wish I still see all listings.
Anyone care to offer any advice?

How to pop and unshift elements from an array in object?

I have an object. And I have a scenario that what do I want to do with it.
Scenario :
All arrays and features were added in objeTest. After that I will call it, I want to remove 'Wednesday' value from default index. And I want to place all 'Wednesdays' in sequence from the first index.
*The following getted error :
Uncaught TypeError: Cannot read property 'day' of undefined*
The following is an example for my issue. You could try and will see error message from console.
I didn't find any solution, I need your advise and solution.
Code :
var objeTest = {
name : 'objeTest',
langs : {
0 : 'EN',
1 : 'VI',
2 : 'RU',
3 : 'AR'
},
commentGeneral : 'testComment'
};
var date = [{
day : 'Sunday',
month : 'July',
comment : ''
},
{
day : 'Wednesday',
month : 'June',
comment : 'lorem ipsum dolor sit amet consectetur adipiscing elit'
},
{
day : 'Wednesday',
month : 'June',
comment : 'lorem ipsum dolor sit amet consectetur adipiscing elit'
},
{
day : 'Friday',
month : 'February',
comment : 'lorem ipsum dolor sit amet consectetur adipiscing elit'
}];
/**
* I don't want to remove that using the array adding
* in the object process ( objeTest.dates = date.filter(...)etc).
*/
objeTest.dates = date; // You couldn't change from adding process. I don't need this solution from here.
// If you couldn't understand, please read again scenario. Thanks for your interesting.
var myObjLeng = objeTest.dates.length;
console.log(objeTest);
for(var i = 0; i < myObjLeng; i++) {
if(objeTest.dates[i].day == 'Wednesday') {
objeTest.dates[i].pop();
objeTest.dates[i].unshift();
}
};
console.log(objeTest);
So the new dates of the object I want to get should look like this in the object:
[
{
day : 'Wednesday',
month : 'June',
comment : 'lorem ipsum dolor sit amet consectetur adipiscing elit'
},
{
day : 'Wednesday',
month : 'August',
comment : 'lorem ipsum dolor sit amet consectetur adipiscing elit'
},
{
day : 'Sunday',
month : 'July',
comment : ''
},
{
day : 'Friday',
month : 'February',
comment : 'lorem ipsum dolor sit amet consectetur adipiscing elit'
}];
Try a sort.
objeTest.dates.sort((entryA, entryB) => {
return (entryB.day === 'Wednesday') - (entryA.day === 'Wednesday')
});
If you need to separate the array the easiest way is to forget about the original one and then set it again.
not_wednesdays = [];
wednesdays = [];
objeTest.dates.forEach(date=>{
if (date.day=="Wednesday") {
wednesdays.push(date);
}
else {
not_wednesdays.push(date);
}
});
objeTest.dates = not_wednesdays;

Angular repeating images

New to angular and developing a simple page just to learn the inner workings. What I have is a div that display name price and description along with a button and a full image. What I'm trying to do is underneath that full image display 2-3 additional images. The problem is the same full image is displaying again and none of the additional images are displaying.
Here is the angular
(function () {
var app = angular.module('gemStore', []);
app.controller('StoreController', function () {
this.products = gems;
});
var gems = [
{
name: 'Defmei',
price: 2.95,
description: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. ',
canPurchase: true,
soldOut: false,
images: [
{
image: "Images/image1.jpg",
image: "Images/image2.jpg",
image: "Images/image3.jpg"
}
]
},
{
name: 'Sijoi',
price: 5.95,
description: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. ',
canPurchase: true,
soldOut: true,
images: [
{
image: "Images/image4.jpg",
image: "Images/image3.jpg",
image: "Images/image2.jpg"
}
]
}
]
})();
Here is the HTML
<body data-ng-controller="StoreController as store" >
<div class="display" data-ng-repeat="product in store.products">
<h1>{{product.name}}</h1>
<h2>{{product.price | currency}}</h2>
<p> {{product.description}} </p>
<img class="imageStyles" data-ng-src="{{product.images[0].image}}"/>
<br />
<div data-ng-repeat="image in product.images">
<img data-ng-src="{{image.image}}" class="thumbs" />
</div>
<button data-ng-show="product.canPurchase">Add to cart</button>
</div>
</body>
That image object seems "broken", you're practically redefining the image attribute 3 times.
In javascript, objects have a syntax like { attribName1: attValue1, attribName2: attValue2 ...}
What you're creating here:
images: [
{
image: "Images/image1.jpg",
image: "Images/image2.jpg",
image: "Images/image3.jpg"
}
]
Is an array with 1 item, which is an object, with 1 property, "image", with a value of... "Images/image3.jpg" maybe (or whatever, I wouldn't be surprised if double-defining attributes like this was in fact undefined behaviour).
What you probably want instead is either an array with 3 elements, or an object with 3 distinct attributes, ie:
images: [
{
"image1": "Images/image1.jpg",
"image2": "Images/image2.jpg",
"image3": "Images/image3.jpg"
}
]
You can iterate through array members and object attributes too with ng-repeat, but you have to change your code accordingly.
Your images array only has one item in it with image defined three times. Change it like the following so that there are three separate items and it should work.
images: [
{image: "Images/image4.jpg"},
{image: "Images/image3.jpg"},
{image: "Images/image2.jpg"}
]

for loop in fancybox given syntax error

function imgshow(val2){
var arrayVal2 = val2.split(',');
$.fancybox([
for (i=0; i<arrayVal2.length; i++){
'uploads/'+arrayVal2[i],
//'http://farm3.static.flickr.com/2687/4220681515_cc4f42d6b9.jpg',
{
'href' : 'uploads/'+arrayVal2[i],
'title' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit'
}
}
], {
'padding' : 0,
'transitionIn' : 'none',
'transitionOut' : 'none',
'type' : 'image',
'changeFade' : 0
});
}
can i give for loop there. there is syntax error where i place for loop
i have images name in database. explode tham and store in a array. and call a for loop to show all images,
but given syntax error
please Guide me
This is not valid javascript
[for (;;) {}]
But you could do this
[
(function() {
var val = [];
for (i=0; i<arrayVal2.length; i++){
val.push(['uploads/'+arrayVal2[i],
//'http://farm3.static.flickr.com/2687/4220681515_cc4f42d6b9.jpg',
{
'href' : 'uploads/'+arrayVal2[i],
'title' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit'
}]);
}
return val;
)()
]
Though it's not pretty. I would recommend refactoring that section.

Categories