text:
.class final Landroid/os/DropBoxManager$Entry$1;
.super Ljava/lang/Object;
.source "DropBoxManager.java"

# interfaces
.implements Landroid/os/Parcelable$Creator;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/os/DropBoxManager$Entry;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

# direct methods
.method constructor <init>()V
    .registers 1

    .prologue
    .line 219
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public createFromParcel(Landroid/os/Parcel;)Landroid/os/DropBoxManager$Entry;
    .registers 8
    .param p1, "in"    # Landroid/os/Parcel;

    .prologue
    .line 222
    invoke-virtual {p1}, Landroid/os/Parcel;->readString()Ljava/lang/String;

    move-result-object v1

    .line 223
    .local v1, "tag":Ljava/lang/String;
    invoke-virtual {p1}, Landroid/os/Parcel;->readLong()J

    move-result-wide v2

    .line 224
    .local v2, "millis":J
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v5

    .line 225
    .local v5, "flags":I
    and-int/lit8 v0, v5, 0x8

    if-eqz v0, :cond_1c

    .line 226
    new-instance v0, Landroid/os/DropBoxManager$Entry;

    invoke-virtual {p1}, Landroid/os/Parcel;->createByteArray()[B

    move-result-object v4

    and-int/lit8 v5, v5, -0x9

    invoke-direct/range {v0 .. v5}, Landroid/os/DropBoxManager$Entry;-><init>(Ljava/lang/String;J[BI)V

    .end local v5    # "flags":I
    return-object v0

    .line 228
    .restart local v5    # "flags":I
    :cond_1c
    sget-object v0, Landroid/os/ParcelFileDescriptor;->CREATOR:Landroid/os/Parcelable$Creator;

    invoke-interface {v0, p1}, Landroid/os/Parcelable$Creator;->createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;

    move-result-object v4

    check-cast v4, Landroid/os/ParcelFileDescriptor;

    .line 229
    .local v4, "pfd":Landroid/os/ParcelFileDescriptor;
    new-instance v0, Landroid/os/DropBoxManager$Entry;

    invoke-direct/range {v0 .. v5}, Landroid/os/DropBoxManager$Entry;-><init>(Ljava/lang/String;JLandroid/os/ParcelFileDescriptor;I)V

    return-object v0
.end method

.method public bridge synthetic createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;
    .registers 3
    .param p1, "in"    # Landroid/os/Parcel;

    .prologue
    .line 221
    invoke-virtual {p0, p1}, Landroid/os/DropBoxManager$Entry$1;->createFromParcel(Landroid/os/Parcel;)Landroid/os/DropBoxManager$Entry;

    move-result-object v0

    return-object v0
.end method

.method public newArray(I)[Landroid/os/DropBoxManager$Entry;
    .registers 3
    .param p1, "size"    # I

    .prologue
    .line 220
    new-array v0, p1, [Landroid/os/DropBoxManager$Entry;

    return-object v0
.end method

.method public bridge synthetic newArray(I)[Ljava/lang/Object;
    .registers 3
    .param p1, "size"    # I

    .prologue
    .line 220
    invoke-virtual {p0, p1}, Landroid/os/DropBoxManager$Entry$1;->newArray(I)[Landroid/os/DropBoxManager$Entry;

    move-result-object v0

    return-object v0
.end method


text:
import $ from 'jquery';
import waypoints from '../../../../node_modules/waypoints/lib/noframework.waypoints';

class RevealOnScroll {
  constructor(elem, offset) {
    this.lazyImages = $('.lazyload');
    this.itemsToReveal = elem;
    this.offsetPercentage =  $('.page-section');
    this.hideInitially();
    this.createWaypoints();
    this.refreshWaypoints();
  }

  refreshWaypoints() {
    this.lazyImages.on('load', function() {
      Waypoint.refreshAll();
    });
  }

  hideInitially() {
    this.itemsToReveal.addClass('reveal-item');
  }

  createWaypoints() {
    var currentObject = this; // This will select the currently selected Object ( in this case we will use to select offsetPercentage)
    this.itemsToReveal.each(function() {
      var currentItem = this; // This will select all elements with a .reveal-item class
      new Waypoint({
        element: currentItem,
        handler: function(direction) {
          if(direction == 'down') {
            $(currentItem).addClass('reveal-item--is-visible');
          } else {
            $(currentItem).removeClass('reveal-item--is-visible');
          }
        },
        offset: currentObject.offsetPercentage
      });
    });
  }
}

export default RevealOnScroll;

redpajama_set_name: RedPajamaGithub


text:
[ -z "$TEST_SRCDIR" ] && { echo "TEST_SRCDIR not set!" >&2; exit 1; }

# Load the unit-testing framework
source "${TEST_SRCDIR}/src/test/shell/unittest.bash" || \
  { echo "Failed to source unittest.bash" >&2; exit 1; }

# Bazel
bazel_tree="${TEST_SRCDIR}/src/test/shell/bazel/doc-srcs.zip"
bazel_path="${TEST_SRCDIR}/src"
bazel_data="${TEST_SRCDIR}"

# Java
jdk_dir="${TEST_SRCDIR}/external/local-jdk"
langtools="${TEST_SRCDIR}/src/test/shell/bazel/langtools.jar"

# Tools directory location
tools_dir="${TEST_SRCDIR}/tools"
langtools_dir="${TEST_SRCDIR}/third_party/java/jdk/langtools"
EXTRA_BAZELRC="build --java_langtools=//tools/jdk:test-langtools --ios_sdk_version=8.4"

# Java tooling
javabuilder_path="${TEST_SRCDIR}/src/java_tools/buildjar/JavaBuilder_deploy.jar"
langtools_path="${TEST_SRCDIR}/third_party/java/jdk/langtools/javac.jar"
singlejar_path="${TEST_SRCDIR}/src/java_tools/singlejar/SingleJar_deploy.jar"
genclass_path="${TEST_SRCDIR}/src/java_tools/buildjar/java/com/google/devtools/build/buildjar/genclass/GenClass_deploy.jar"
ijar_path="${TEST_SRCDIR}/third_party/ijar/ijar"

# Android tooling
aargenerator_path="${TEST_SRCDIR}/src/tools/android/java/com/google/devtools/build/android/AarGeneratorAction_deploy.jar"
androidresourceprocessor_path="${TEST_SRCDIR}/src/tools/android/java/com/google/devtools/build/android/AndroidResourceProcessingAction_deploy.jar"
dexmapper_path="${TEST_SRCDIR}/src/tools/android/java/com/google/devtools/build/android/ziputils/mapper_deploy.jar"
dexreducer_path="${TEST_SRCDIR}/src/tools/android/java/com/google/devtools/build/android/ziputils/reducer_deploy.jar"
incrementaldeployment_path="${TEST_SRCDIR}/src/tools/android/java/com/google/devtools/build/android/incrementaldeployment"

# iOS and Objective-C tooling
iossim_path="${TEST_SRCDIR}/third_party/iossim/iossim"
actoolzip_path="${TEST_SRCDIR}/src/tools/xcode-common/java/com/google/devtools/build/xcode/actoolzip/actoolzip_deploy.jar"
ibtoolwrapper_path="${TEST_SRCDIR}/src/tools/xcode/ibtoolwrapper/ibtoolwrapper.sh"
swiftstdlibtoolzip_path="${TEST_SRCDIR}/src/tools/xcode-common/java/com/google/devtools/build/xcode/swiftstdlibtoolzip/swiftstdlibtoolzip_deploy.jar"
momczip_path="${TEST_SRCDIR}/src/objc_tools/momczip/momczip_deploy.jar"
bundlemerge_path="${TEST_SRCDIR}/src/objc_tools/bundlemerge/bundlemerge_deploy.jar"
plmerge_path="${TEST_SRCDIR}/src/objc_tools/plmerge/plmerge_deploy.jar"
xcodegen_path="${TEST_SRCDIR}/src/objc_tools/xcodegen/xcodegen_deploy.jar"
stdredirect_path="${TEST_SRCDIR}/src/tools/xcode/stdredirect/StdRedirect.dylib"
realpath_path="${TEST_SRCDIR}/src/tools/xcode/realpath/realpath"
environment_plist_path="${TEST_SRCDIR}/src/tools/xcode/environment/environment_plist.sh"

# Test data
testdata_path=${TEST_SRCDIR}/src/test/shell/bazel/testdata
python_server="${TEST_SRCDIR}/src/test/shell/bazel/testing_server.py"

# Third-party
PLATFORM="$(uname -s | tr 'A-Z' 'a-z')"
MACHINE_TYPE="$(uname -m)"
MACHINE_IS_64BIT='no'
if [ "${MACHINE_TYPE}" = 'amd64' -o "${MACHINE_TYPE}" = 'x86_64' ]; then
  MACHINE_IS_64BIT='yes'
fi
case "${PLATFORM}" in
  darwin)
    if [ "${MACHINE_IS_64BIT}" = 'yes' ]; then
      protoc_compiler="${TEST_SRCDIR}/third_party/protobuf/protoc-osx-x86_64.exe"
    else
      protoc_compiler="${TEST_SRCDIR}/third_party/protobuf/protoc-osx-x86_32.exe"
    fi
    ;;
  *)
    if [ "${MACHINE_IS_64BIT}" = 'yes' ]; then
      protoc_compiler="${TEST_SRCDIR}/third_party/protobuf/protoc-linux-x86_64.exe"
    else
      protoc_compiler="${TEST_SRCDIR}/third_party/protobuf/protoc-linux-x86_32.exe"
    fi
    ;;
esac
protoc_jar="${TEST_SRCDIR}/third_party/protobuf/protobuf-*.jar"
junit_jar="${TEST_SRCDIR}/third_party/junit/junit-*.jar"
hamcrest_jar="${TEST_SRCDIR}/third_party/hamcrest/hamcrest-*.jar"

# This function copies the tools directory from Bazel.
function copy_tools_directory() {
  cp -RL ${tools_dir}/* tools
  # To support custom langtools
  cp ${langtools} tools/jdk/langtools.jar
  cat >>tools/jdk/BUILD <<'EOF'
filegroup(name = "test-langtools", srcs = ["langtools.jar"])
EOF

  mkdir -p third_party/java/jdk/langtools
  cp -R ${langtools_dir}/* third_party/java/jdk/langtools

  chmod -R +w .
  mkdir -p tools/defaults
  touch tools/defaults/BUILD
}

# Report whether a given directory name corresponds to a tools directory.
function is_tools_directory() {
  case "$1" in
    third_party|tools|src)
      true
      ;;
    *)
      false
      ;;
  esac
}

# Copy the examples of the base workspace
function copy_examples() {
  EXAMPLE="$TEST_SRCDIR/examples"
  cp -RL ${EXAMPLE} .
  chmod -R +w .
}

#
# Find a random unused TCP port
#
pick_random_unused_tcp_port () {
    perl -MSocket -e '
sub CheckPort {
  my ($port) = @_;
  socket(TCP_SOCK, PF_INET, SOCK_STREAM, getprotobyname("tcp"))
    || die "socket(TCP): $!";
  setsockopt(TCP_SOCK, SOL_SOCKET, SO_REUSEADDR, 1)
    || die "setsockopt(TCP): $!";
  return 0 unless bind(TCP_SOCK, sockaddr_in($port, INADDR_ANY));
  socket(UDP_SOCK, PF_INET, SOCK_DGRAM, getprotobyname("udp"))
    || die "socket(UDP): $!";
  return 0 unless bind(UDP_SOCK, sockaddr_in($port, INADDR_ANY));
  return 1;
}
for (1 .. 128) {
  my ($port) = int(rand() * 27000 + 32760);
  if (CheckPort($port)) {
    print "$port\n";
    exit 0;
  }
}
print "NO_FREE_PORT_FOUND\n";
exit 1;
'
}

#
# A uniform SHA-256 commands that works accross platform
#
case "${PLATFORM}" in
  darwin)
    function sha256sum() {
      cat "$1" | shasum -a 256 | cut -f 1 -d " "
    }
    ;;
  *)
    # Under linux sha256sum should exists
    ;;
esac


text:
TODO: 平时积累的一些小程序片段

## Installation

TODO: git clone 即可

## Usage

TODO: no

## Development

TODO:  crystal 0.21.0

## Contributing

1. Fork it ( https://github.com/lgphp/crystal-example/fork )
2. Create your feature branch (git checkout -b my-new-feature)
3. Commit your changes (git commit -am 'Add some feature')
4. Push to the branch (git push origin my-new-feature)
5. Create a new Pull Request

## Contributors

- [[lgphp]](https://github.com/[lgphp])  - creator, maintainer


text:
package de.mikeherwig.LRWebdriverBridgeActions;

import static org.junit.Assert.*;

import org.junit.Test;

import actions.SimpleExampleAction;
import de.mikeherwig.LRWebdriverBridge.ActionListener;
import de.mikeherwig.LRWebdriverBridge.LRWebdriverBridge;
import de.mikeherwig.LRWebdriverBridge.RunnerMode;

public class WebdriverRunnerTest {

	@Test
	public void executeAction() {
		LRWebdriverBridge bridge = LRWebdriverBridge.getInstance();

		assertNotNull(bridge);

		bridge.addActionListener(new ActionListener() {

			@Override
			public void onMessageReceive(String message, String exceptionMessage) {
				System.out.println(message);
			}

			@Override
			public void onBeforeRun() {}

			@Override
			public void onAfterRun(long responseTime, boolean isSuccess, String actionName) {
				assertTrue(responseTime > 0);
				String[] arr = SimpleExampleAction.class.getName().split("\\.");
				assertEquals(actionName, arr[arr.length - 1]);
				System.out.println("Finished action in " + responseTime + " ms.");
			}
		});

		boolean isSuccess = bridge.execute(SimpleExampleAction.class.getName(), RunnerMode.WEBDRIVER_API);
		assertTrue(isSuccess);
	}

}


text:
package com.android.org.bouncycastle.jce.provider.asymmetric;

@com.francetelecom.rd.stubs.annotation.ClassDone(0)
public class EC
{
  // Classes

  public static class Mappings
    extends java.util.HashMap  {
    // Constructors

    public Mappings(){
      super();
    }
  }
  // Constructors

  public EC(){
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <ImageView
        android:id="@+id/summary_img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="10dp"
        android:scaleType="center" >
    </ImageView>

    <cn.bingoogolapple.badgeview.BGABadgeTextView
        android:id="@+id/summary_text"
        style="@style/wrap_warp_tv_centerVertical"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/summary_img"
        android:textColor="#333333"
        android:textSize="16sp"
        android:layout_marginLeft="16dp"
        android:paddingRight="18dp"
        app:badge_padding="5dp"
        app:badge_gravity="rightCenter">
    </cn.bingoogolapple.badgeview.BGABadgeTextView>

    <TextView
        android:id="@+id/detail_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toLeftOf="@+id/detail_img"
        android:text="详情"
        android:textColor="#999999"
        android:textSize="16sp" >
    </TextView>

    <ImageView
        android:id="@+id/detail_img"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="8dp"
        android:scaleType="center"
        android:visibility="gone" >
    </ImageView>

    <View
        android:id="@+id/divider"
        android:layout_alignParentBottom="true"
        style="@style/divider_style" />

</RelativeLayout>


text:
import collections
from typing import Callable, Iterable, List, Optional, Tuple

Mutations = Iterable[Tuple[str, Callable[[str], str]]]

# Set to force solution paths always require given string.
REQUIRED_SUBSTRING = ()

BOO_MAP = {
  'a': 'ue',
  'e': 'ai',
  'i': 'eo',
  'o': 'iu',
  'u': 'oa',
}
BOO_PRIME_SUCC_MAP = {  # Seeing a `key` requires `value` follows.
  leader: successor for (leader, successor) in BOO_MAP.values()
}
BOO_PRIME_LEAD_MAP = {  # Seeing a `key` implies insert `value`.
  value[0]: key for key, value in BOO_MAP.items()
}
LETTERS = 'zabcdefghijklmnopqrstuvwxyza'
# Override available letters, if appropriate:
# LETTERS = 'asinrd'
WIGGLER_MAP = {
  LETTERS[i]: LETTERS[i+1] + LETTERS[i-1] for i in range(1, len(LETTERS) - 1)
}
# Override available wiggler moves, if appropriate:
# WIGGLER_MAP = {'n': 'om', 'e': 'fd'}
WIGGLER_PRIME_SUCC_MAP = {
  leader: successor for (leader, successor) in WIGGLER_MAP.values()
}
WIGGLER_PRIME_LEAD_MAP = {
  value[0]: key for key, value in WIGGLER_MAP.items()
}

SHYGUY_MAP = str.maketrans('lr', 'rl')

def boo(a: str) -> str:
  return ''.join(BOO_MAP.get(c, c) for c in a)

def BOO(src: str, acc: tuple) -> Mutations:
  del src, acc
  yield 'boo', boo

def boo_prime(src: str) -> str:
  i = 0
  end = len(src)
  result = []
  while i < end:
    c = src[i]
    result.append(BOO_PRIME_LEAD_MAP.get(c, c))
    if src[i] in BOO_PRIME_SUCC_MAP:
      i += 1  # Skip next letter.
    i += 1
  return ''.join(result)

def BOO_PRIME(src: str, acc: tuple) -> Mutations:
  del acc
  i = 0
  end = len(src) - 1
  while i < end:
    if src[i] in BOO_PRIME_SUCC_MAP:
      if BOO_PRIME_SUCC_MAP[src[i]] != src[i+1]:
        return
      i += 1  # Skip the pair.
    i += 1
  # Special case for last letter which may have been unchecked.
  if src[-1] in BOO_PRIME_SUCC_MAP and src[-2] not in BOO_PRIME_SUCC_MAP:
    return
  yield 'boo', boo_prime

def bowser(a: str) -> str:
  lowest_c = min(a)
  return a.replace(lowest_c, '')

def BOWSER(src: str, acc: tuple) -> Mutations:
  if any_dupe('bowser', acc):
    return
  del src, acc
  yield 'bowser', bowser

def bullet(a: str, charge:str) -> str:
  return charge[0] + a[1:]

def BULLET(src: str, acc: tuple) -> Mutations:
  del src
  if next_dupe('bullet', acc):
    return
  for c in LETTERS:
    yield 'bullet(%s)' % c, lambda a: bullet(a, c)

BULLET_PRIME = BULLET

def inky(a: str, charge:str) -> str:
  return a[0] + charge[0] + a[1:-1] + charge[0] + a[-1]

def INKY(src: str, acc: tuple) -> Mutations:
  del src, acc
  for c in LETTERS:
    yield 'inky(%s)' % c, lambda a: inky(a, c)

def inky_prime(src: str) -> str:
  return src[0] + src[2:-2] + src[-1]

def INKY_PRIME(src: str, acc: tuple) -> Mutations:
  del acc
  if len(src) < 4:
    return
  if src[1] != src[-2]:
    return
  yield 'inky(%s)' % src[1], inky_prime

def lakitu(a: str, n:int) -> str:
  return a[n:] + a[:n]

def LAKITU(src: str, acc: tuple) -> Mutations:
  if next_dupe('lakitu', acc):
    return
  for n in range(1, len(src)):
    yield 'lakitu(%s)' % src[n], lambda a: lakitu(a, n)

LAKITU_PRIME = LAKITU

def piranha(a: str) -> str:
  n = int(len(a) / 2)
  return a[n:] + ' ' + a[:n]

def PIRANHA(src: str, acc: tuple) -> Mutations:
  del acc
  if ' ' in src:  # Limit to 1 word.
    return
  yield 'piranha', piranha

def shyguy(a: str) -> str:
  return a.translate(SHYGUY_MAP)

def SHYGUY(src: str, acc: tuple) -> Mutations:
  del src
  if next_dupe('shyguy', acc):
    return
  yield 'shyguy', shyguy

def wiggler(a: str, n: int) -> str:
  return a[:n] + WIGGLER_MAP[a[n]] + a[n + 1:]

def WIGGLER(src: str, acc: tuple) -> Mutations:
  del acc
  for n in range(len(src) - 1):
    if src[n] in WIGGLER_MAP:
      yield 'wiggler(%s%d)' % (src[n], n), lambda a: wiggler(a, n)

def wiggler_prime(src: str, n: int) -> str:
  return src[:n] + WIGGLER_PRIME_LEAD_MAP[src[n]] + src[n+2:]

def WIGGLER_PRIME(src: str, acc: tuple) -> Mutations:
  del acc
  i = 0
  end = len(src) - 1
  while i < end:
    if src[i] in WIGGLER_PRIME_SUCC_MAP:
      if WIGGLER_PRIME_SUCC_MAP[src[i]] == src[i+1]:
        yield 'wiggler(%s%d)' % (src[i], i), lambda a: wiggler_prime(a, i)
        i += 1  # Skip the pair.
    i += 1

CAN_SHRINK = {
  BOWSER,
  BOO_PRIME,
  WIGGLER_PRIME,
  INKY_PRIME,
}
CAN_GROW = {
  BOO,
  WIGGLER,
  INKY,
  PIRANHA,
}

def search(start: str, end: str, characters: list) -> str:
  result = search_inner(start, end, characters)
  formatted = []
  while result:
    result, top = result
    formatted.append(top)
  return ', '.join(reversed(formatted))

def search_inner(
    start: str, end: str, characters: list, depth: int = 10) -> Optional[tuple]:
  queue = collections.deque([(start, (), depth)])
  end_length = len(end)
  can_shrink = any(c in CAN_SHRINK for c in characters)
  can_grow = any(c in CAN_GROW for c in characters)
  last_depth = None
  seen = set()
  while queue:
    current, acc, remaining = queue.popleft()
    if last_depth != remaining:
      last_depth = remaining
    if remaining <= 0:
      continue
    for desc, mutation in mutations(characters, current, acc):
      changed = mutation(current).strip()
      if changed == end:
        return acc, desc
      elif remaining <= 0:
        continue
      elif changed != start:
        changed_length = len(changed)
        if (
            (changed_length == end_length) or
            (changed_length > end_length and can_shrink) or
            can_grow
          ):
          if any(s not in changed+changed for s in REQUIRED_SUBSTRING):
            continue
          hashed = hash(changed)
          if hashed not in seen:
            seen.add(hashed)  # Never revisit same word twice.
            queue.append((changed, (acc, desc), remaining - 1))
  return None

def mutations(characters: List[Callable], src: str, acc: tuple) -> Iterable:
  for character in characters:
    yield from character(src, acc)

def next_dupe(search: str, acc: tuple):
  if not acc:
    return False
  return acc[1].startswith(search)

def any_dupe(search: str, acc: tuple):
  while acc:
    if acc[1].startswith(search):
      return True
    acc = acc[0]
  return False


text:
package streamers

import (
	"io"
	"os"
	"path/filepath"
	"strconv"

	"github.com/cadenzr/cadenzr/models"
	"github.com/cadenzr/cadenzr/transcoders"
)

type Streamer interface {
	io.Closer
	io.ReadSeeker
}

type FileStreamer struct {
	f *os.File
}

func (s *FileStreamer) Read(p []byte) (n int, err error) {
	n, err = s.f.Read(p)
	return
}

func (s *FileStreamer) Seek(offset int64, whence int) (n int64, err error) {
	n, err = s.f.Seek(offset, whence)

	return
}

func (s *FileStreamer) Close() error {
	return s.f.Close()
}

func NewFileStreamer(path string) (streamer Streamer, err error) {
	fh, err := os.Open(path)
	if err != nil {
		return
	}

	streamer = &FileStreamer{
		f: fh,
	}

	return
}

func NewTranscodeStreamer(song *models.Song, codec transcoders.CodecType) (streamer Streamer, err error) {
	cachePath := "cache" + string(filepath.Separator) + "transcodings" + string(filepath.Separator) + strconv.Itoa(int(song.ID)) + codec.Extension()
	err = os.MkdirAll(filepath.Dir(cachePath), 0755)
	if err != nil {
		return
	}

	if _, err = os.Stat(cachePath); !os.IsNotExist(err) {
		return NewFileStreamer(cachePath)
	}

	originalFile, err := os.Open(song.Path)
	if err != nil {
		return
	}
	defer originalFile.Close()

	cacheFile, err := os.Create(cachePath)
	if err != nil {
		return
	}
	defer cacheFile.Close()

	transcoder, err := transcoders.NewTranscoder(originalFile, codec)
	if err != nil {
		return
	}

	_, err = io.Copy(cacheFile, transcoder)
	if err != nil {
		// So that it first gets closed?
		defer os.Remove(cachePath)
		return
	}

	streamer, err = NewFileStreamer(cachePath)
	return
}


text:
{% set pagetitle = 'Common complaints' %}
{% set seq_length = 0 %}
{% set seq_position = 0 %}
{% set seq_llink = "javascript:;" %}		## set rlink equal to next page href
{% set seq_rlink = "javascript:;" %}		## set llink equal to previous page href
{% extends "templates.jinja/base.page-with-sequence.html" %}
{% block title %} Hesperian - Pregnancy & Birth{% endblock %}
{% block id %}Cravings_during_pregnancy{% endblock %}

		{% block content %}

Cravings

A food craving is a strong desire to eat a certain food, or even something that is not food at all, like dirt, chalk, or clay. If a woman gets a craving for nutritious foods (like beans, eggs, fruits, and vegetables), it is OK for her to eat as much as she wants.

A woman who wants a lot of "junk food" (like candy, soda, or packaged snacks) should eat nutritious food first.

A woman who craves things that are not food, like dirt or clay, should not eat them. They may poison her and her baby, or make her sick. This may be a sign that she needs more protein and iron-rich foods in her diet.

		{% endblock %}
		{% block footer %}

				Related information:
				Eating well during pregnancy
				Signs of anemia

		{% endblock %}


text:
package com.iluwatar.factorymethod;

/**
 *
 * The interface containing method for producing objects.
 *
 */
public interface Blacksmith {

	Weapon manufactureWeapon(WeaponType weaponType);

}


text:
package org.sakaiproject.lessonbuildertool.model;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

import java.sql.Connection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.sakaiproject.authz.api.SecurityService;
import org.sakaiproject.authz.cover.AuthzGroupService;
import org.sakaiproject.db.api.SqlReader;
import org.sakaiproject.db.api.SqlService;
import org.sakaiproject.event.cover.EventTrackingService;
import org.sakaiproject.lessonbuildertool.SimplePage;
import org.sakaiproject.lessonbuildertool.SimplePageComment;
import org.sakaiproject.lessonbuildertool.SimplePageCommentImpl;
import org.sakaiproject.lessonbuildertool.SimplePageGroup;
import org.sakaiproject.lessonbuildertool.SimplePageGroupImpl;
import org.sakaiproject.lessonbuildertool.SimplePageImpl;
import org.sakaiproject.lessonbuildertool.SimplePageItem;
import org.sakaiproject.lessonbuildertool.SimplePageItemImpl;
import org.sakaiproject.lessonbuildertool.SimplePageItemAttributeImpl;
import org.sakaiproject.lessonbuildertool.SimplePageLogEntry;
import org.sakaiproject.lessonbuildertool.SimplePageLogEntryImpl;
import org.sakaiproject.lessonbuildertool.SimplePageQuestionAnswer;
import org.sakaiproject.lessonbuildertool.SimplePageQuestionAnswerImpl;
import org.sakaiproject.lessonbuildertool.SimplePageQuestionResponse;
import org.sakaiproject.lessonbuildertool.SimplePageQuestionResponseImpl;
import org.sakaiproject.lessonbuildertool.SimplePageQuestionResponseTotals;
import org.sakaiproject.lessonbuildertool.SimplePageQuestionResponseTotalsImpl;
import org.sakaiproject.lessonbuildertool.SimpleStudentPage;
import org.sakaiproject.lessonbuildertool.SimpleStudentPageImpl;
import org.sakaiproject.lessonbuildertool.SimplePagePeerEval;
import org.sakaiproject.lessonbuildertool.SimplePagePeerEvalImpl;
import org.sakaiproject.lessonbuildertool.SimplePagePeerEvalResult;
import org.sakaiproject.lessonbuildertool.SimplePagePeerEvalResultImpl;
import org.sakaiproject.lessonbuildertool.SimplePageProperty;
import org.sakaiproject.lessonbuildertool.SimplePagePropertyImpl;

import org.sakaiproject.tool.api.ToolManager;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.orm.hibernate3.HibernateTemplate;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.JSONArray;

public class SimplePageToolDaoImpl extends HibernateDaoSupport implements SimplePageToolDao {
	private static Log log = LogFactory.getLog(SimplePageToolDaoImpl.class);

	private ToolManager toolManager;
	private SecurityService securityService;
	private SqlService sqlService;
	private static String SITE_UPD = "site.upd";

        // part of HibernateDaoSupport; this is the only context in which it is OK
        // to modify the template configuration
	protected void initDao() throws Exception {
		super.initDao();
		getHibernateTemplate().setCacheQueries(true);
		log.info("initDao template " + getHibernateTemplate());
		SimplePageItemImpl.setSimplePageToolDao(this);
	}

	// the permissions model here is preliminary. I'm not convinced that all the code in
	// upper layers checks where it should, so the Dao is supplying an extra layer of
	// protection. As far as I can tell, any database change should be done by
	// someone with update privs, except that add or update to the log is done on
	// behalf of normal people. I've checked all the code that does save or update for
	// log entries and it looks OK.

	public boolean canEditPage() {
		String ref = null;
		// no placement, startup testing, should be an advisor in place
		try {
			ref = "/site/" + toolManager.getCurrentPlacement().getContext();
		} catch (java.lang.NullPointerException ignore) {
			ref = "";
		}
		return securityService.unlock(SimplePage.PERMISSION_LESSONBUILDER_UPDATE, ref);
	}

	public boolean canEditPage(long pageId) {
		boolean canEdit = canEditPage();
		// forced comments have a pageid of -1, because they are associated with
		// more than one page. But the student can't edit them anyway, so fail it
		//  also, top-level fake items have pageid of 0
		if(!canEdit && pageId != -1L && pageId != 0L) {
			SimplePage page = getPage(pageId);
			String owner = page.getOwner();
			String group = page.getGroup();
			if (group != null)
			    group = "/site/" + page.getSiteId() + "/group/" + group;
			String currentUser = UserDirectoryService.getCurrentUser().getId();
			if (currentUser != null) {
			    if (group == null && currentUser.equals(owner))
				canEdit = true;
			    else if (group != null && AuthzGroupService.getUserRole(currentUser, group) != null)
				canEdit = true;
			}
		}

		return canEdit;
	}

	public boolean canEditPage(SimplePage page) {
		boolean canEdit = canEditPage();
		// forced comments have a pageid of -1, because they are associated with
		// more than one page. But the student can't edit them anyway, so fail it
		if(!canEdit && page != null) {
			String owner = page.getOwner();
			String group = page.getGroup();
			if (group != null)
			    group = "/site/" + page.getSiteId() + "/group/" + group;
			String currentUser = UserDirectoryService.getCurrentUser().getId();
			if (currentUser != null) {
			    if (group == null && currentUser.equals(owner))
				canEdit = true;
			    else if (group != null && AuthzGroupService.getUserRole(currentUser, group) != null)
				canEdit = true;
			}
		}
		return canEdit;
	}

	public void setSecurityService(SecurityService service) {
		securityService = service;
	}

	public void setSqlService(SqlService service) {
		sqlService = service;
	}

	public void setToolManager(ToolManager service) {
		toolManager = service;
	}

	public List<SimplePageItem> findItemsOnPage(long pageId) {
	    DetachedCriteria d = DetachedCriteria.forClass(SimplePageItem.class).add(Restrictions.eq("pageId", pageId));
		List<SimplePageItem> list = getHibernateTemplate().findByCriteria(d);

		Collections.sort(list, new Comparator<SimplePageItem>() {
			public int compare(SimplePageItem a, SimplePageItem b) {
				return Integer.valueOf(a.getSequence()).compareTo(b.getSequence());
			}
		});

		return list;
	}

	public void flush() {
	    getHibernateTemplate().flush();
	}

	public void clear() {
	    getHibernateTemplate().clear();
	}

	public List<SimplePageItem> findItemsInSite(String siteId) {
	    Object [] fields = new Object[1];
	    fields[0] = siteId;
	    List<String> ids = sqlService.dbRead("select b.id from lesson_builder_pages a,lesson_builder_items b,SAKAI_SITE_PAGE c where a.siteId = ? and a.parent is null and a.pageId = b.sakaiId and b.type = 2 and b.pageId = 0 and a.toolId = c.PAGE_ID order by c.SITE_ORDER", fields, null);

	    List<SimplePageItem> result = new ArrayList<SimplePageItem>();

	    if (result != null) {
		for (String id: ids) {
		    SimplePageItem i = findItem(new Long(id));
		    result.add(i);
		}
	    }
	    return result;
	}

	public List<SimplePageItem> findDummyItemsInSite(String siteId) {
	    Object [] fields = new Object[1];
	    fields[0] = siteId;
	    List<String> ids = sqlService.dbRead("select b.id from lesson_builder_pages a,lesson_builder_items b where a.siteId = ? and a.pageId = b.pageId and b.sakaiId = '/dummy'", fields, null);

	    List<SimplePageItem> result = new ArrayList<SimplePageItem>();

	    if (result != null) {
		for (String id: ids) {
		    SimplePageItem i = findItem(new Long(id));
		    result.add(i);
		}
	    }
	    return result;
	}

    // warning: only the id and html fields will be filled out
    // we had serious performance issues with an earlier version, so I'm doing it without hibernate
	public List<SimplePageItem> findTextItemsInSite(String siteId) {
	    Object [] fields = new Object[1];
	    fields[0] = siteId;
	    List<SimplePageItem> items = sqlService.dbRead("select b.id,b.html from lesson_builder_pages a,lesson_builder_items b where a.siteId = ? and a.pageId = b.pageId and b.type = 5", fields, new SqlReader() {
		    public Object readSqlResultRecord(ResultSet result) {
    			try {
			    SimplePageItem item = new SimplePageItemImpl();
			    item.setId(result.getLong(1));
			    item.setHtml(result.getString(2));
			    return item;
    			} catch (SQLException e) {
			    log.warn("findTextItemsInSite: " + e);
			    return null;
    			}
		    }
		});

	    return items;
	}

    // because they don't come from hibernate, you can't use update on them.
    // we need to be able to update the HTML field

    public PageData findMostRecentlyVisitedPage(final String userId, final String toolId) {
    	Object [] fields = new Object[4];
    	fields[0] = userId;
    	fields[1] = toolId;
    	fields[2] = userId;
    	fields[3] = toolId;

    	List<PageData> rv = sqlService.dbRead("select a.itemId, a.id, b.sakaiId, b.name from lesson_builder_log a, lesson_builder_items b where a.userId=? and a.toolId=? and a.lastViewed = (select max(lastViewed) from lesson_builder_log where userId=? and toolId = ?) and a.itemId = b.id", fields, new SqlReader() {
    		public Object readSqlResultRecord(ResultSet result) {
    			try {
    				PageData ret = new PageData();
    				ret.itemId = result.getLong(1);
    				ret.pageId = result.getLong(3);
    				ret.name = result.getString(4);

    				return ret;
    			} catch (SQLException e) {
    				log.warn("findMostRecentlyVisitedPage: " + toolId + " : " + e);
    				return null;
    			}
    		}
    	});

    	if (rv != null && rv.size() > 0)
    		return rv.get(0);
    	else
    		return null;
	}

	public SimplePageItem findItem(long id) {

		DetachedCriteria d = DetachedCriteria.forClass(SimplePageItem.class).add(Restrictions.eq("id", id));
		List<SimplePageItem> list = getHibernateTemplate().findByCriteria(d);

		if (list != null && list.size() > 0) {
			return list.get(0);
		} else {
			return null;
		}
	}

	public SimplePageProperty findProperty(String attribute) {

		DetachedCriteria d = DetachedCriteria.forClass(SimplePageProperty.class).add(Restrictions.eq("attribute", attribute));

		List<SimplePageProperty> list = null;
		try {
		    list = getHibernateTemplate().findByCriteria(d);
		} catch (org.hibernate.ObjectNotFoundException e) {
		    return null;
		}

		if (list != null && list.size() > 0) {
			return list.get(0);
		} else {
			return null;
		}
	}

        public SimplePageProperty makeProperty(String attribute, String value) {
	    return new SimplePagePropertyImpl(attribute, value);
	}

	public List<SimplePageComment> findComments(long commentWidgetId) {
		DetachedCriteria d = DetachedCriteria.forClass(SimplePageComment.class).add(Restrictions.eq("itemId", commentWidgetId));
		List<SimplePageComment> list = getHibernateTemplate().findByCriteria(d);

		return list;
	}

	public List<SimplePageComment> findCommentsOnItems(List<Long> commentItemIds) {
		if ( commentItemIds == null || commentItemIds.size() == 0)
		    return new ArrayList<SimplePageComment>();

		DetachedCriteria d = DetachedCriteria.forClass(SimplePageComment.class).add(Restrictions.in("itemId", commentItemIds));
		List<SimplePageComment> list = getHibernateTemplate().findByCriteria(d);

		return list;
	}

	public List<SimplePageComment> findCommentsOnItemsByAuthor(List<Long> commentItemIds, String author) {
		if ( commentItemIds == null || commentItemIds.size() == 0)
		    return new ArrayList<SimplePageComment>();

		DetachedCriteria d = DetachedCriteria.forClass(SimplePageComment.class).add(Restrictions.in("itemId", commentItemIds))
				.add(Restrictions.eq("author", author));
		List<SimplePageComment> list = getHibernateTemplate().findByCriteria(d);

		return list;
	}

	public List<SimplePageComment> findCommentsOnItemByAuthor(long commentWidgetId, String author) {
		DetachedCriteria d = DetachedCriteria.forClass(SimplePageComment.class)
		    .add(Restrictions.eq("itemId", commentWidgetId))
		    .add(Restrictions.eq("author", author));

		List<SimplePageComment> list = getHibernateTemplate().findByCriteria(d);

		return list;
	}

	public List<SimplePageComment> findCommentsOnPageByAuthor(long pageId, String author) {
		DetachedCriteria d = DetachedCriteria.forClass(SimplePageComment.class)
			.add(Restrictions.eq("pageId", pageId))
			.add(Restrictions.eq("author", author));

		List<SimplePageComment> list = getHibernateTemplate().findByCriteria(d);

		return list;
	}

	public SimplePageComment findCommentById(long commentId) {
		DetachedCriteria d = DetachedCriteria.forClass(SimplePageComment.class).add(Restrictions.eq("id", commentId));
		List<SimplePageComment> list = getHibernateTemplate().findByCriteria(d);

		if(list.size() > 0) {
			return list.get(0);
		}else {
			return null;
		}
	}

	public SimplePageComment findCommentByUUID(String commentUUID) {
		DetachedCriteria d = DetachedCriteria.forClass(SimplePageComment.class).add(Restrictions.eq("UUID", commentUUID));
		List<SimplePageComment> list = getHibernateTemplate().findByCriteria(d);

		if(list.size() > 0) {
			return list.get(0);
		}else {
			return null;
		}
	}

	public SimplePageItem findCommentsToolBySakaiId(String sakaiId) {
		DetachedCriteria d = DetachedCriteria.forClass(SimplePageItem.class).add(Restrictions.eq("sakaiId", sakaiId));
		List<SimplePageItem> list = getHibernateTemplate().findByCriteria(d);

		// We loop through and check type here in-case something else has the same
		// sakaiId, and to prevent creating a new index for something that probably
		// doesn't really need it.  There shouldn't be more than a couple of matches
		// with different types.
		for(SimplePageItem item : list) {
			if(item.getType() == SimplePageItem.COMMENTS) {
				return item;
			}
		}

		return null;
	}

	public List<SimplePageItem> findItemsBySakaiId(String sakaiId) {
		DetachedCriteria d = DetachedCriteria.forClass(SimplePageItem.class).add(Restrictions.eq("sakaiId", sakaiId));
		return getHibernateTemplate().findByCriteria(d);
	}

    // find the student's page. In theory we keep them from doing a second page. With
    // group pages that means students in more than one group can only do one. So return the first
    // Different versions if item is controlled by group or not. That lets us use simple
    // hibernate queries and maximum caching
	public SimpleStudentPage findStudentPage(long itemId, String owner) {
		DetachedCriteria d = DetachedCriteria.forClass(SimpleStudentPage.class).add(Restrictions.eq("itemId", itemId))
			.add(Restrictions.eq("owner", owner)).add(Restrictions.eq("deleted", false));
		List<SimpleStudentPage> list = getHibernateTemplate().findByCriteria(d);

		if(list.size() > 0) {
			return list.get(0);
		}else {
			return null;
		}
	}

    // groups is set of groups to search.
    // null groups means there are no permitted groups, so the answer is obviously null
	public SimpleStudentPage findStudentPage(long itemId, Collection<String> groups) {
		if (groups == null || groups.size() == 0) // no possible groups, so no result
		    return null;

		DetachedCriteria d = DetachedCriteria.forClass(SimpleStudentPage.class).add(Restrictions.eq("itemId", itemId))
			.add(Restrictions.in("group", groups)).add(Restrictions.eq("deleted", false));
		List<SimpleStudentPage> list = getHibernateTemplate().findByCriteria(d);

		if(list.size() > 0) {
			return list.get(0);
		}else {
			return null;
		}
	}

	public SimpleStudentPage findStudentPage(long id) {
		DetachedCriteria d = DetachedCriteria.forClass(SimpleStudentPage.class).add(Restrictions.eq("id", id));
		List<SimpleStudentPage> list = getHibernateTemplate().findByCriteria(d);

		if(list.size() > 0) {
			return list.get(0);
		}else {
			return null;
		}
	}

	public SimpleStudentPage findStudentPageByPageId(long pageId) {
		DetachedCriteria d = DetachedCriteria.forClass(SimpleStudentPage.class).add(Restrictions.eq("pageId", pageId));
		List<SimpleStudentPage> list = getHibernateTemplate().findByCriteria(d);

		if(list.size() > 0) {
			return list.get(0);
		}else {
			return null;
		}
	}

	public List<SimpleStudentPage> findStudentPages(long itemId) {
		DetachedCriteria d = DetachedCriteria.forClass(SimpleStudentPage.class).add(Restrictions.eq("itemId", itemId));
		List<SimpleStudentPage> list = getHibernateTemplate().findByCriteria(d);

		return list;
	}

	public SimplePageItem findItemFromStudentPage(long pageId) {
		DetachedCriteria d = DetachedCriteria.forClass(SimpleStudentPage.class).add(Restrictions.eq("pageId", pageId));

		List<SimpleStudentPage> list = getHibernateTemplate().findByCriteria(d);

		if(list.size() > 0) {
			return findItem(list.get(0).getItemId());
		}else {
			return null;
		}
	}

	public SimplePageItem findTopLevelPageItemBySakaiId(String id) {
	        DetachedCriteria d = DetachedCriteria.forClass(SimplePageItem.class).add(Restrictions.eq("sakaiId", id))
		    .add(Restrictions.eq("pageId", 0L))
		    .add(Restrictions.eq("type",SimplePageItem.PAGE));

		List<SimplePageItem> list = getHibernateTemplate().findByCriteria(d);

		if (list == null || list.size() < 1)
		    return null;

		return list.get(0);
	}

	public List<SimplePageItem> findPageItemsBySakaiId(String id) {
	        DetachedCriteria d = DetachedCriteria.forClass(SimplePageItem.class).add(Restrictions.eq("sakaiId", id)).
		    add(Restrictions.eq("type",SimplePageItem.PAGE));

		List<SimplePageItem> list = getHibernateTemplate().findByCriteria(d);

		return list;
	}

	public List findControlledResourcesBySakaiId(String id, String siteId) {
	    Object [] fields = new Object[2];
	    fields[0] = id;
	    fields[1] = siteId;
	    List ids = sqlService.dbRead("select a.id from lesson_builder_items a, lesson_builder_pages b where a.sakaiId = ? and ( a.type=1 or a.type=7) and a.prerequisite = 1 and a.pageId = b.pageId and b.siteId = ?", fields, null);
	    return ids;

	}

	public SimplePageItem findNextPageItemOnPage(long pageId, int sequence) {
	        DetachedCriteria d = DetachedCriteria.forClass(SimplePageItem.class).add(Restrictions.eq("pageId", pageId)).
		    add(Restrictions.eq("sequence", sequence+1)).
		    add(Restrictions.eq("type",SimplePageItem.PAGE));

		List<SimplePageItem> list = getHibernateTemplate().findByCriteria(d);

		if (list == null || list.size() < 1)
		    return null;

		return list.get(0);
	}

	public SimplePageItem findNextItemOnPage(long pageId, int sequence) {
	        DetachedCriteria d = DetachedCriteria.forClass(SimplePageItem.class).add(Restrictions.eq("pageId", pageId)).
		    add(Restrictions.eq("sequence", sequence+1));

		List<SimplePageItem> list = getHibernateTemplate().findByCriteria(d);

		if (list == null || list.size() < 1)
		    return null;

		return list.get(0);
	}

	public List<SimplePageQuestionAnswer> findAnswerChoices(SimplePageItem question) {
		List<SimplePageQuestionAnswer> ret = new ArrayList<SimplePageQuestionAnswer>();

		// find new id number, max + 1
		List answers = (List)question.getJsonAttribute("answers");
		if (answers == null)
		    return ret;
		for (Object a: answers) {
		    Map answer = (Map) a;
		    SimplePageQuestionAnswer newAnswer = new SimplePageQuestionAnswerImpl((Long)answer.get("id"),
			       (String)answer.get("text"), (Boolean) answer.get("correct"));
		    ret.add(newAnswer);
		}
		return ret;
	}

	public boolean hasCorrectAnswer(SimplePageItem question) {
		// find new id number, max + 1
		List answers = (List)question.getJsonAttribute("answers");
		if (answers == null)
		    return false;
		for (Object a: answers) {
		    Map answer = (Map) a;
		    if ((Boolean) answer.get("correct"))
			return true;
		}
		return false;
	}

	public SimplePageQuestionAnswer findAnswerChoice(SimplePageItem question, long answerId) {
		// find new id number, max + 1
		List answers = (List)question.getJsonAttribute("answers");
		if (answers == null)
		    return null;
		for (Object a: answers) {
		    Map answer = (Map) a;
		    if (answerId == (Long)answer.get("id")) {
			SimplePageQuestionAnswer newAnswer = new SimplePageQuestionAnswerImpl(answerId,(String)answer.get("text"), (Boolean) answer.get("correct"));
			return newAnswer;
		    }
		}
		return null;
	}

	public SimplePageQuestionResponse findQuestionResponse(long questionId, String userId) {
        DetachedCriteria d = DetachedCriteria.forClass(SimplePageQuestionResponse.class).add(Restrictions.eq("questionId", questionId))
        		.add(Restrictions.eq("userId", userId));

        List<SimplePageQuestionResponse> list = getHibernateTemplate().findByCriteria(d);
        if(list != null && list.size() > 0) {
        	return list.get(0);
        }else {
        	return null;
        }
	}

	public SimplePageQuestionResponse findQuestionResponse(long responseId) {
        DetachedCriteria d = DetachedCriteria.forClass(SimplePageQuestionResponse.class).add(Restrictions.eq("id", responseId));

        List<SimplePageQuestionResponse> list = getHibernateTemplate().findByCriteria(d);
        if(list != null && list.size() > 0) {
        	return list.get(0);
        }else {
        	return null;
        }
	}

	public List<SimplePageQuestionResponse> findQuestionResponses(long questionId) {
        DetachedCriteria d = DetachedCriteria.forClass(SimplePageQuestionResponse.class).add(Restrictions.eq("questionId", questionId));

        List<SimplePageQuestionResponse> list = getHibernateTemplate().findByCriteria(d);
        return list;
	}

	public void getCause(Throwable t, List<String>elist) {
		while (t.getCause() != null) {
			t = t.getCause();
		}
		log.warn("error saving or updating: " + t.toString());
		elist.add(t.getLocalizedMessage());
	}

	public boolean saveItem(Object o, List<String>elist, String nowriteerr, boolean requiresEditPermission) {

		/*
		 * This checks a lot of conditions:
		 * 1) If o is SimplePageItem or SimplePage, it makes sure it gets the right page and checks the
		 *    permissions on it.
		 * 2) If it's a log entry or question response, it lets it go.
		 * 3) If requiresEditPermission is set to false, it lets it go.
		 *
		 * Essentially, if any of those say that the edit is fine, it won't throw the error.
		 */
	    if(requiresEditPermission && !(o instanceof SimplePageItem && canEditPage(((SimplePageItem)o).getPageId()))
	    			&& !(o instanceof SimplePage && canEditPage((SimplePage)o))
				&& !(o instanceof SimplePageLogEntry || o instanceof SimplePageQuestionResponse)
				&& !(o instanceof SimplePageGroup)) {
			elist.add(nowriteerr);
			return false;
		}

		try {
		    getHibernateTemplate().save(o);

		    if (o instanceof SimplePageItem) {
			SimplePageItem i = (SimplePageItem)o;
			EventTrackingService.post(EventTrackingService.newEvent("lessonbuilder.create", "/lessonbuilder/item/" + i.getId(), true));
		    } else if (o instanceof SimplePage) {
			SimplePage i = (SimplePage)o;
			EventTrackingService.post(EventTrackingService.newEvent("lessonbuilder.create", "/lessonbuilder/page/" + i.getPageId(), true));
		    }

		    if(o instanceof SimplePageItem || o instanceof SimplePage) {
		    	updateStudentPage(o);
		    }

		    return true;
		} catch (org.springframework.dao.DataIntegrityViolationException e) {
		    getCause(e, elist);
		    return false;
		} catch (org.hibernate.exception.DataException e) {
		    getCause(e, elist);
		    return false;
		} catch (DataAccessException e) {
		    getCause(e, elist);
		    return false;
		}
	}

    // for use within copytransfer. We don't need to do permissions, and it probably
    // doesn't make sense to log every item created
	public boolean quickSaveItem(Object o) {
		try {
			Object id = getHibernateTemplate().save(o);
			return true;
		} catch (DataAccessException e) {
			e.printStackTrace();
			log.warn("Hibernate could not save: " + e.toString());
			return false;
		}
	}

	public boolean deleteItem(Object o) {
		/*
		 * If o is SimplePageItem or SimplePage, it makes sure it gets the right page and checks the
		 * permissions on it. If the item isn't SimplePageItem or SimplePage, it lets it go.
		 *
		 * Essentially, if any of those say that the edit is fine, it won't throw the error.
		 */
		if(!(o instanceof SimplePageItem && canEditPage(((SimplePageItem)o).getPageId()))
				&& !(o instanceof SimplePage && canEditPage((SimplePage)o))
				&& (o instanceof SimplePage || o instanceof SimplePageItem)) {
			return false;
		}

		if (o instanceof SimplePageItem) {
		    SimplePageItem i = (SimplePageItem)o;
		    EventTrackingService.post(EventTrackingService.newEvent("lessonbuilder.delete", "/lessonbuilder/item/" + i.getId(), true));
		} else if (o instanceof SimplePage) {
		    SimplePage i = (SimplePage)o;
		    EventTrackingService.post(EventTrackingService.newEvent("lessonbuilder.delete", "/lessonbuilder/page/" + i.getPageId(), true));
		} else if(o instanceof SimplePageComment) {
			SimplePageComment i = (SimplePageComment) o;
			EventTrackingService.post(EventTrackingService.newEvent("lessonbuilder.delete", "/lessonbuilder/comment/" + i.getId(), true));
		}

		try {
			getHibernateTemplate().delete(o);
			return true;
		} catch (DataAccessException e) {
			try {

				/* If we have multiple objects of the same item, you must merge them
				 * before deleting.  If the first delete fails, we merge and try again.
				 */
				getHibernateTemplate().delete(getHibernateTemplate().merge(o));

				return true;
			}catch(DataAccessException ex) {
				ex.printStackTrace();
				log.warn("Hibernate could not delete: " + e.toString());
				return false;
			}
		}
	}

	public boolean update(Object o, List<String>elist, String nowriteerr, boolean requiresEditPermission) {
		/*
		 * This checks a lot of conditions:
		 * 1) If o is SimplePageItem or SimplePage, it makes sure it gets the right page and checks the
		 *    permissions on it.
		 * 2) If it's a log entry, it lets it go.
		 * 3) If requiresEditPermission is set to false, it lets it go.
		 *
		 * Essentially, if any of those say that the edit is fine, it won't throw the error.
		 */
		if(requiresEditPermission && !(o instanceof SimplePageItem && canEditPage(((SimplePageItem)o).getPageId()))
				&& !(o instanceof SimplePage && canEditPage((SimplePage)o))
		   		&& !(o instanceof SimplePageLogEntry || o instanceof SimplePageQuestionResponse)
				&& !(o instanceof SimplePageGroup)) {
			elist.add(nowriteerr);
			return false;
		}

		if (o instanceof SimplePageItem) {
		    SimplePageItem i = (SimplePageItem)o;
		    EventTrackingService.post(EventTrackingService.newEvent("lessonbuilder.update", "/lessonbuilder/item/" + i.getId(), true));
		} else if (o instanceof SimplePage) {
		    SimplePage i = (SimplePage)o;
		    EventTrackingService.post(EventTrackingService.newEvent("lessonbuilder.update", "/lessonbuilder/page/" + i.getPageId(), true));
		}

		try {
			if(!(o instanceof SimplePageLogEntry)) {
				getHibernateTemplate().merge(o);
			}else {
				// Updating seems to always update the timestamp on the log correctly,
				// while merging doesn't always get it right.  However, it's possible that
				// update will fail, so we do both, in order of preference.
				try {
					getHibernateTemplate().update(o);
				}catch(DataAccessException ex) {
					log.warn("Wasn't able to update log entry, timing might be a bit off.");
					getHibernateTemplate().merge(o);
				}
			}

		    if(o instanceof SimplePageItem || o instanceof SimplePage) {
		    	updateStudentPage(o);
		    }

		    return true;
		} catch (org.springframework.dao.DataIntegrityViolationException e) {
		    getCause(e, elist);
		    return false;
		} catch (org.hibernate.exception.DataException e) {
		    getCause(e, elist);
		    return false;
		} catch (DataAccessException e) {
		    getCause(e, elist);
		    return false;
		}
	}

    // ditto for update
	public boolean quickUpdate(Object o) {
		try {
			getHibernateTemplate().merge(o);
			return true;
		} catch (DataAccessException e) {
			e.printStackTrace();
			return false;
		}
	}

	public Long getTopLevelPageId(String toolId) {
		DetachedCriteria d = DetachedCriteria.forClass(SimplePage.class).add(Restrictions.eq("toolId", toolId)).add(Restrictions.isNull("parent"));

		List list = getHibernateTemplate().findByCriteria(d);

		if (list.size() > 1) {
			log.warn("Problem finding which page we should be on.  Doing the best we can.");
		}

		if (list != null && list.size() > 0) {
			return ((SimplePage) list.get(0)).getPageId();
		} else {
			return null;
		}
	}

	public SimplePage getPage(long pageId) {
		DetachedCriteria d = DetachedCriteria.forClass(SimplePage.class).add(Restrictions.eq("pageId", pageId));

		List l = getHibernateTemplate().findByCriteria(d);

		if (l != null && l.size() > 0) {
			return (SimplePage) l.get(0);
		} else {
			return null;
		}
	}

	public List<SimplePage> getSitePages(String siteId) {
	    DetachedCriteria d = DetachedCriteria.forClass(SimplePage.class).add(Restrictions.eq("siteId", siteId)).add(Restrictions.isNull("owner"));

		List<SimplePage> l = getHibernateTemplate().findByCriteria(d);

		if (l != null && l.size() > 0) {
		    return l;
		} else {
		    return null;
		}
	}

	public SimplePageLogEntry getLogEntry(String userId, long itemId, Long studentPageId) {
		if(studentPageId.equals(-1L)) studentPageId = null;

		DetachedCriteria d = DetachedCriteria.forClass(SimplePageLogEntry.class).add(Restrictions.eq("userId", userId))
				.add(Restrictions.eq("itemId", itemId));

		if(studentPageId != null) {
			d.add(Restrictions.eq("studentPageId", studentPageId));
		}else {
			d.add(Restrictions.isNull("studentPageId"));
		}

		List l = getHibernateTemplate().findByCriteria(d);

		if (l != null && l.size() > 0) {
			return (SimplePageLogEntry) l.get(0);
		} else {
			return null;
		}
	}

	// owner not currently used. would need group as well
        public boolean isPageVisited(long pageId, String userId, String owner) {
	    // if this is a student page, it's most likely the top level, so do that query first
	    if (owner != null) {
		Object [] fields = new Object[3];
		fields[0] = pageId;
		fields[1] = pageId;
		fields[2] = userId;
		List<String> ones = sqlService.dbRead("select 1 from lesson_builder_student_pages a, lesson_builder_log b where a.pageId=? and a.itemId = b.itemId and b.studentPageId=? and b.userId=?", fields, null);
		if (ones != null && ones.size() > 0)
		    return true;
	    }

	    Object [] fields = new Object[2];
	    fields[0] = Long.toString(pageId);
	    fields[1] = userId;
	    List<String> ones = sqlService.dbRead("select 1 from lesson_builder_items a, lesson_builder_log b where a.sakaiId=? and a.type=2 and a.id=b.itemId and b.userId=?", fields, null);
	    if (ones != null && ones.size() > 0)
		return true;
	    else
		return false;
	}

	public List<SimplePageLogEntry> getStudentPageLogEntries(long itemId, String userId) {
		DetachedCriteria d = DetachedCriteria.forClass(SimplePageLogEntry.class).add(Restrictions.eq("userId", userId))
				.add(Restrictions.eq("itemId", itemId))
				.add(Restrictions.isNotNull("studentPageId"));

		List<SimplePageLogEntry> entries = getHibernateTemplate().findByCriteria(d);

		return entries;
	}

	public List<String> findUserWithCompletePages(Long itemId){
		Object [] fields = new Object[1];
		fields[0] = itemId;

		List<String> users = sqlService.dbRead("select a.userId from lesson_builder_log a where a.itemId = ? and a.complete = true", fields, null);

		return users;
	}

	public SimplePageGroup findGroup(String itemId) {
		DetachedCriteria d = DetachedCriteria.forClass(SimplePageGroup.class).add(Restrictions.eq("itemId", itemId));

		List l = getHibernateTemplate().findByCriteria(d);

		if (l != null && l.size() > 0) {
			return (SimplePageGroup) l.get(0);
		} else {
			return null;
		}
	}

	public SimplePage makePage(String toolId, String siteId, String title, Long parent, Long topParent) {
		return new SimplePageImpl(toolId, siteId, title, parent, topParent);
	}

	public SimplePageItem makeItem(long id, long pageId, int sequence, int type, String sakaiId, String name) {
		return new SimplePageItemImpl(id, pageId, sequence, type, sakaiId, name);
	}

	public SimplePageItem makeItem(long pageId, int sequence, int type, String sakaiId, String name) {
		return new SimplePageItemImpl(pageId, sequence, type, sakaiId, name);
	}

	public SimplePageGroup makeGroup(String itemId, String groupId, String groups, String siteId) {
		return new SimplePageGroupImpl(itemId, groupId, groups, siteId);
	}

	public SimplePageQuestionResponse makeQuestionResponse(String userId, long questionId) {
		return new SimplePageQuestionResponseImpl(userId, questionId);
	}

	public SimplePageLogEntry makeLogEntry(String userId, long itemId, Long studentPageId) {
		return new SimplePageLogEntryImpl(userId, itemId, studentPageId);
	}

	public SimplePageComment makeComment(long itemId, long pageId, String author, String comment, String UUID, boolean html) {
		return new SimplePageCommentImpl(itemId, pageId, author, comment, UUID, html);
	}

	public SimpleStudentPage makeStudentPage(long itemId, long pageId, String title, String author, String group) {
		return new SimpleStudentPageImpl(itemId, pageId, title, author, group);
	}

    // answer is stored as id [int], text, correct [boolean]

	public SimplePageQuestionAnswer makeQuestionAnswer(String text, boolean correct) {
		return new SimplePageQuestionAnswerImpl(0, text, correct);
	}

    // only implemented for existing questions, i.e. questions with id numbers
	public boolean deleteQuestionAnswer(SimplePageQuestionAnswer questionAnswer, SimplePageItem question) {
		if(!canEditPage(question.getPageId())) {
		    log.warn("User tried to edit question on page without edit permission. PageId: " + question.getPageId());
		    return false;
		}

		// getId returns long, so this can never be null
		Long delid = questionAnswer.getId();

		// find new id number, max + 1
		// JSON uses Long for integer values
		List answers = (List)question.getJsonAttribute("answers");
		Long max = -1L;
		if (answers == null)
		    return false;
		for (Object a: answers) {
		    Map answer = (Map) a;
		    if (delid.equals(answer.get("id"))) {
			answers.remove(a);
			return true;
		    }
		}

		return false;
	}

       // methods above are historical. I leave them for completeness. THere are the ones actually used:

	public void clearQuestionAnswers(SimplePageItem question) {
		question.setJsonAttribute("answers", null);
	}

	public Long maxQuestionAnswer(SimplePageItem question)  {
		Long max = 0L;
		List answers = (List)question.getJsonAttribute("answers");
		if (answers == null)
		    return max;
		for (Object a: answers) {
		    Map answer = (Map) a;
		    Long i = (Long)answer.get("id");
		    if (i > max)
			max = i;
		}
		return max;
	}

	public Long addQuestionAnswer(SimplePageItem question, Long id, String text, Boolean isCorrect) {
		// no need to check security. that happens when item is saved

		List answers = (List)question.getJsonAttribute("answers");
		if (answers == null) {
		    answers = new JSONArray();
		    question.setJsonAttribute("answers", answers);
		    if (id <= 0L)
			id = 1L;
		} else if (id <= 0L) {
		    Long max = 0L;
		    for (Object a: answers) {
			Map answer = (Map) a;
			Long i = (Long)answer.get("id");
			if (i > max)
			    max = i;
		    }
		    id = max + 1;
		}

		// create and add the json form of the answer
		Map newAnswer = new JSONObject();
		newAnswer.put("id", id);
		newAnswer.put("text", text);
		newAnswer.put("correct", isCorrect);
		answers.add(newAnswer);

		return id;
	}

	public void clearPeerEvalRows(SimplePageItem question) {
		question.setJsonAttribute("rows", null);
	}

	public Long maxPeerEvalRow(SimplePageItem question)  {
		Long max = 0L;
		List rows = (List)question.getJsonAttribute("rows");
		if (rows == null)
		    return max;
		for (Object a: rows) {
		    Map row = (Map) a;
		    Long i = (Long)row.get("id");
		    if (i > max)
			max = i;
		}
		return max;
	}

	public void addPeerEvalRow(SimplePageItem question, Long id, String text) {
		// no need to check security. that happens when item is saved

		List rows = (List)question.getJsonAttribute("rows");
		if (rows == null) {
		  	rows = new JSONArray();
		    question.setJsonAttribute("rows", rows);
		    if(id <= 0L)
		    	id = 1L;
		    }else if (id <= 0L) {
		    	Long max = 0L;
		    	for (Object r: rows) {
		    		Map row =(Map) r;
		    		Long i = (Long)row.get("id");
		    		if(i > max)
		    			max = i;
		    	}
		    	id = max +1;
		    }
		Map newRow = new JSONObject();
		newRow.put("id", id);
		newRow.put("rowText",text);
		rows.add(newRow);

	}

	public SimplePageItem copyItem(SimplePageItem old) {
		SimplePageItem item =  new SimplePageItemImpl();
		item.setPageId(old.getPageId());
		item.setSequence(old.getSequence());
		item.setType(old.getType());
		item.setSakaiId(old.getSakaiId());
		item.setName(old.getName());
		item.setHtml(old.getHtml());
		item.setDescription(old.getDescription());
		item.setHeight(old.getHeight());
		item.setWidth(old.getWidth());
		item.setAlt(old.getAlt());
		item.setNextPage(old.getNextPage());
		item.setFormat(old.getFormat());
		item.setRequired(old.isRequired());
		item.setAlternate(old.isAlternate());
		item.setPrerequisite(old.isPrerequisite());
		item.setSubrequirement(old.getSubrequirement());
		item.setRequirementText(old.getRequirementText());
		item.setSameWindow(old.isSameWindow());
		item.setAnonymous(old.isAnonymous());
		item.setShowComments(old.getShowComments());
		item.setForcedCommentsAnonymous(old.getForcedCommentsAnonymous());
		item.setAttributeString(old.getAttributeString()); // copy via json
		item.setShowPeerEval(old.getShowPeerEval());

		//		Map<String, SimplePageItemAttributeImpl> attrs = ((SimplePageItemImpl)old).getAttributes();
		//		if (attrs != null) {
		//		    Collection<SimplePageItemAttributeImpl> attributes = attrs.values();
		//		    if (attributes.size() > 0) {
		//			for (SimplePageItemAttributeImpl attr: attributes) {
		//			    item.setAttribute(attr.getAttr(), attr.getValue());
		//}
		//		    }
		//		}

		return item;
	}

    // phase 2 of copy after save, we need item number here
	public SimplePageItem copyItem2(SimplePageItem old, SimplePageItem item) {

		syncQRTotals(item);

		return item;
	}

	private void updateStudentPage(Object o) {
		SimplePage page;

		if(o instanceof SimplePageItem) {
			SimplePageItem item = (SimplePageItem) o;
			page = getPage(item.getPageId());
		}else if(o instanceof SimplePage) {
			page = (SimplePage) o;
		}else {
			return;
		}

		if(page != null && page.getTopParent() != null) {
			SimpleStudentPage studentPage = findStudentPage(page.getTopParent());
			if(studentPage != null) {
				studentPage.setLastUpdated(new Date());
				quickUpdate(studentPage);
			}
		}
	}

	public Map JSONParse(String s) {
	    return (JSONObject)JSONValue.parse(s);
	}

	public Map newJSONObject() {
	    return new JSONObject();
	}

	public List newJSONArray() {
	    return new JSONArray();
	}

	public SimplePageQuestionResponseTotals makeQRTotals(long qid, long rid) {
	    return new SimplePageQuestionResponseTotalsImpl(qid, rid);
	}

	public List<SimplePageQuestionResponseTotals> findQRTotals(long questionId) {
		DetachedCriteria d = DetachedCriteria.forClass(SimplePageQuestionResponseTotals.class).add(Restrictions.eq("questionId", questionId));
		List<SimplePageQuestionResponseTotals> list = getHibernateTemplate().findByCriteria(d);

		return list;
	}

	public void incrementQRCount(long questionId, long responseId) {
	    Object [] fields = new Object[2];
	    fields[0] = questionId;
	    fields[1] = responseId;
	    sqlService.dbWrite("update lesson_builder_qr_totals set respcount = respcount + 1 where questionId = ? and responseId = ?", fields);
	}

	public void syncQRTotals(SimplePageItem item) {
	    if (item.getType() != SimplePageItem.QUESTION || ! "multipleChoice".equals(item.getAttribute("questionType")))
		return;

	    Map<Long, SimplePageQuestionResponseTotals> oldTotals = new HashMap<Long, SimplePageQuestionResponseTotals>();
	    List<SimplePageQuestionResponseTotals> oldQrTotals = findQRTotals(item.getId());
	    for (SimplePageQuestionResponseTotals total: oldQrTotals)
		oldTotals.put(total.getResponseId(), total);

	    for (SimplePageQuestionAnswer answer: findAnswerChoices(item)) {
		Long id = answer.getId();
		if (oldTotals.get(id) != null)
		    oldTotals.remove(id);  // in both old and new, done with it
		else {
		    // in new but not old, add it
		    SimplePageQuestionResponseTotals total = makeQRTotals(item.getId(), id);
		    quickSaveItem(total);
		}
	    }

	    // entries that were in old list but not new one, remove them
	    for (Long rid: oldTotals.keySet()) {
		deleteItem(oldTotals.get(rid));
	    }
	}

	public SimplePagePeerEval findPeerEval(long itemId) {
		SimplePageItem item = findItem(itemId);

		List rows = (List)item.getJsonAttribute("rows");
		if (rows == null)
		    return null;
		for (Object a: rows) {
		    Map row = (Map) a;
		}
		return null;
	}

	public List<SimplePagePeerEvalResult> findPeerEvalResult(long pageId,String userId,String gradee)
	 //List<String> ids = sqlService.dbRead("select b.id from lesson_builder_pages a,lesson_builder_items b where a.siteId = ? and a.pageId = b.pageId and b.sakaiId = '/dummy'", fields, null);
	{
		DetachedCriteria d = DetachedCriteria.forClass(SimplePagePeerEvalResult.class)
			    .add(Restrictions.eq("pageId", pageId))
			    .add(Restrictions.eq("grader", userId))
			    .add(Restrictions.eq("gradee", gradee));

			List<SimplePagePeerEvalResult> list = getHibernateTemplate().findByCriteria(d);
			List<SimplePagePeerEvalResult> newList= new ArrayList<SimplePagePeerEvalResult>();

			for(SimplePagePeerEvalResult eval: list){
				if(eval.getSelected())
					newList.add(eval);
			}

			return newList;
	}

	public SimplePagePeerEvalResult makePeerEvalResult(long pageId, String gradee,String grader, String rowText, int columnValue){
		return new SimplePagePeerEvalResultImpl(pageId, gradee, grader, rowText, columnValue);
	}

	public List<SimplePagePeerEvalResult> findPeerEvalResultByOwner(long pageId,String pageOwner){
		DetachedCriteria d = DetachedCriteria.forClass(SimplePagePeerEvalResult.class)
			    .add(Restrictions.eq("pageId", pageId))
			    .add(Restrictions.eq("gradee", pageOwner));

		List<SimplePagePeerEvalResult> list = getHibernateTemplate().findByCriteria(d);
		List<SimplePagePeerEvalResult> newList= new ArrayList<SimplePagePeerEvalResult>();

		for(SimplePagePeerEvalResult eval: list){
			if(eval.getSelected())
				newList.add(eval);
		}

		return newList;
	}

	public List<SimplePageItem>findGradebookItems(final String gradebookUid) {

	    String hql = "select item from org.sakaiproject.lessonbuildertool.SimplePageItem item, org.sakaiproject.lessonbuildertool.SimplePage page where item.pageId = page.pageId and page.siteId = :site and (item.gradebookId is not null or item.altGradebook is not null)";
	    return getHibernateTemplate().findByNamedParam(hql, "site", gradebookUid);
	}

	public List<SimplePage>findGradebookPages(final String gradebookUid) {

	    String hql = "select page from org.sakaiproject.lessonbuildertool.SimplePage page where page.siteId = :site and (page.gradebookPoints is not null)";
	    return getHibernateTemplate().findByNamedParam(hql, "site", gradebookUid);
	}

	// items in lesson_builder_groups for specified site, map of itemId to groups
	public Map<String,String> getExternalAssigns(String siteId) {

	    DetachedCriteria d = DetachedCriteria.forClass(SimplePageGroup.class)
		.add(Restrictions.eq("siteId", siteId));

	    List<SimplePageGroup> list = getHibernateTemplate().findByCriteria(d);

	    Map<String,String>ret = new HashMap<String,String>();
	    for (SimplePageGroup group: list)
		ret.put(group.getItemId(), group.getGroups());

	    return ret;

	}

    // return 1 if we found something, 0 if not
    // this is only going to find something once per site, typically.
    // so it's best to optimize for the normal case that nothing is there
    // initialy this called
    // dbWriteCount("delete from SAKAI_SITE_PROPERTY where SITE_ID=? and NAME='lessonbuilder-needsfixup'", fields, null, null, false);
    // but that doesn't exist in 2.8.

	public int clearNeedsFixup(String siteId) {
	    Object [] fields = new Object[1];
	    fields[0] = siteId;

	    List<String> needsList = sqlService.dbRead("select VALUE from SAKAI_SITE_PROPERTY where SITE_ID=? and NAME='lessonbuilder-needsfixup'", fields, null);

	    // normal case -- no flag
	    if (needsList == null || needsList.size() == 0)
		return 0;

	    // there is a flag, do something more carefully avoiding race conditions
	    //   There is a possible timing issue if someone copies data into the site after the
	    // last test. If so, we'll get it next time someone uses the site.
	    // we need to be provably sure that if the flag is set, this code returns 1 exactly once.
	    // I believe that is the case.

	    int retval = 0;
	    Connection conn = null;
	    boolean wasCommit = true;

	    try {
		conn = sqlService.borrowConnection();
		needsList = sqlService.dbRead(conn, "select VALUE from SAKAI_SITE_PROPERTY where SITE_ID=? and NAME='lessonbuilder-needsfixup' for update", fields, null);
		wasCommit = conn.getAutoCommit();
		conn.setAutoCommit(false);

		if (needsList != null && needsList.size() > 0) {
		    retval = 1;
		    sqlService.dbWrite(conn, "delete from SAKAI_SITE_PROPERTY where SITE_ID=? and NAME='lessonbuilder-needsfixup'", fields);
		}

		conn.commit();

	// I don't think we need to handle errrors explicitly. They will result in
	// returning 0, which is about the best we can do
	    } catch (Exception e) {
	    } finally {

		if (conn != null) {

		    try {
			conn.setAutoCommit(wasCommit);
		    } catch (Exception e) {
			System.out.println("transact: (setAutoCommit): " + e);
		    }

		    sqlService.returnConnection(conn);
		}

	    }

	    return retval;

	}

}


text:
<?php

namespace SurveyGizmo\Helper;

use SurveyGizmo\SurveyGizmoCore;
use \Exception;

class Question extends SurveyGizmoCore
{
	/**
	 * Custom Survey Id
	 * @var string
	 */
	protected $surveyId;

	/**
	 * Response constructor
	 * @param string $surveyId Custom survey id
	 */
	public function __construct($surveyId = null)
	{
		parent::__construct();

		if (is_null($surveyId) == false) {
			$this->surveyId = $surveyId;
		} else {
			$this->surveyId = $this->getSurveyId();
		}
	}

	/**
	 * Getting the survey
	 * @return object
	 */
	public function survey()
	{
		$surveyUrl = '/survey/' . $this->surveyId;

		$response = $this->sendRequest($surveyUrl);

		if (is_null($response)) {
			throw new Exception("Error getting survey", 1);
		}

		return $response;
	}

	/**
	 * Getting an specific question
	 * @param  integer $questionId
	 * @return object
	 */
	public function question($questionId)
	{
		$questionUrl = '/survey/' . $this->surveyId . '/surveyquestion/' . $questionId;

		$response = $this->sendRequest($questionUrl);

		if (is_null($response)) {
			throw new Exception("Error getting question", 1);
		}

		return $response;
	}
}


text:
{-# LANGUAGE OverloadedStrings #-}

module Answer (answer) where
{-
This  module connects to a Database to find the answer.
-}
import Database.MySQL.Simple

answer :: IO Int
answer = do
  conn <- connect defaultConnectInfo
  [Only i] <- query_ conn "select 21 * 2"
  return i


text:
package me.welcomer.framework.pico.service

import scala.concurrent.duration._
import scala.language.postfixOps
import akka.actor.ActorSystem
import akka.util.Timeout
import me.welcomer.link.mandrill.MandrillRepository
import me.welcomer.link.mandrill.MandrillRepositoryComponent
import me.welcomer.link.RawJsonApi

trait PicoLinkServiceComponent { self: MandrillRepositoryComponent =>
  protected def _picoLinkService(picoUUID: String)(implicit system: ActorSystem): PicoLinkService

  trait PicoLinkService {
    implicit val system: ActorSystem
    implicit val picoUUID: String

    def mandrill(key: String)(implicit timeout: Timeout = 5 seconds): MandrillRepository

    def rawJsonApi(implicit timeout: Timeout = 5 seconds): RawJsonApi
  }
}

trait PicoLinkServiceComponentImpl extends PicoLinkServiceComponent { self: MandrillRepositoryComponent =>
  override protected def _picoLinkService(picoUUID: String)(implicit system: ActorSystem): PicoLinkService = new PicoLinkServiceImpl()(system, picoUUID)

  private[this] class PicoLinkServiceImpl(implicit val system: ActorSystem, val picoUUID: String) extends PicoLinkService {

    override def mandrill(key: String)(implicit timeout: Timeout = 5 seconds): MandrillRepository = {
      _mandrillRepository(key)
    }

    override def rawJsonApi(implicit timeout: Timeout = 5 seconds): RawJsonApi = new RawJsonApi
  }
}


text:
var inherit = function (d, b) {
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
    return d;
};

var bind = function (f, o) {
    return function () { return f.apply(o, arguments); };
};

var makeClass = function (constructor, fields, statics, base) {
    var result = inherit(constructor, base || Object), p;
    _.each(fields, function (value, key) { result.prototype[key] = value; });
    _.each(statics, function (value, key) { result[key] = value; });
    if (base) result.prototype.base = base.prototype;
    result.prototype.self = result;
    result.prototype.callBase = function (func, args) {
        base.prototype[func].apply(this, args);
    };
    return result;
};

var funcall = function (f) { return f(); };


text:
class CPDF_RenderOptions {
 public:
  enum Type : uint8_t { kNormal = 0, kGray, kAlpha, kForcedColor };

  enum RenderType : uint8_t { kFill = 0, kStroke };

  struct Options {
    Options();
    Options(const Options& rhs);

    bool bClearType = false;
    bool bPrintGraphicText = false;
    bool bPrintPreview = false;
    bool bBGRStripe = false;
    bool bNoNativeText = false;
    bool bForceHalftone = false;
    bool bRectAA = false;
    bool bFillFullcover = false;
    bool bPrintImageText = false;
    bool bOverprint = false;
    bool bThinLine = false;
    bool bBreakForMasks = false;
    bool bNoTextSmooth = false;
    bool bNoPathSmooth = false;
    bool bNoImageSmooth = false;
    bool bLimitedImageCache = false;
    bool bConvertFillToStroke = false;
  };

  struct ColorScheme {
    FX_ARGB path_fill_color;
    FX_ARGB path_stroke_color;
    FX_ARGB text_fill_color;
    FX_ARGB text_stroke_color;
  };

  CPDF_RenderOptions();
  CPDF_RenderOptions(const CPDF_RenderOptions& rhs);
  ~CPDF_RenderOptions();

  FX_ARGB TranslateColor(FX_ARGB argb) const;
  FX_ARGB TranslateObjectColor(FX_ARGB argb,
                               CPDF_PageObject::Type object_type,
                               RenderType render_type) const;

  void SetColorScheme(const ColorScheme& color_scheme) {
    m_ColorScheme = color_scheme;
  }

  void SetColorMode(Type mode) { m_ColorMode = mode; }
  bool ColorModeIs(Type mode) const { return m_ColorMode == mode; }

  const Options& GetOptions() const { return m_Options; }
  Options& GetOptions() { return m_Options; }

  uint32_t GetCacheSizeLimit() const;

  void SetDrawAnnots(bool draw) { m_bDrawAnnots = draw; }
  bool GetDrawAnnots() const { return m_bDrawAnnots; }

  void SetOCContext(RetainPtr<CPDF_OCContext> context) {
    m_pOCContext = context;
  }
  const CPDF_OCContext* GetOCContext() const { return m_pOCContext.Get(); }

 private:
  Type m_ColorMode = kNormal;
  bool m_bDrawAnnots = false;
  Options m_Options;
  ColorScheme m_ColorScheme;
  RetainPtr<CPDF_OCContext> m_pOCContext;
};

#endif  // CORE_FPDFAPI_RENDER_CPDF_RENDEROPTIONS_H_


text:
<?php

namespace Mollie\API\Resource\Payment;

use Mollie\API\Mollie;
use Mollie\API\Resource\Base\PaymentResourceBase;
use Mollie\API\Model\Payment;
use Mollie\API\Model\Refund;

class RefundResource extends PaymentResourceBase
{
    /**
     * Payment refund resource constructor
     *
     * @param Mollie $api API reference
     * @param Payment|string $payment
     * @param Refund|string $refund
     */
    public function __construct(Mollie $api, $payment, $refund = null)
    {
        parent::__construct($api, $payment);

        if (isset($refund)) {
            $this->refund = $this->getRefundID($refund);
        }
    }

    /**
     * Get payment refund
     *
     * @param Refund|string $refundId
     * @return Refund
     */
    public function get($refundId = null)
    {
        // Get refund ID
        $refundId = $this->getRefundID($refundId);

        // Get refund
        $resp = $this->api->request->get("/payments/{$this->payment}/refunds/{$refundId}");

        // Return refund model
        return new Refund($this->api, $resp);
    }

    /**
     * Get all payment refunds
     * @return Refund[]
     */
    public function all()
    {
        $items = array();

        // API request
        $resp = $this->api->request->getAll("/payments/{$this->payment}/refunds");

        foreach ($resp as $item) {
            $items[] = new Refund($this->api, $item);
        }

        return $items;
    }

    /**
     * Create payment refund
     *
     * @see https://www.mollie.com/nl/docs/reference/refunds/create
     * @param double $amount The amount in EURO that you want to refund. Omit to refund full amount
     * @return Refund
     */
    public function create($amount = null)
    {
        // API request
        $resp = $this->api->request->post("/payments/{$this->payment}/refunds", array(
            'amount'        => $amount
        ));

        // Return refund model
        return new Refund($this->api, $resp);
    }

    /**
     * Cancel payment refund
     *
     * @see https://www.mollie.com/nl/docs/reference/refunds/delete
     * @param Refund|string $refundId
     */
    public function cancel($refundId = null)
    {
        // Get refund ID
        $refundId = $this->getRefundID($refundId);

        // API request
        $this->api->request->delete("/payments/{$this->payment}/refunds/{$refundId}");
    }
}


text:
package org.compass.annotations.test.dynamic.jexl;

import java.util.Calendar;

import org.compass.annotations.test.AbstractAnnotationsTestCase;
import org.compass.core.CompassSession;
import org.compass.core.CompassTransaction;
import org.compass.core.Resource;
import org.compass.core.config.CompassConfiguration;

/**
 * @author kimchy
 */
public class JexlDynamicTests extends AbstractAnnotationsTestCase {

    protected void addExtraConf(CompassConfiguration conf) {
        conf.addClass(A.class);
    }

    public void testSimpleExpression() throws Exception {
        CompassSession session = openSession();
        CompassTransaction tr = session.beginTransaction();

        A a = new A();
        a.setId(1);
        a.setValue("value");
        a.setValue2("value2");
        Calendar cal = Calendar.getInstance();
        cal.set(1977, 4, 1);
        a.setDate(cal.getTime());
        session.save(a);

        Resource resource = session.loadResource(A.class, 1);
        assertEquals("valuevalue2", resource.getValue("test"));
        assertEquals("value", resource.getValue("test2"));
        assertEquals("1977", resource.getValue("date"));

        tr.commit();
        session.close();
    }
}


text:
Provider
========

Common interfaces `ProviderInterface` and `ConsumerInterface` for inverting
control of configuration. This allows a *consumer* to pass control to a
*provider* so that the *provider* can configure the *consumer*.

The *consumer* must implement a `register()` method and the provider must
implement a `provides()` method. An instance of *provider* is passed to
`register()`, and `register()` in turn calls `provides()`, passing an instance
of itself. This then allows the *provider* to call methods on the *consumer* and
configure as needed.

In practice, this might look like:

```php
use MattFerris\Provider\ConsumerInterface;
use MattFerris\Provider\ProviderInterface;

// service container which contains service definitions
class ServiceContainer implements ConsumerInterface
{
    public function register(ProviderInterface $provider)
    {
        $provider->provides($this);
        return $this;
    }

    ...
}

class DatabaseProvider implements ProviderInterface
{
    public function provides(ConsumerInterface $consumer)
    {
        $consumer->set('DatabaseService', $databaseServiceDefinition);
    }
}

$container = new ServiceContainer();
$container->register(new DatabaseProvider());
$db = $container->get('DatabaseService');
$db->query(...);
```

*Note*: `ProviderInterface` doesn't type-hint what kind of *consumer* it
expects. This is on purpose, as *providers* implementing the interface can then
validate the *consumer* based on what type they want. If a *consumer* isn't of
they correct type, *providers* can throw an `InvalidConsumerException`.

Taking this example further, if an application contains multiple packages that
each provide services, packages can configure their services automatically by
implementing their own *providers*.

```php
$container = new ServiceContainer();
$container
    ->register(new DatabasePackage\ServiceProvider())
    ->register(new Authentication\ServiceProvider())
    ->register(new EventDispatcher\ServiceProvider());
```


text:
<?php

namespace As3\Modlr\Exception;

/**
 * RuntimeException.
 *
 * @author Jacob Bare <jacob.bare@gmail.com>
 */
class RuntimeException extends \RuntimeException implements ExceptionInterface
{
}


text:
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def index(request):
    # return HttpResponse("
The Fett homepage
")
    fett = "The is a python varable"
    return render(request, 'fett/fett_home.html', {'fett' : fett})

def plotResults(request):
    import matplotlib
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    from matplotlib.dates import DateFormatter

    import numpy as np
    x = np.arange(0, 10, 1)
    y = np.sin(x)

    fig = Figure()
    ax=fig.add_subplot(1,1,1)

    ax.plot(x, y)

    canvas = FigureCanvas(fig)
    response = HttpResponse(content_type='image/png')

    canvas.print_png(response)
    return response


text:
#include "messageprocessor.h"
#include "byzantineauthenticationadapter.h"
#include <map>
#include <set>
#include <vector>
#include <string>
#include <iostream>
#include <cstring>
#include <cstdio>

#include <sys/stat.h>
#include <sys/types.h>
#include <zlib.h>
#include <sys/time.h>

float get_milli_seconds(struct timeval & start, struct timeval & end)
{
   return 1000.0 * ( end.tv_sec - start.tv_sec + (end.tv_usec - start.tv_usec)/1000000.0 ) ;
}

#define  MAX_NAME  1024
#define  KEYBITS   128
     /**
      * Program takes in an email trace to simulate the progress of
      * byzantine fault tolerant authentication on the work load
      *
      * Format of the email trace file:
      *     timeofmail  sizeofmail  mesgid   fromwho  towho ccwho ... \n
      *
      * Logic
      * Compute all senders and receivers and make an adapter for each.
      * Load all the messages into sequence by time.
      * Execute the work load in a synchronous manner using the
      * receive call at end of every call
      */

int linebufsize = 64*1024;

char * linebuf = new char [linebufsize];

unsigned int mintime = 0xffffffff;

struct MessageTrace
{
   std::string    from;
   std::vector<std::string>   to;
   unsigned       date;
   unsigned       size;
};

std::set<std::string>  peers;

std::map<unsigned, MessageTrace>    message_trace;

std::map<std::string, std::vector<std::string> > trustgroups;

std::map<std::string, ByzantineAuthenticationAdapter *> peer_map;

void transmit_outstanding_messages();

std::string trim(std::string who)
{
   char name[MAX_NAME];
   strcpy( name, who.c_str() ) ;

   int len = who.size();
   for( int i = 0; i < len; i++ )
      if( isupper(name[i]) )
         name[i] = tolower(name[i]) ;
   return name;
}

int get_compr_size(const std::string& mesg)
{
   uLongf destLen = (mesg.size() + 12) + (mesg.size()/4);
   Bytef *dest = new Bytef[destLen];
   const Bytef *source = (Bytef *) mesg.data();
   uLong sourceLen = mesg.size();
   int ret = 0;
   if( Z_OK != (ret = compress(dest, &destLen, source, sourceLen)))
   {
      std::cerr << "Error in compress " << ret << std::endl;
      abort() ;
   }
   delete [] dest;
   return destLen*3/2;  // for base 64 encoding
}

bool  load_trace(char * filename)
{
   FILE * fp = fopen(filename, "r");
   if(!fp)
      return false;

   std::map<std::string, int> woutcount;
   std::map<std::string, int> outcount;
   std::map<std::string, int> incount;

   const char * tb = " \t\n" ;
   while(fgets(linebuf, linebufsize, fp))
   {
      char * p = 0;
      MessageTrace curr;
      for( int tn = 0; 1; tn++)
      {
         if(!tn)
            p = strtok( linebuf , tb )  ;
         else
            p = strtok( 0, tb ) ;
         if(!p)
            break;
         switch(tn)
         {
            case 0: curr.date = atoi(p);
               if (mintime > curr.date)
                  mintime = curr.date;
               break;

            case 1: curr.size = atoi(p);
               break;

            case 2: break;

            case 3: curr.from = trim(p);
               peers.insert(curr.from);
               break;

            default:
               curr.to.push_back(trim(p));
               peers.insert(trim(p));
               break;
         }
      }
      message_trace.insert(std::make_pair(curr.date, curr));
      outcount[ curr.from ] ++ ;
      for( std::vector<std::string>::iterator i = curr.to.begin() ; i != curr.to.end() ; i++)
         incount[ *i ] ++ ;
      woutcount[curr.from] +=  curr.to.size();
   }
   return true;
}

int main(int argc, char * argv[])
{
   if( argc != 7 )
   {
      std::cout << "Usage " << argv[0] << " <bsfile> <msgtrace> <tgs> <expiryinterval> <nmespayload> <keysz> " << std::endl;
      return 1;
   }

   int tgs = atoi(argv[3]);
   int expiry = atoi(argv[4]);
   int payload = atoi(argv[5]);
   int keysize = atoi(argv[6]);

        // load all the traces
   for( int i = 2; i < argc; i++ )
      load_trace( argv[i] ) ;

        // load trusted group information
   FILE * bfp = fopen( argv[1] , "r" ) ;
   while( fgets( linebuf, linebufsize, bfp ) )
   {
      char * p = strtok( linebuf, " \t\n" ) ;
      if(p && peers.find(p) != peers.end())
      {
         std::string self = p;
         int count = 0;
         while( (p = strtok( 0, " \t\n" )) &&  peers.find(p) != peers.end() && count < atoi(argv[3]) )
         {
            count++;
            trustgroups[self].push_back(std::string(p));
         }

         if(count < 4)
            trustgroups.erase(self);
      }
   }
   std::cout << "loaded trust groups" << std::endl ;

        // erased peers who have no trust groups
   for( std::set<std::string>::iterator i = peers.begin() ; i != peers.end() ; )
   {
      std::set<std::string>::iterator j = i;
      j++;
      if( trustgroups.find(*i) == trustgroups.end() )
         peers.erase(*i);
      i = j;
   }
   std::cout << "trimmed messages in trace " << peers.size() << " peers left " << std::endl ;

        // initialize all adapters
   mkdir( "./peerdata", 0770 ) ;
   system( "rm -rf peerdata/*" ) ;

   for( std::set<std::string>::iterator i = peers.begin() ; i != peers.end() ; i++ )
   {
      ByzantineAuthenticationAdapter * adapter =
         ByzantineAuthenticationAdapter::New( "example.conf" ,
                                              atoi(argv[3]),      // trusted group size
                                              atoi(argv[4]),      // expiry interval in seconds
                                              atoi(argv[5]));     // maximum message payload i.e. how many messages to attach on outgoing

      std::string filename = *i + ".xml";
      filename = "./peerdata/" + filename;
      peerid_t me = *i;

      if(!adapter->Init(atoi(argv[6]), me, trustgroups[*i], filename.c_str(), mintime))
         return false;

      peer_map.insert( std::make_pair( *i, adapter ) ) ;
   }
   std::cout << "initialize all adapters" << std::endl ;

   float totalsendtime;

        // run the trace
   char filename[1024];
   sprintf( filename, "tgs%d.expiry%d.payload%d.data", tgs, expiry, payload ) ;

   FILE * statfp = fopen( filename, "w" ) ;
   int done = 0, max = message_trace.size();
   int percent, prevpercent = 0;
   for( std::map<unsigned, MessageTrace>::iterator i = message_trace.begin();
        i != message_trace.end() ; i++ )
   {
      done++;
      percent = int( 100.0*done/max ) ;
      if( percent != prevpercent )
      {
         std::cout << percent << " % done " << std::endl;
         prevpercent = percent;
      }
      std::cout << done << " of " << max << " done\r" << std::flush ;

      if( peer_map.find(i->second.from) == peer_map.end() )
         continue;

           // the sender
      ByzantineAuthenticationAdapter * pfrom = peer_map[i->second.from];
      pfrom->LocalTime (i->second.date) ;

           // gather message
      std::string mesg;
      std::vector<std::string> outgoingtrimmed;
      for( std::vector<std::string>::iterator j = i->second.to.begin(); j != i->second.to.end(); j++ )
         if( peer_map.find(*j) != peer_map.end() )
            outgoingtrimmed.push_back(*j) ;

      if(outgoingtrimmed.empty())
         continue;

      float sendtime, comprtime, recvtime;
      struct timeval start, end;
      gettimeofday(&start , 0);
      pfrom->SendMulti( outgoingtrimmed, mesg ) ;  // many send
      gettimeofday(&end , 0);
      totalsendtime += (sendtime = get_milli_seconds(start, end));

      gettimeofday(&start , 0);
      int overhead = get_compr_size(mesg);
      gettimeofday(&end , 0);
      comprtime = get_milli_seconds(start, end);

      unsigned int ntrusted, nknown;
      float completion = pfrom->GetCompletion(ntrusted, nknown) ;
      unsigned nmessages, nbytes;
      pfrom->GetCacheSize(nmessages, nbytes);
      fprintf( statfp, "SENDER=%s  TIME=%lu  NUMDEST=%lu OVERHEAD=%d  BASEOVERHEAD=%lu SIZE=%lu  COMPLETION=%f NTRUSTED=%u NKNOWN=%u CACHENMESG=%u CACHENBYTES=%u SNDTIME=%f COMPRTIME=%f KEYSZ=%d\n" ,
               i->second.from.c_str(),
               (unsigned long) i->second.date,
               (unsigned long) outgoingtrimmed.size(),
               overhead,
               (unsigned long)mesg.size(),
               (unsigned long)i->second.size, completion, ntrusted, nknown , nmessages, nbytes, sendtime, comprtime, keysize ) ;

           // send to each receiver
      for( std::vector<std::string>::iterator j = i->second.to.begin(); j != i->second.to.end(); j++ )
      {
         std::string pubkey;
         bool unknown;
         int trust_value;

         if( peer_map.find(*j) == peer_map.end() )
            continue;

              // already doing inside
         pfrom->GetAuthenticatedKey(*j, pubkey, trust_value, unknown);

         ByzantineAuthenticationAdapter * pto = peer_map[*j];
         pto->LocalTime(i->second.date) ;
         gettimeofday(&start , 0);
         pto->Recv( i->second.from, mesg ) ;
         gettimeofday(&end , 0);
         recvtime = get_milli_seconds(start, end);
      }
   }

        // de init all adapters
   for( std::map<std::string, ByzantineAuthenticationAdapter *>::iterator i = peer_map.begin();
        i != peer_map.end(); i++ )
   {
      i->second->DeInit();
      ByzantineAuthenticationAdapter::Delete(i->second) ;
   }

   fclose(statfp);
   return 0;
}