What are your favorite skeleton files for the various languages? [closed] - ide

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
It is useful to have skeleton or template files that you can just copy and use as a basis for a new script or app.
For example, I use the following ones (emacs with the auto-insert module automatically opens a copy of the appropriate skeleton file when I create a new file).
Perl:
#!/usr/bin/perl -w
use strict;
use Getopt::Long;
my $verbose = 1;
GetOptions("verbose!" => \$verbose
) or die("options error");
C++:
#include <iostream>
#include <stdexcept>
int main(int argc, char** argv){
try{
}
catch(std::exception& e){
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Arguably, one could include basic code for boost::program_options etc.
What are your favorite skeleton files?

The only skeleton file I have is for LaTeX.
\documentclass{article}
%\documentclass[11pt]{amsart}
\usepackage[dvips]{graphicx}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage{cancel}
\oddsidemargin0cm
\topmargin-1cm
\textwidth16.5cm
\textheight23.5cm
\parskip1ex
\parindent0ex
\begin{document}
\title{ ... }
\author{ ... }
\date{ ... }
\maketitle
\end{document}
Obviously I use this for writing math papers.
Otherwise, I always start from scratch. There's no programming language I can think of where the requisite infrastructure is more than you can keep around in your brain or take longer than 20 seconds to type out.

My Perl templates look like this:
If I am opening a .pm module:
use MooseX::Declare;
class What::Ever {
};
1;
Or, if not on a MooseX::Declare project:
package What::Ever;
use Moose;
1;
If it's a .pl file:
#!/usr/bin/env perl
use strict;
use warnings;
use feature ':5.10';
Since I use autoinsert.el, I also have it ask me if I want to use FindBin; if so:
#!/usr/bin/env perl
use strict;
use warnings;
use feature ':5.10';
use FindBin qw($Bin);
use lib "$Bin/../lib";
The necessary emacs code is in my elisp repository at http://github.com/jrockway/elisp/blob/fd5d73530a117a13ddcde92bc1c22aba1bfde1f0/_local/auto-inserts.el.
Finally, I think you will prefer MooseX::Getopt to plain Getopt. It is a much more maintainable approach to writing "one-off" scripts. (The next few lines go something like:
use My::Script; # that's why we did the "use lib" thing
My::Script->new_with_options->run; # this parses the command line, creates a new object, and runs the script
All the important code goes in a class that can be unit tested, glued to a web app, etc.)

In visual studio, they're called Project files; my current favorite is Windows Application ;-)

Java
package edu.vt;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class Template
{
private Log log = LogFactory.getLog(getClass());
/* Constructors
***************************************************************************/
public Template()
{
}
/* Accessors/Mutators
***************************************************************************/
/* Local Methods
***************************************************************************/
}
and
package testing.edu.vt;
import edu.vt.Template;
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class TemplateTestCase extends TestCase
{
private final Log log = LogFactory.getLog(getClass());
public TemplateTestCase(final String name)
{
super(name);
}
protected void setUp()
{
}
protected void tearDown()
{
}
public void testLifeCycle() throws Exception
{
assertTrue(true);
}
}

Python is simple, but it still helps if you import things with shortcut names, for example:
import sys
import numpy as np
import pylab as pyb
import matplotlib.pyplot as plt
import matplotlib as mpl
But just don't do: import skynet.

Bourne Shell
#!/bin/sh
usage() {
cat <<EOF
$0 <cmd>
cmd:
samplecmd
EOF
}
cmd=${1}
shift
case ${cmd} in
samplecmd)
arg1=${arg1:-${1}} # arg list takes precedence over env var
if [ "x${arg1}" = "x" ] ; then
usage
fi
samplecmd ${arg1}
;;
*)
usage
;;
esac
I like to make little helper scripts like this to document commands I type in the shell.

When I'm writing code that will be OSS I have a simple boiler plate template that I can key in the license and URL to the license text. The boiler plate has author details, and other crap hard coded.
For commercial dev I have a boiler plate with company information, and standard copyright notices in it.
I don't keep any standard skeletons because I've found I just cut out the content and added my own anyway. Most cases are different enough that changing the skeleton to match takes as long as bashing it out by hand.

Related

Can not resolve JavaParser

JavaParser.CallContext and JavaParser.FunctionDeclContext do not seem to be able to resolve. This is modeled after page 139 in the definitive antlr reference.
Am I missing a Lib?
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.misc.MultiMap;
import org.antlr.v4.runtime.misc.OrderedHashSet;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.*;
import org.stringtemplate.v4.ST;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Set;
static class FunctionListener extends JavaBaseListener {
Graph graph = new Graph();
String currentFunctionName = null;
public void enterFunctionDecl(JavaParser.FunctionDeclContext ctx) {
currentFunctionName = ctx.ID().getText();
graph.nodes.add(currentFunctionName);
}
public void exitCall(JavaParser.CallContext ctx) {
String funcName = ctx.ID().getText();
// map current function to the callee
graph.edge(currentFunctionName, funcName);
}
}
I think I have seen this one, and I dont have enough points to "comment", but let me ask a question first; It looks like you are trying to produce an external version of the AST on page 137, You took the examples and renamed them to the grammar you had generated already. I'm going to assume that the rest of it is working or you would have had a lot more errors than this one ! Is that the goal ? Are you after just the calling methods/classes or are you after the full homogeneous AST ?
This depends on the grammar entry points. That's not as obvious in the book as it seems. You referenced functionDecl, which looks to be an entry in the Cymbol.g4, but doesn't exist in Java.g4 So rather than JavaParser.FunctionDeclContext I suggest JavaParser.classOrInterfaceDeclarationContext. It should should pull up the right method. I will also confess that I don't know what the exitCall would map to. I could use the illumination on that myself.
Were you after the whole AST or only the call graph ? If the whole AST, I think you can use enterEveryRule or ExitEveryRule for that as well, but confirmation would be good.
So start by regenerating your grammar, change your program to reference the rule entry point in the .g4 files, then see if it all works.
Thanks

import cycle in golang with test packages

I am trying to refactor some test code and in two packages I need to do the same thing (connect to a DB). I am getting an import cycle. I get why I can't do it, but am wondering what the best way around it is.
Some specifics, I have three packages: testutils, client, engine.
In engine I define an interface & implementation (both exported).
package engine
type interface QueryEngine {
// ...
}
type struct MagicEngine {
// ...
}
And then in the testutils package I will create a MagicEngine and try and return it.
package testutils
func CreateAndConnect() (*engine.MagicEngine, error) {
// ....
}
Now in the test code (using a TestMain) I need to do something like
package engine
func TestMain(m *testing.M) {
e, err := testutils.CreateAndConnect()
// ....
os.Exit(m.Run())
}
This is of course a cycle. I want to do this so that I can in the client package also use this testutils.CreateAndConnect() method. I don't want to repeat the code in both packages. I don't want it in the main code of the engine package, it is very specific to the tests.
I tried adding it as an exported method on the engine test class (engine/engine_test.go) and using it in the client/client_test.go. No dice. :/
I feel I have done this in other languages, but could be crazy. What is the best way to structure this code for reusability?
You could use black-box style testing because the components of engine are exported. Change your tests to be in package engine_test:
package engine_test
import "engine"
import "testutils"
func TestMain(m *testing.M) {
e, err := testutils.CreateAndConnect()
// ....
os.Exit(m.Run())
}

How to include code excerpts using tags in asciidoc?

I can include the full Greet.java file
public class Greet {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
from within the asciidoc file
== Hello Java
This is how one greets in Java:
[source,java]
.Greet.java
----
include::Greet.java
----
producing the documentation
But suppose that I only want to include an excerpt from the code delimited by tags. In the code above, suppose I only want to include the main function.
I don't see symbolic tags in the documentation, but this page suggests that it's sufficient to write
public class Greet {
// tag::helloMethod[]
public static void main(String[] args) {
System.out.println("Hello World!");
}
// end::helloMethod[]
}
and
== Hello Java
This is how one greets in Java:
[source,java]
.Greet.java
----
include::Greet.java[tags=helloMethod]
----
That just produces:
Can you suggest a method that would include just the excerpt? I'm using asciidoc 8.6.9.
What you're doing should work fine in Asciidoctor (the Ruby implementation of AsciiDoc), but not AsciiDoc (the Python implementation).
Notice though the different mechanism for obtaining syntax highlighting.
To get syntax highlighting with asciidoc one uses a command-line switch asciidoc -a source-highlighter=pygments file.adoc.
No command-line switch is needed (or possible) with Asciidoctor. With AsciiDoctor syntax highlighting is obtained by:
Inserting :source-highlighter: pygments at the top of each source file, and
Running sudo gem install pygments.rb to install pygments.
The Asciidoctor tags option can include multiple tags as well;
[tags="tag 1, tag 2, …"]
Bringing in more code excerpts in one go…

How to create a Dynamic Library in D?

I want to create a Dynamic library (cross-platform) in D, so I did some Googling. After some time I found this page. I am absolutely stunned by how much complexities there are in writing, compiling and even linking to a DLL. Isn't there a uniform way of creating a shared library like you would in C? (just leave out the main function and pass some flags to the linker)
Well, I decided to spend some time today messing with this and I kinda sorta have something that works, at least if the main program is also written in D (on Linux, I think it will work from C too on Windows. The reason is I didn't link to phobos in the .so in the D one, so it relies upon the exe for those symbols. I think, tbh I don't know exactly what is going on here, maybe it would work better if I used the shared phobos lib too)
Anyway, first, let's throw some code down.
This is testdll.d and it builds our dll
module testdll;
import std.stdio;
extern(C)
export void lol() {
import core.stdc.stdio;
printf("hello from C\n");
writeln("hello!");
}
version(Windows)
extern(Windows) bool DllMain(void* hInstance, uint ulReason, void*) {
import std.c.windows.windows;
import core.sys.windows.dll;
switch (ulReason)
{
default: assert(0);
case DLL_PROCESS_ATTACH:
dll_process_attach( hInstance, true );
break;
case DLL_PROCESS_DETACH:
dll_process_detach( hInstance, true );
break;
case DLL_THREAD_ATTACH:
dll_thread_attach( true, true );
break;
case DLL_THREAD_DETACH:
dll_thread_detach( true, true );
break;
}
return true;
}
You'll notice most that code is the WinMain which just calls druntime functions. I think that main should be available at least as a mixin, or maybe even fully automatic, since it is pure boilerplate.
And the client code:
import core.runtime;
alias extern(C) void function() functype;
version(Posix) {
extern(C) void* dlsym(void*, const char*);
extern(C) void* dlopen(const char*, int);
extern(C) char* dlerror();
pragma(lib, "dl");
} else version(Windows) {
extern(Windows) void* LoadLibraryA(const char* filename);
extern(Windows) void* GetProcAddress(void*, const char*);
}
void main() {
version(Posix) {
auto thing = dlopen("./testdll.so", 2);
if(thing is null) {
import std.conv;
import std.stdio;
writeln(to!string(dlerror()));
return;
}
auto proc = cast(functype) dlsym(thing, "lol");
} else version(Windows) {
auto thing = LoadLibraryA("testdll.dll");
assert(thing !is null);
auto proc = cast(functype) GetProcAddress(thing, "lol");
}
assert(proc !is null);
//import std.stdio; writeln("calling proc");
proc();
}
This has different code for Windows and Linux, though it is pretty similar. The druntime stuff is supposed to start taking care of this soon as we mentioned in the comments.
The compile commands aren't too bad but a little weird. Linux first:
dmd -fPIC -shared testdll.d -defaultlib= # builds the dll
PIC and shared tell it to build the .so. I did the blank defaultlib because without it, loading the dll at runtime failed with "symbol already defined" errors.
Building the client is straightforward:
dmd testdllc.d
Note that there's the pragma(lib) in the file that links with the -ldl option automatically. Run it and get some hello! BTW be sure both are in the same directory since this loads ./ in the loader.
Now, let's build on Windows.
dmd -oftestdll.dll -shared testdll.d testdll.def
Tell it to output our dll, use -shared so it knows, and then the other thing is the def file, like described here http://dlang.org/dll.html/dllmain
These are the contents of that file:
LIBRARY testdll
EXETYPE NT
CODE SHARED EXECUTE
DATA WRITE
EXPORTS
lol
If you don't use the .def file, the dll will build successfully, but the procedure won't be found because it isn't exported. (I think the export keyword in D should be able to do this automatically, bypassing hte .def file, and I believe there's a discussion on doing this, but right now it is required as far as I know.)
And the client is similarly easy:
dmd testdllc.d
Run it and get some hellos, if all goes well.
Now, why did I do the functype alias in the client? Easier than doing the other casting and such, and it makes it nicely extern(C).
Why is the lol function extern(C) in the first place? Just so it has an easier name to use in GetProcAddress/dlsym. Could have also pragma(mangle) or did .mangleof with an import thing. All kinds of options there, fairly straightforward, I just wanted to keep it simple to make the test easier to focus on. "lol" is a simpler name than "_D7testdll3lolFZv" or whatever the mangled name would be.... (OMG I mangled it correctly by hand! Sometimes I think I write too much D lol) and yeah that works too it is just harder to do by eyeball. Note: on Windows, the .def file might have to leave off the leading underscore if you do it that way.
anyway, yeah, this made a working dll/so for me and a program to load and use it successfully. Not as pretty as it could/should be, but it works. For me at least.

How to add comments to fenced code block within doxygen documentation

I am using fenced code blocks in Doxygen using the markdown syntax. This makes it easy to add a simple code example, like this:
~~~~~{.cpp}
void doSomething()
{
}
~~~~~
When I try to add comments into the fenced code block using two forward slashes, Doxygen seems to remove the slashes. So when I write this:
~~~~~{.cpp}
void doSomething()
{
// This function should do something
}
~~~~~
I get this output:
void doSomething()
{
This function should do something
}
How can I tell Doxygen to keep the comments in the fenced code block?
EDIT:
The complete file looks like this (we use the standard Doxygen extension of .dox for documentation-only files):
/*!
\page PATTERN_SAMPLE Sample
~~~~~{.cpp}
void doSomething()
{
// This function should do something
}
~~~~~
*/
The result looks like this:
Try with \code
\code{.cpp}
class Cpp {};
\endcode
I encountered the same issue. No need to change code format. You can specify STRIP_CODE_COMMENTS as NO: this setting outputs the source code with the comment.
# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any
# special comment blocks from generated source code fragments. Normal, C++ and
# Fortran comments will always remain visible.
# The default value is: YES.
STRIP_CODE_COMMENTS = NO