Skip to content

Instantly share code, notes, and snippets.

@nathanathan

nathanathan/README.md

Last active Dec 11, 2015
Embed
What would you like to do?
A version of the howdoi code search tool that runs in a webpage.
howdoi.js
---------
[Based on the shell script here.](https://github.com/gleitz/howdoi)
YQL is used for getting search results.
Stack overflow has an excellent api that provides the answer bodies.
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<base target="_blank" />
<style>
.code {
background-color: lightgray;
}
.fa-link {
float:right;
}
</style>
</head>
<body>
<div id="results"></div>
<form action="#">
<label>howdoi</label>
<input name="q">
<button>submit</button>
</form>
<p>Based on the howdoi script <a href="https://github.com/gleitz/howdoi">here</a></p>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="//raw.github.com/allmarkedup/jQuery-URL-Parser/master/purl.js"></script>
<script>
$(function(){
var query = $.url().param('q');
if(!query){
$('#results').text("No query string in url");
return;
}
var qRegex = new RegExp("(howdoi)?(.*)");
query = qRegex.exec(query).pop();
if(query.trim().length === 0){
$('#results').text("Query string is empty.");
return;
}
function scrapeCodeFromUrl(url) {
var matchObj = url.match(new RegExp("questions/([0-9]+)/"));
if(!matchObj || matchObj.length === 0){
console.error("Could not parse url: " + url);
return;
}
var id = matchObj.pop();
$.ajax({
type: "get",
url: "//api.stackexchange.com/2.1/questions/" + id + "/answers",
dataType: "json",
data: {
site: "stackoverflow",
filter: "withbody"
},
success: function(res) {
var $result = $('<div class="result">');
var $code = $('<code>');
var answer = res.items[0];
$result.append($('<a class="fa-link">Full answer</a>').attr('href', url));
$result.append($('<pre class="code">').append($(answer.body).find("code")));
$('#results').append($result);
}
});
}
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql/",
dataType: "json",
data: {
"q": "select * from google.search where q = \"site:stackoverflow.com/questions " + query + "\"",
"format": "json",
"env": "store://datatables.org/alltableswithkeys"
},
success: function(res) {
if(!res.query || res.query.count === 0) {
$('#results').text("No search results.");
return;
}
//TODO: To limit requests I could collect multiple ids from search results
//before going to SO
res.query.results.results.slice(0,3).forEach(function(result){
scrapeCodeFromUrl(result.url);
});
}
});
});
</script>
{
"category": "main",
"components": [
"howdoi ", {"regex":".+", "tag" : "query"}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment