text:
package com.siyeh.ig.fixes;

import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiFormatUtil;
import com.intellij.psi.util.PsiUtil;
import com.siyeh.ig.psiutils.ClassUtils;
import com.siyeh.ig.psiutils.TypeUtils;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class SerialVersionUIDBuilder extends JavaRecursiveElementVisitor {

  @NonNls private static final String ACCESS_METHOD_NAME_PREFIX = "access$";

  private final PsiClass clazz;
  private int index = -1;
  private final Set<MemberSignature> nonPrivateConstructors;
  private final Set<MemberSignature> nonPrivateMethods;
  private final Set<MemberSignature> nonPrivateFields;
  private final List<MemberSignature> staticInitializers;
  private boolean assertStatement = false;
  private boolean classObjectAccessExpression = false;
  private final Map<PsiElement, String> memberMap =
    new HashMap<PsiElement, String>();

  private static final Comparator<PsiClass> INTERFACE_COMPARATOR =
    new Comparator<PsiClass>() {
      @Override
      public int compare(PsiClass object1, PsiClass object2) {
        if (object1 == null && object2 == null) {
          return 0;
        }
        if (object1 == null) {
          return 1;
        }
        if (object2 == null) {
          return -1;
        }
        final String name1 = object1.getQualifiedName();
        final String name2 = object2.getQualifiedName();
        if (name1 == null && name2 == null) {
          return 0;
        }
        if (name1 == null) {
          return 1;
        }
        if (name2 == null) {
          return -1;
        }
        return name1.compareTo(name2);
      }
    };
  @NonNls private static final String CLASS_ACCESS_METHOD_PREFIX = "class$";

  private SerialVersionUIDBuilder(PsiClass clazz) {
    super();
    this.clazz = clazz;
    nonPrivateMethods = new HashSet<MemberSignature>();
    final PsiMethod[] methods = clazz.getMethods();
    for (final PsiMethod method : methods) {
      if (!method.isConstructor() &&
          !method.hasModifierProperty(PsiModifier.PRIVATE)) {
        final MemberSignature methodSignature =
          new MemberSignature(method);
        nonPrivateMethods.add(methodSignature);
      }
    }
    nonPrivateFields = new HashSet<MemberSignature>();
    final PsiField[] fields = clazz.getFields();
    for (final PsiField field : fields) {
      if (!field.hasModifierProperty(PsiModifier.PRIVATE) ||
          !(field.hasModifierProperty(PsiModifier.STATIC) ||
            field.hasModifierProperty(PsiModifier.TRANSIENT))) {
        final MemberSignature fieldSignature =
          new MemberSignature(field);
        nonPrivateFields.add(fieldSignature);
      }
    }

    staticInitializers = new ArrayList<MemberSignature>();
    final PsiClassInitializer[] initializers = clazz.getInitializers();
    if (initializers.length > 0) {
      for (final PsiClassInitializer initializer : initializers) {
        final PsiModifierList modifierList =
          initializer.getModifierList();
        if (modifierList != null &&
            modifierList.hasModifierProperty(PsiModifier.STATIC)) {
          final MemberSignature initializerSignature =
            MemberSignature.getStaticInitializerMemberSignature();
          staticInitializers.add(initializerSignature);
          break;
        }
      }
    }
    if (staticInitializers.isEmpty()) {
      final PsiField[] psiFields = clazz.getFields();
      for (final PsiField field : psiFields) {
        if (hasStaticInitializer(field)) {
          final MemberSignature initializerSignature =
            MemberSignature.getStaticInitializerMemberSignature();
          staticInitializers.add(initializerSignature);
          break;
        }
      }
    }

    nonPrivateConstructors = new HashSet<MemberSignature>();
    final PsiMethod[] constructors = clazz.getConstructors();
    if (constructors.length == 0 && !clazz.isInterface()) {
      // generated empty constructor if no constructor is defined in the source
      final MemberSignature constructorSignature;
      if (clazz.hasModifierProperty(PsiModifier.PUBLIC)) {
        constructorSignature = MemberSignature.getPublicConstructor();
      }
      else {
        constructorSignature = MemberSignature.getPackagePrivateConstructor();
      }
      nonPrivateConstructors.add(constructorSignature);
    }
    for (final PsiMethod constructor : constructors) {
      if (!constructor.hasModifierProperty(PsiModifier.PRIVATE)) {
        final MemberSignature constructorSignature =
          new MemberSignature(constructor);
        nonPrivateConstructors.add(constructorSignature);
      }
    }
  }

  public static long computeDefaultSUID(PsiClass psiClass) {
    final Project project = psiClass.getProject();
    final GlobalSearchScope scope = GlobalSearchScope.allScope(project);
    final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
    final PsiClass serializable =
      psiFacade.findClass(CommonClassNames.JAVA_IO_SERIALIZABLE, scope);
    if (serializable == null) {
      // no jdk defined for project.
      return -1L;
    }

    final boolean isSerializable = psiClass.isInheritor(serializable, true);
    if (!isSerializable) {
      return 0L;
    }

    final SerialVersionUIDBuilder serialVersionUIDBuilder = new SerialVersionUIDBuilder(psiClass);
    try {
      final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      final DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);

      final String className = PsiFormatUtil.getExternalName(psiClass);
      dataOutputStream.writeUTF(className);

      final PsiModifierList classModifierList = psiClass.getModifierList();
      int classModifiers = classModifierList != null ? MemberSignature.calculateModifierBitmap(classModifierList) : 0;
      final MemberSignature[] methodSignatures = serialVersionUIDBuilder.getNonPrivateMethodSignatures();
      if (psiClass.isInterface()) {
        classModifiers |= Modifier.INTERFACE;
        if (methodSignatures.length == 0) {
          // interfaces were not marked abstract when they did't have methods in java 1.0
          // For serialization compatibility the abstract modifier is ignored.
          classModifiers &= ~Modifier.ABSTRACT;
        }
      }
      dataOutputStream.writeInt(classModifiers);

      final PsiClass[] interfaces = psiClass.getInterfaces();
      Arrays.sort(interfaces, INTERFACE_COMPARATOR);
      for (PsiClass aInterfaces : interfaces) {
        final String name = aInterfaces.getQualifiedName();
        dataOutputStream.writeUTF(name);
      }

      final MemberSignature[] fields = serialVersionUIDBuilder.getNonPrivateFields();
      Arrays.sort(fields);
      for (final MemberSignature field : fields) {
        dataOutputStream.writeUTF(field.getName());
        dataOutputStream.writeInt(field.getModifiers());
        dataOutputStream.writeUTF(field.getSignature());
      }

      final MemberSignature[] staticInitializers = serialVersionUIDBuilder.getStaticInitializers();
      for (final MemberSignature staticInitializer : staticInitializers) {
        dataOutputStream.writeUTF(staticInitializer.getName());
        dataOutputStream.writeInt(staticInitializer.getModifiers());
        dataOutputStream.writeUTF(staticInitializer.getSignature());
      }

      final MemberSignature[] constructors = serialVersionUIDBuilder.getNonPrivateConstructors();
      Arrays.sort(constructors);
      for (final MemberSignature constructor : constructors) {
        dataOutputStream.writeUTF(constructor.getName());
        dataOutputStream.writeInt(constructor.getModifiers());
        dataOutputStream.writeUTF(constructor.getSignature());
      }

      Arrays.sort(methodSignatures);
      for (final MemberSignature methodSignature : methodSignatures) {
        dataOutputStream.writeUTF(methodSignature.getName());
        dataOutputStream.writeInt(methodSignature.getModifiers());
        dataOutputStream.writeUTF(methodSignature.getSignature());
      }

      dataOutputStream.flush();
      @NonNls final String algorithm = "SHA";
      final MessageDigest digest = MessageDigest.getInstance(algorithm);
      final byte[] digestBytes = digest.digest(byteArrayOutputStream.toByteArray());
      long serialVersionUID = 0L;
      for (int i = Math.min(digestBytes.length, 8) - 1; i >= 0; i--) {
        serialVersionUID = serialVersionUID << 8 | digestBytes[i] & 0xFF;
      }
      return serialVersionUID;
    }
    catch (IOException exception) {
      final InternalError internalError = new InternalError(exception.getMessage());
      internalError.initCause(exception);
      throw internalError;
    }
    catch (NoSuchAlgorithmException exception) {
      final SecurityException securityException = new SecurityException(exception.getMessage());
      securityException.initCause(exception);
      throw securityException;
    }
  }

  private void createClassObjectAccessSynthetics(PsiType type) {
    if (!classObjectAccessExpression) {
      final MemberSignature syntheticMethod =
        MemberSignature.getClassAccessMethodMemberSignature();
      nonPrivateMethods.add(syntheticMethod);
    }
    PsiType unwrappedType = type;
    @NonNls final StringBuffer fieldNameBuffer;
    if (type instanceof PsiArrayType) {
      fieldNameBuffer = new StringBuffer();
      fieldNameBuffer.append("array");
      while (unwrappedType instanceof PsiArrayType) {
        final PsiArrayType arrayType = (PsiArrayType)unwrappedType;
        unwrappedType = arrayType.getComponentType();
        fieldNameBuffer.append('$');
      }
    }
    else {
      fieldNameBuffer = new StringBuffer(CLASS_ACCESS_METHOD_PREFIX);
    }
    if (unwrappedType instanceof PsiPrimitiveType) {
      final PsiPrimitiveType primitiveType = (PsiPrimitiveType)unwrappedType;
      fieldNameBuffer.append(MemberSignature.createPrimitiveType(primitiveType));
    }
    else {
      final String text = unwrappedType.getCanonicalText().replace('.',
                                                                   '$');
      fieldNameBuffer.append(text);
    }
    final String fieldName = fieldNameBuffer.toString();
    final MemberSignature memberSignature =
      new MemberSignature(fieldName, Modifier.STATIC,
                          "Ljava/lang/Class;");
    if (!nonPrivateFields.contains(memberSignature)) {
      nonPrivateFields.add(memberSignature);
    }
    classObjectAccessExpression = true;
  }

  private String getAccessMethodIndex(PsiElement element) {
    String cache = memberMap.get(element);
    if (cache == null) {
      cache = String.valueOf(index);
      index++;
      memberMap.put(element, cache);
    }
    return cache;
  }

  public MemberSignature[] getNonPrivateConstructors() {
    init();
    return nonPrivateConstructors.toArray(new MemberSignature[nonPrivateConstructors.size()]);
  }

  public MemberSignature[] getNonPrivateFields() {
    init();
    return nonPrivateFields.toArray(new MemberSignature[nonPrivateFields.size()]);
  }

  public MemberSignature[] getNonPrivateMethodSignatures() {
    init();
    return nonPrivateMethods.toArray(new MemberSignature[nonPrivateMethods.size()]);
  }

  public MemberSignature[] getStaticInitializers() {
    init();
    return staticInitializers.toArray(new MemberSignature[staticInitializers.size()]);
  }

  private static boolean hasStaticInitializer(PsiField field) {
    if (field.hasModifierProperty(PsiModifier.STATIC)) {
      final PsiExpression initializer = field.getInitializer();
      if (initializer == null) {
        return false;
      }
      final PsiType fieldType = field.getType();
      final PsiType stringType = TypeUtils.getStringType(field);
      if (field.hasModifierProperty(PsiModifier.FINAL) && (fieldType instanceof PsiPrimitiveType || fieldType.equals(stringType))) {
        return !PsiUtil.isConstantExpression(initializer);
      }
      else {
        return true;
      }
    }
    return false;
  }

  private void init() {
    if (index < 0) {
      index = 0;
      clazz.acceptChildren(this);
    }
  }

  @Override
  public void visitAssertStatement(PsiAssertStatement statement) {
    super.visitAssertStatement(statement);
    if (assertStatement) {
      return;
    }
    final MemberSignature memberSignature =
      MemberSignature.getAssertionsDisabledFieldMemberSignature();
    nonPrivateFields.add(memberSignature);
    final PsiManager manager = clazz.getManager();
    final PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
    final PsiClassType classType = factory.createType(clazz);
    createClassObjectAccessSynthetics(classType);
    if (staticInitializers.isEmpty()) {
      final MemberSignature initializerSignature =
        MemberSignature.getStaticInitializerMemberSignature();
      staticInitializers.add(initializerSignature);
    }
    assertStatement = true;
  }

  @Override
  public void visitClassObjectAccessExpression(
    PsiClassObjectAccessExpression expression) {
    final PsiTypeElement operand = expression.getOperand();
    final PsiType type = operand.getType();
    if (!(type instanceof PsiPrimitiveType)) {
      createClassObjectAccessSynthetics(type);
    }
    super.visitClassObjectAccessExpression(expression);
  }

  @Override
  public void visitMethodCallExpression(
    @NotNull PsiMethodCallExpression methodCallExpression) {
    // for navigating the psi tree in the order javac navigates its AST
    final PsiExpressionList argumentList =
      methodCallExpression.getArgumentList();
    final PsiExpression[] expressions = argumentList.getExpressions();
    for (final PsiExpression expression : expressions) {
      expression.accept(this);
    }
    final PsiReferenceExpression methodExpression =
      methodCallExpression.getMethodExpression();
    methodExpression.accept(this);
  }

  @Override
  public void visitReferenceElement(PsiJavaCodeReferenceElement reference) {
    super.visitReferenceElement(reference);
    final PsiElement parentClass = ClassUtils.getContainingClass(reference);
    if (reference.getParent() instanceof PsiTypeElement) {
      return;
    }
    final PsiElement element = reference.resolve();
    if (!(element instanceof PsiClass)) {
      return;
    }
    final PsiClass elementParentClass =
      ClassUtils.getContainingClass(element);
    if (elementParentClass == null ||
        !elementParentClass.equals(clazz) ||
        element.equals(parentClass)) {
      return;
    }
    final PsiClass innerClass = (PsiClass)element;
    if (!innerClass.hasModifierProperty(PsiModifier.PRIVATE)) {
      return;
    }
    final PsiMethod[] constructors = innerClass.getConstructors();
    if (constructors.length == 0) {
      getAccessMethodIndex(innerClass);
    }
  }

  @Override
  public void visitReferenceExpression(
    @NotNull PsiReferenceExpression expression) {
    super.visitReferenceExpression(expression);
    final PsiElement element = expression.resolve();
    final PsiElement elementParentClass =
      ClassUtils.getContainingClass(element);
    final PsiElement expressionParentClass =
      ClassUtils.getContainingClass(expression);
    if (expressionParentClass == null || expressionParentClass
      .equals(elementParentClass)) {
      return;
    }
    PsiElement parentOfParentClass =
      ClassUtils.getContainingClass(expressionParentClass);
    while (parentOfParentClass != null &&
           !parentOfParentClass.equals(clazz)) {
      if (!(expressionParentClass instanceof PsiAnonymousClass)) {
        getAccessMethodIndex(expressionParentClass);
      }
      getAccessMethodIndex(parentOfParentClass);
      parentOfParentClass = ClassUtils.getContainingClass(parentOfParentClass);
    }
    if (element instanceof PsiField) {
      final PsiField field = (PsiField)element;
      if (field.hasModifierProperty(PsiModifier.PRIVATE)) {
        boolean isStatic = false;
        final PsiType type = field.getType();
        if (field.hasModifierProperty(PsiModifier.STATIC)) {
          if (field.hasModifierProperty(PsiModifier.FINAL) &&
              type instanceof PsiPrimitiveType) {
            final PsiExpression initializer = field.getInitializer();
            if (PsiUtil.isConstantExpression(initializer)) {
              return;
            }
          }
          isStatic = true;
        }
        final String returnTypeSignature =
          MemberSignature.createTypeSignature(type).replace('/',
                                                            '.');
        final String className = clazz.getQualifiedName();
        @NonNls final StringBuilder signatureBuffer =
          new StringBuilder("(");
        if (!isStatic) {
          signatureBuffer.append('L').append(className).append(';');
        }
        final String accessMethodIndex = getAccessMethodIndex(field);
        if (!field.getContainingClass().equals(clazz)) {
          return;
        }
        @NonNls String name = null;
        final PsiElement parent = expression.getParent();
        if (parent instanceof PsiAssignmentExpression) {
          final PsiAssignmentExpression assignment = (PsiAssignmentExpression)parent;
          if (assignment.getLExpression().equals(expression)) {
            name = ACCESS_METHOD_NAME_PREFIX + accessMethodIndex +
                   "02";
            signatureBuffer.append(returnTypeSignature);
          }
        }
        else if (parent instanceof PsiPostfixExpression) {
          final PsiPostfixExpression postfixExpression =
            (PsiPostfixExpression)parent;
          final IElementType tokenType = postfixExpression.getOperationTokenType();
          if (tokenType.equals(JavaTokenType.PLUSPLUS)) {
            name = ACCESS_METHOD_NAME_PREFIX + accessMethodIndex +
                   "08";
          }
          else if (tokenType.equals(JavaTokenType.MINUSMINUS)) {
            name = ACCESS_METHOD_NAME_PREFIX + accessMethodIndex +
                   "10";
          }
        }
        else if (parent instanceof PsiPrefixExpression) {
          final PsiPrefixExpression prefixExpression = (PsiPrefixExpression)parent;
          final IElementType tokenType = prefixExpression.getOperationTokenType();
          if (tokenType.equals(JavaTokenType.PLUSPLUS)) {
            name = ACCESS_METHOD_NAME_PREFIX + accessMethodIndex +
                   "04";
          }
          else if (tokenType.equals(JavaTokenType.MINUSMINUS)) {
            name = ACCESS_METHOD_NAME_PREFIX + accessMethodIndex +
                   "06";
          }
        }
        if (name == null) {
          name = ACCESS_METHOD_NAME_PREFIX + accessMethodIndex + "00";
        }
        signatureBuffer.append(')').append(returnTypeSignature);
        final String signature = signatureBuffer.toString();
        final MemberSignature methodSignature =
          new MemberSignature(name, Modifier.STATIC, signature);
        nonPrivateMethods.add(methodSignature);
      }
    }
    else if (element instanceof PsiMethod) {
      final PsiMethod method = (PsiMethod)element;
      if (method.hasModifierProperty(PsiModifier.PRIVATE) &&
          method.getContainingClass().equals(clazz)) {
        final String signature;
        if (method.hasModifierProperty(PsiModifier.STATIC)) {
          signature =
            MemberSignature.createMethodSignature(method)
              .replace('/', '.');
        }
        else {
          final String returnTypeSignature =
            MemberSignature.createTypeSignature(method.getReturnType())
              .replace('/', '.');
          @NonNls final StringBuilder signatureBuffer =
            new StringBuilder();
          signatureBuffer.append("(L");
          signatureBuffer.append(clazz.getQualifiedName())
            .append(';');
          final PsiParameter[] parameters = method.getParameterList()
            .getParameters();
          for (final PsiParameter parameter : parameters) {
            final PsiType type = parameter.getType();
            final String typeSignature = MemberSignature.createTypeSignature(type)
              .replace('/', '.');
            signatureBuffer.append(typeSignature);
          }
          signatureBuffer.append(')');
          signatureBuffer.append(returnTypeSignature);
          signature = signatureBuffer.toString();
        }
        final String accessMethodIndex = getAccessMethodIndex(method);
        final MemberSignature methodSignature =
          new MemberSignature(ACCESS_METHOD_NAME_PREFIX +
                              accessMethodIndex + "00",
                              Modifier.STATIC, signature);
        nonPrivateMethods.add(methodSignature);
      }
    }
  }
}


text:
.class public abstract Landroid/database/BulkCursorNative;
.super Landroid/os/Binder;
.source "BulkCursorNative.java"

# interfaces
.implements Landroid/database/IBulkCursor;

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

    invoke-direct {p0}, Landroid/os/Binder;-><init>()V

    const-string/jumbo v0, "android.content.IBulkCursor"

    invoke-virtual {p0, p0, v0}, Landroid/database/BulkCursorNative;->attachInterface(Landroid/os/IInterface;Ljava/lang/String;)V

    return-void
.end method

.method public static asInterface(Landroid/os/IBinder;)Landroid/database/IBulkCursor;
    .locals 2

    const/4 v1, 0x0

    if-nez p0, :cond_0

    return-object v1

    :cond_0
    const-string/jumbo v1, "android.content.IBulkCursor"

    invoke-interface {p0, v1}, Landroid/os/IBinder;->queryLocalInterface(Ljava/lang/String;)Landroid/os/IInterface;

    move-result-object v0

    check-cast v0, Landroid/database/IBulkCursor;

    if-eqz v0, :cond_1

    return-object v0

    :cond_1
    new-instance v1, Landroid/database/BulkCursorProxy;

    invoke-direct {v1, p0}, Landroid/database/BulkCursorProxy;-><init>(Landroid/os/IBinder;)V

    return-object v1
.end method

# virtual methods
.method public asBinder()Landroid/os/IBinder;
    .locals 0

    return-object p0
.end method

.method public onTransact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z
    .locals 10
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    const/4 v9, 0x1

    packed-switch p1, :pswitch_data_0

    invoke-super {p0, p1, p2, p3, p4}, Landroid/os/Binder;->onTransact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    move-result v8

    return v8

    :pswitch_0
    :try_start_0
    const-string/jumbo v8, "android.content.IBulkCursor"

    invoke-virtual {p2, v8}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    invoke-virtual {p2}, Landroid/os/Parcel;->readInt()I

    move-result v6

    invoke-virtual {p0, v6}, Landroid/database/BulkCursorNative;->getWindow(I)Landroid/database/CursorWindow;

    move-result-object v7

    invoke-virtual {p3}, Landroid/os/Parcel;->writeNoException()V

    if-nez v7, :cond_0

    const/4 v8, 0x0

    invoke-virtual {p3, v8}, Landroid/os/Parcel;->writeInt(I)V

    :goto_0
    return v9

    :cond_0
    const/4 v8, 0x1

    invoke-virtual {p3, v8}, Landroid/os/Parcel;->writeInt(I)V

    const/4 v8, 0x1

    invoke-virtual {v7, p3, v8}, Landroid/database/CursorWindow;->writeToParcel(Landroid/os/Parcel;I)V
    :try_end_0
    .catch Ljava/lang/Exception; {:try_start_0 .. :try_end_0} :catch_0

    goto :goto_0

    :catch_0
    move-exception v1

    invoke-static {p3, v1}, Landroid/database/DatabaseUtils;->writeExceptionToParcel(Landroid/os/Parcel;Ljava/lang/Exception;)V

    return v9

    :pswitch_1
    :try_start_1
    const-string/jumbo v8, "android.content.IBulkCursor"

    invoke-virtual {p2, v8}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    invoke-virtual {p0}, Landroid/database/BulkCursorNative;->deactivate()V

    invoke-virtual {p3}, Landroid/os/Parcel;->writeNoException()V

    return v9

    :pswitch_2
    const-string/jumbo v8, "android.content.IBulkCursor"

    invoke-virtual {p2, v8}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    invoke-virtual {p0}, Landroid/database/BulkCursorNative;->close()V

    invoke-virtual {p3}, Landroid/os/Parcel;->writeNoException()V

    return v9

    :pswitch_3
    const-string/jumbo v8, "android.content.IBulkCursor"

    invoke-virtual {p2, v8}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    invoke-virtual {p2}, Landroid/os/Parcel;->readStrongBinder()Landroid/os/IBinder;

    move-result-object v8

    invoke-static {v8}, Landroid/database/IContentObserver$Stub;->asInterface(Landroid/os/IBinder;)Landroid/database/IContentObserver;

    move-result-object v3

    invoke-virtual {p0, v3}, Landroid/database/BulkCursorNative;->requery(Landroid/database/IContentObserver;)I

    move-result v0

    invoke-virtual {p3}, Landroid/os/Parcel;->writeNoException()V

    invoke-virtual {p3, v0}, Landroid/os/Parcel;->writeInt(I)V

    invoke-virtual {p0}, Landroid/database/BulkCursorNative;->getExtras()Landroid/os/Bundle;

    move-result-object v8

    invoke-virtual {p3, v8}, Landroid/os/Parcel;->writeBundle(Landroid/os/Bundle;)V

    return v9

    :pswitch_4
    const-string/jumbo v8, "android.content.IBulkCursor"

    invoke-virtual {p2, v8}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    invoke-virtual {p2}, Landroid/os/Parcel;->readInt()I

    move-result v4

    invoke-virtual {p0, v4}, Landroid/database/BulkCursorNative;->onMove(I)V

    invoke-virtual {p3}, Landroid/os/Parcel;->writeNoException()V

    return v9

    :pswitch_5
    const-string/jumbo v8, "android.content.IBulkCursor"

    invoke-virtual {p2, v8}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    invoke-virtual {p0}, Landroid/database/BulkCursorNative;->getExtras()Landroid/os/Bundle;

    move-result-object v2

    invoke-virtual {p3}, Landroid/os/Parcel;->writeNoException()V

    invoke-virtual {p3, v2}, Landroid/os/Parcel;->writeBundle(Landroid/os/Bundle;)V

    return v9

    :pswitch_6
    const-string/jumbo v8, "android.content.IBulkCursor"

    invoke-virtual {p2, v8}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    invoke-virtual {p2}, Landroid/os/Parcel;->readBundle()Landroid/os/Bundle;

    move-result-object v2

    invoke-virtual {p0, v2}, Landroid/database/BulkCursorNative;->respond(Landroid/os/Bundle;)Landroid/os/Bundle;

    move-result-object v5

    invoke-virtual {p3}, Landroid/os/Parcel;->writeNoException()V

    invoke-virtual {p3, v5}, Landroid/os/Parcel;->writeBundle(Landroid/os/Bundle;)V
    :try_end_1
    .catch Ljava/lang/Exception; {:try_start_1 .. :try_end_1} :catch_0

    return v9

    :pswitch_data_0
    .packed-switch 0x1
        :pswitch_0
        :pswitch_1
        :pswitch_3
        :pswitch_4
        :pswitch_5
        :pswitch_6
        :pswitch_2
    .end packed-switch
.end method

redpajama_set_name: RedPajamaGithub


text:
package com.example.jmsSqs;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.HashSet;

import javax.validation.ConstraintViolationException;

import org.junit.Assert;

import org.apache.hadoop.conf.Configuration;
import org.elasticmq.rest.sqs.SQSRestServer;
import org.elasticmq.rest.sqs.SQSRestServerBuilder;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.amazonaws.services.sqs.model.CreateQueueResult;
import com.amazonaws.services.sqs.model.PurgeQueueRequest;
import com.datatorrent.api.LocalMode;

/**
 * Test the DAG declaration in local mode.
 */
public class ApplicationTest {

  private static final Logger LOG = LoggerFactory.getLogger(ApplicationTest.class);

  private static final String FILE_NAME = "test";
  private static final String FILE_DIR  = "target/jmsSQS";
  private static final String FILE_PATH = FILE_DIR + "/" + FILE_NAME + ".0";     // first part

  private static final String QUEUE_NAME_PREFIX = "jms4Sqs";

  private String currentQueueName;

  private String currentQueueUrl;

  private AmazonSQSClient sqs;

  private SQSRestServer mockServer;

  // test messages
  private static String[] lines =
  {
    "1st line",
    "2nd line",
    "3rd line",
    "4th line",
    "5th line",
  };

  @Test
  public void testApplication() throws Exception {
    try {
      // delete output file if it exists
      File file = new File(FILE_PATH);
      file.delete();

      // Each run creates its own uniquely named queue in SQS and then deletes it afterwards.
      //  because SQS doesn't allow a deleted queue to be reused within 60 seconds
      currentQueueName = QUEUE_NAME_PREFIX + System.currentTimeMillis();

      createSQSClient();

      // write messages to the SQS Queue
      writeToQueue();

      // run app asynchronously; terminate after results are checked
      LocalMode.Controller lc = asyncRun();

      // check for presence of output file
      chkOutput();

      // compare output lines to input
      compare();

      lc.shutdown();
    } catch (ConstraintViolationException e) {
      Assert.fail("constraint violations: " + e.getConstraintViolations());
    }
  }

  private void createSQSClient()
  {
    createElasticMQMockServer();
    // just use x and y as access and secret keys respectively: not checked by the mock server
    sqs = new AmazonSQSClient(new BasicAWSCredentials("x", "y"));
    // have it talk to the embedded server
    sqs.setEndpoint("http://localhost:9324");
  }

  private void createElasticMQMockServer()
  {
    // By default the urls will use http://localhost:9324 as the base URL
    mockServer = SQSRestServerBuilder.start();
  }

  private void writeMsg(String[] msgs)
  {
    CreateQueueResult res = sqs.createQueue(currentQueueName);

    currentQueueUrl = res.getQueueUrl();

    // we should purge the queue first
    PurgeQueueRequest purgeReq = new PurgeQueueRequest(currentQueueUrl);
    sqs.purgeQueue(purgeReq);
    for (String text : msgs) {
      sqs.sendMessage(currentQueueUrl, text);
    }
  }

  private void writeToQueue() {
    writeMsg(lines);
    LOG.debug("Sent messages to topic {}", QUEUE_NAME_PREFIX);
  }

  private Configuration getConfig() {
    Configuration conf = new Configuration(false);

    // read config values from the properties.xml file
    conf.addResource(this.getClass().getResourceAsStream("/META-INF/properties.xml"));

    // one can also set or override values in code as below
    String pre = "dt.operator.fileOut.prop.";
    conf.set(pre + "filePath", FILE_DIR);

    pre = "dt.operator.sqsIn.prop.";
    // set the subject here since it is dynamically generated
    conf.set(pre + "subject", currentQueueName);
    // set the endpoint to point to our mock server
    conf.set(pre + "aws.endpoint", "http://localhost:9324");

    return conf;
  }

  private static void chkOutput() throws Exception {
    File file = new File(FILE_PATH);
    final int MAX = 60;
    for (int i = 0; i < MAX && (! file.exists()); ++i ) {
      LOG.debug("Sleeping, i = {}", i);
      Thread.sleep(1000);
    }
    if (! file.exists()) {
      String msg = String.format("Error: %s not found after %d seconds%n", FILE_PATH, MAX);
      throw new RuntimeException(msg);
    }
  }

  private void compare() throws Exception {
    // read output file
    File file = new File(FILE_PATH);
    BufferedReader br = new BufferedReader(new FileReader(file));

    HashSet<String> set = new HashSet<String>();
    String line;
    while (null != (line = br.readLine())) {
      set.add(line);
    }
    br.close();

    // now delete the file, we don't need it anymore
    Assert.assertTrue("Deleting "+file, file.delete());

    // delete the current queue, since the Queue's job is done
    sqs.deleteQueue(currentQueueUrl);

    // compare
    Assert.assertEquals("number of lines", lines.length, set.size());
    for (int i = 0; i < lines.length; ++i) {
      Assert.assertTrue("set contains "+lines[i], set.remove(lines[i]));
    }
  }

  private LocalMode.Controller asyncRun() throws Exception {
    Configuration conf = getConfig();
    LocalMode lma = LocalMode.newInstance();
    lma.prepareDAG(new SqsApplication(), conf);
    LocalMode.Controller lc = lma.getController();
    lc.runAsync();
    return lc;
  }

}


text:
Miscellaneous Options

This page contains options that don't really fit in any other category.
Most useful is the table in the second section that allows you to set
the nice level (process priority) for FTP sessions by class. A negative
nice level gives the session a higher CPU priority, while a positive
nice level gives a lower priority. On most operating systems, the allowable
nice levels range from -20 to 20.

The bottom table sets the file permissions mask for new files and directories
by class. For example, a umask of <tt>0700</tt> would give newly uploaded
files permissions of 077 (<tt>---rw-rw-</tt>).


text:
package de.devgruppe.fundiscordbot.command.commands.memegen;

public class MemeGenHelper {
  public static final String REQUEST_URL = "https://memegen.link/";
  public static final String TEMPLATE_PATH = "api/templates/";
  public static final String[] REQUEST_HEADERS = new String[]{
          "Accept", "application/json",
          "User-Agent", "Mozilla/5.0"
  };
  public static final int EXPECTED_RESPONSE_CODE = 200;
}


text:
title: "Orphans"
playwright: "Dennis Kelly"
period: Spring
season: "In House"
season_sort: 240
date_start: 2015-02-25
date_end: 2015-02-28
venue: New Theatre

cast:
  - role: Liam
    name: Diderik Ypma
  - role: Helen
    name: Anna Stubbs
  - role: Danny
    name: Shannon Smith

crew:
  - role: Director
    name: Gus Herbert
  - role: Producer
    name: Matt Standen
  - role: Technical Director
    name: Joseph Heil
  - role: Shadow Technical Director
    name: Alba Bodi Garcia
  - role: Lighting Designer
    name: Harry Bridge
  - role: Technical Operator
    name: Nick Gill
  - role: Technical Operator
    name: James Fox
  - role: Technical Operator
    name: Nathan Penney
  - role: Costume Design
    name: Maddie Hardy
  - role: Poster Designer
    name: Max Miller

links:
  - type: Review
    href: https://impactnottingham.com/2015/02/orphans-nottingham-new-theatre/
    snapshot: SnsAP
    publisher: Impact Nottingham
    author: Malena Wong
    title: "Orphans @ NNT"
    date: 2015-02-26
    rating: 6/10
    quote: "Orphans directed by Gus Herbert is a gripping story filled with tension caused by opposing family loyalties."

assets:
  - type: poster
    image: C6bKHvD
  - type: backstage
    video: kSHqXGL
    title: Backstage At

prod_shots: r5bkP7
---

Helen and her husband Danny are celebrating the news that Helen is newly pregnant with their second child with a quiet night in, but are interrupted by Helen's brother Liam, who arrives covered in blood claiming to have found a young man who has been stabbed on the street. However when Liam's account of the event begins to change under questioning, suspicions are aroused followed by increasing concern that he may have been more involved than first thought. A commentary on the extreme violence in urban areas, the question is - how far you would go for your family?


text:
<?php

namespace UthandoCommon\Stdlib;

/**
 * Class StringUtils
 *
 * @package UthandoCommon\Stdlib
 */
abstract class StringUtils
{
    /**
     * Check to see if string starts with a string
     *
     * @param string $string
     * @param string $look
     * @return bool
     */
    public static function endsWith($string, $look)
    {
        return strrpos($string, $look) === strlen($string) - strlen($look);
    }

    /**
     * Checks to see if a string ends with a string.
     *
     * @param string $string
     * @param string $look
     * @return bool
     */
    public static function startsWith($string, $look)
    {
        return strpos($string, $look) === 0;
    }
}


text:
echo "Creating Datastore/App Engine instance"
gcloud app create --region "us-central"

echo "Creating bucket: gs://$DEVSHELL_PROJECT_ID-media"
gsutil mb gs://$DEVSHELL_PROJECT_ID-media

echo "Exporting GCLOUD_PROJECT and GCLOUD_BUCKET"
export GCLOUD_PROJECT=$DEVSHELL_PROJECT_ID
export GCLOUD_BUCKET=$DEVSHELL_PROJECT_ID-media

echo "Creating virtual environment"
mkdir ~/venvs
virtualenv ~/venvs/developingapps
source ~/venvs/developingapps/bin/activate

echo "Installing Python libraries"
pip install --upgrade pip
pip install -r requirements.txt

echo "Creating Datastore entities"
python add_entities.py

echo "Creating quiz-account Service Account"
gcloud iam service-accounts create quiz-account --display-name "Quiz Account"
gcloud iam service-accounts keys create key.json --iam-account=quiz-account@$DEVSHELL_PROJECT_ID.iam.gserviceaccount.com
export GOOGLE_APPLICATION_CREDENTIALS=key.json

echo "Setting quiz-account IAM Role"
gcloud projects add-iam-policy-binding $DEVSHELL_PROJECT_ID --member serviceAccount:quiz-account@$DEVSHELL_PROJECT_ID.iam.gserviceaccount.com --role roles/owner

echo "Creating Cloud Pub/Sub topics"
gcloud beta pubsub topics create feedback
gcloud beta pubsub topics create answers
gcloud beta pubsub subscriptions create worker-subscription --topic feedback
gcloud beta pubsub subscriptions create answer-subscription --topic answers

echo "Creating Cloud Spanner Instance, Database, and Table"
gcloud spanner instances create quiz-instance --config=regional-us-central1 --description="Quiz instance" --nodes=1
gcloud spanner databases create quiz-database --instance quiz-instance --ddl "CREATE TABLE Feedback ( feedbackId STRING(100) NOT NULL, email STRING(100), quiz STRING(20), feedback STRING(MAX), rating INT64, score FLOAT64, timestamp INT64 ) PRIMARY KEY (feedbackId); CREATE TABLE Answers (answerId STRING(100) NOT NULL, id INT64, email STRING(60), quiz STRING(20), answer INT64, correct INT64, timestamp INT64) PRIMARY KEY (answerId DESC);"

echo "Project ID: $DEVSHELL_PROJECT_ID"


text:
/**
@example_title Native Controls
@example_order 30
@example_html
    <script src="nativeControl.js"></script>
*/

var uki = require('uki');

uki(
    { view: 'Flow', horizontal: true, spacing: 'large', pos: 'l:10px t:10px',
      childViews: [
        { view: 'Flow', childViews: [
            { view: 'Label', text: 'Radio group' },
            { view: 'nativeControl.Radio', name: 'group_1', text: 'Red' },
            { view: 'nativeControl.Radio', name: 'group_1', text: 'Blue',
                checked: true },
            { view: 'nativeControl.Radio', name: 'group_1', text: 'Green' }
        ]},
        { view: 'Flow', childViews: [
            { view: 'Label', text: 'Checkbox group' },
            { view: 'nativeControl.Checkbox', name: 'group_2', text: 'Red' },
            { view: 'nativeControl.Checkbox', name: 'group_2', text: 'Blue',
                checked: true },
            { view: 'nativeControl.Checkbox', name: 'group_2', text: 'Green',
                checked: true }
        ]},
        { view: 'Flow', childViews: [
            { view: 'Label', text: 'Other' },
            { view: 'nativeControl.Button', value: 'Button' },
            { view: 'nativeControl.Text', value: '', placeholder: 'Name?' },
            { view: 'nativeControl.Select', options: [
                { text: 'Default', options: [
                    'Red',
                    'Blue',
                    'Green'
                ]},
                { text: 'User', options: [
                    { text: 'Favorite', value: 1234522 },
                    { text: 'Less favorite', value: 1264522 }
                ]},
                { text: 'Custom', value: '' }
            ], value: '1264522' }
        ]}

    ]}
).attach();


text:
using namespace std;

int main()
{
  string name = "zhangsan";
  const string *ps = &name;
  const void *temp_1 = static_cast<const void*>(ps);
  void *res = const_cast<void*>(temp_1);

  void *pv = (void*)ps;

  char a = 'a', *pc = &a;
  int i = int(*pc);

  const string *const ps2 = &name;
  const void *tmp1 = static_cast<const void*>(ps2);

  return 0;
}


text:
<?php
namespace Phpiz\Core\Abstracts;
use Phpiz\Core\Abstracts\Interfaces\Filter as IFilter;

abstract class Filter implements IFilter {

}


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

define('RATING_UNSET_RATING', -999);

define ('RATING_AGGREGATE_NONE', 0); //no ratings
define ('RATING_AGGREGATE_AVERAGE', 1);
define ('RATING_AGGREGATE_COUNT', 2);
define ('RATING_AGGREGATE_MAXIMUM', 3);
define ('RATING_AGGREGATE_MINIMUM', 4);
define ('RATING_AGGREGATE_SUM', 5);

define ('RATING_DEFAULT_SCALE', 5);

/**
 * The rating class represents a single rating by a single user
 *
 * @package   core_rating
 * @category  rating
 * @copyright 2010 Andrew Davis
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since     Moodle 2.0
 */
class rating implements renderable {

    /**
     * @var stdClass The context in which this rating exists
     */
    public $context;

    /**
     * @var string The component using ratings. For example "mod_forum"
     */
    public $component;

    /**
     * @var string The rating area to associate this rating with
     *             This allows a plugin to rate more than one thing by specifying different rating areas
     */
    public $ratingarea = null;

    /**
     * @var int The id of the item (forum post, glossary item etc) being rated
     */
    public $itemid;

    /**
     * @var int The id scale (1-5, 0-100) that was in use when the rating was submitted
     */
    public $scaleid;

    /**
     * @var int The id of the user who submitted the rating
     */
    public $userid;

    /**
     * @var stdclass settings for this rating. Necessary to render the rating.
     */
    public $settings;

    /**
     * @var int The Id of this rating within the rating table. This is only set if the rating already exists
     */
    public $id = null;

    /**
     * @var int The aggregate of the combined ratings for the associated item. This is only set if the rating already exists
     */
    public $aggregate = null;

    /**
     * @var int The total number of ratings for the associated item. This is only set if the rating already exists
     */
    public $count = 0;

    /**
     * @var int The rating the associated user gave the associated item. This is only set if the rating already exists
     */
    public $rating = null;

    /**
     * @var int The time the associated item was created
     */
    public $itemtimecreated = null;

    /**
     * @var int The id of the user who submitted the rating
     */
    public $itemuserid = null;

    /**
     * Constructor.
     *
     * @param stdClass $options {
     *            context => context context to use for the rating [required]
     *            component => component using ratings ie mod_forum [required]
     *            ratingarea => ratingarea to associate this rating with [required]
     *            itemid  => int the id of the associated item (forum post, glossary item etc) [required]
     *            scaleid => int The scale in use when the rating was submitted [required]
     *            userid  => int The id of the user who submitted the rating [required]
     *            settings => Settings for the rating object [optional]
     *            id => The id of this rating (if the rating is from the db) [optional]
     *            aggregate => The aggregate for the rating [optional]
     *            count => The number of ratings [optional]
     *            rating => The rating given by the user [optional]
     * }
     */
    public function __construct($options) {
        $this->context =    $options->context;
        $this->component =  $options->component;
        $this->ratingarea = $options->ratingarea;
        $this->itemid =     $options->itemid;
        $this->scaleid =    $options->scaleid;
        $this->userid =     $options->userid;

        if (isset($options->settings)) {
            $this->settings = $options->settings;
        }
        if (isset($options->id)) {
            $this->id = $options->id;
        }
        if (isset($options->aggregate)) {
            $this->aggregate = $options->aggregate;
        }
        if (isset($options->count)) {
            $this->count = $options->count;
        }
        if (isset($options->rating)) {
            $this->rating = $options->rating;
        }
    }

    /**
     * Update this rating in the database
     *
     * @param int $rating the integer value of this rating
     */
    public function update_rating($rating) {
        global $DB;

        $time = time();

        $data = new stdClass;
        $data->rating       = $rating;
        $data->timemodified = $time;

        $item = new stdclass();
        $item->id = $this->itemid;
        $items = array($item);

        $ratingoptions = new stdClass;
        $ratingoptions->context = $this->context;
        $ratingoptions->component = $this->component;
        $ratingoptions->ratingarea = $this->ratingarea;
        $ratingoptions->items = $items;
        $ratingoptions->aggregate = RATING_AGGREGATE_AVERAGE;//we dont actually care what aggregation method is applied
        $ratingoptions->scaleid = $this->scaleid;
        $ratingoptions->userid = $this->userid;

        $rm = new rating_manager();
        $items = $rm->get_ratings($ratingoptions);
        $firstitem = $items[0]->rating;

        if (empty($firstitem->id)) {
            // Insert a new rating
            $data->contextid    = $this->context->id;
            $data->component    = $this->component;
            $data->ratingarea   = $this->ratingarea;
            $data->rating       = $rating;
            $data->scaleid      = $this->scaleid;
            $data->userid       = $this->userid;
            $data->itemid       = $this->itemid;
            $data->timecreated  = $time;
            $data->timemodified = $time;
            $DB->insert_record('rating', $data);
        } else {
            // Update the rating
            $data->id           = $firstitem->id;
            $DB->update_record('rating', $data);
        }
    }

    /**
     * Retreive the integer value of this rating
     *
     * @return int the integer value of this rating object
     */
    public function get_rating() {
        return $this->rating;
    }

    /**
     * Returns this ratings aggregate value as a string.
     *
     * @return string ratings aggregate value
     */
    public function get_aggregate_string() {

        $aggregate = $this->aggregate;
        $method = $this->settings->aggregationmethod;

        // only display aggregate if aggregation method isn't COUNT
        $aggregatestr = '';
        if ($aggregate && $method != RATING_AGGREGATE_COUNT) {
            if ($method != RATING_AGGREGATE_SUM && !$this->settings->scale->isnumeric) {
                $aggregatestr .= $this->settings->scale->scaleitems[round($aggregate)]; //round aggregate as we're using it as an index
            } else { // aggregation is SUM or the scale is numeric
                $aggregatestr .= round($aggregate, 1);
            }
        }

        return $aggregatestr;
    }

    /**
     * Returns true if the user is able to rate this rating object
     *
     * @param int $userid Current user assumed if left empty
     * @return bool true if the user is able to rate this rating object
     */
    public function user_can_rate($userid = null) {
        if (empty($userid)) {
            global $USER;
            $userid = $USER->id;
        }
        // You can't rate your item
        if ($this->itemuserid == $userid) {
            return false;
        }
        // You can't rate if you don't have the system cap
        if (!$this->settings->permissions->rate) {
            return false;
        }
        // You can't rate if you don't have the plugin cap
        if (!$this->settings->pluginpermissions->rate) {
            return false;
        }

        // You can't rate if the item was outside of the assessment times
        $timestart = $this->settings->assesstimestart;
        $timefinish = $this->settings->assesstimefinish;
        $timecreated = $this->itemtimecreated;
        if (!empty($timestart) && !empty($timefinish) && ($timecreated < $timestart || $timecreated > $timefinish)) {
            return false;
        }
        return true;
    }

    /**
     * Returns true if the user is able to view the aggregate for this rating object.
     *
     * @param int|null $userid If left empty the current user is assumed.
     * @return bool true if the user is able to view the aggregate for this rating object
     */
    public function user_can_view_aggregate($userid = null) {
        if (empty($userid)) {
            global $USER;
            $userid = $USER->id;
        }

        // if the item doesnt belong to anyone or its another user's items and they can see the aggregate on items they don't own
        // Note that viewany doesnt mean you can see the aggregate or ratings of your own items
        if ((empty($this->itemuserid) or $this->itemuserid != $userid) && $this->settings->permissions->viewany && $this->settings->pluginpermissions->viewany ) {
            return true;
        }

        // if its the current user's item and they have permission to view the aggregate on their own items
        if ($this->itemuserid == $userid && $this->settings->permissions->view && $this->settings->pluginpermissions->view) {
            return true;
        }

        return false;
    }

    /**
     * Returns a URL to view all of the ratings for the item this rating is for.
     *
     * If this is a rating of a post then this URL will take the user to a page that shows all of the ratings for the post
     * (this one included).
     *
     * @param bool $popup whether of not the URL should be loaded in a popup
     * @return moodle_url URL to view all of the ratings for the item this rating is for.
     */
    public function get_view_ratings_url($popup = false) {
        $attributes = array(
            'contextid'  => $this->context->id,
            'component'  => $this->component,
            'ratingarea' => $this->ratingarea,
            'itemid'     => $this->itemid,
            'scaleid'    => $this->settings->scale->id
        );
        if ($popup) {
            $attributes['popup'] = 1;
        }
        return new moodle_url('/rating/index.php', $attributes);
    }

    /**
     * Returns a URL that can be used to rate the associated item.
     *
     * @param int|null          $rating    The rating to give the item, if null then no rating param is added.
     * @param moodle_url|string $returnurl The URL to return to.
     * @return moodle_url can be used to rate the associated item.
     */
    public function get_rate_url($rating = null, $returnurl = null) {
        if (empty($returnurl)) {
            if (!empty($this->settings->returnurl)) {
                $returnurl = $this->settings->returnurl;
            } else {
                global $PAGE;
                $returnurl = $PAGE->url;
            }
        }
        $args = array(
            'contextid'   => $this->context->id,
            'component'   => $this->component,
            'ratingarea'  => $this->ratingarea,
            'itemid'      => $this->itemid,
            'scaleid'     => $this->settings->scale->id,
            'returnurl'   => $returnurl,
            'rateduserid' => $this->itemuserid,
            'aggregation' => $this->settings->aggregationmethod,
            'sesskey'     => sesskey()
        );
        if (!empty($rating)) {
            $args['rating'] = $rating;
        }
        $url = new moodle_url('/rating/rate.php', $args);
        return $url;
    }

    /**
    * Remove this rating from the database
    * @return void
    */
    //public function delete_rating() {
        //todo implement this if its actually needed
    //}
} //end rating class definition

/**
 * The rating_manager class provides the ability to retrieve sets of ratings from the database
 *
 * @package   core_rating
 * @category  rating
 * @copyright 2010 Andrew Davis
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since     Moodle 2.0
 */
class rating_manager {

    /**
     * @var array An array of calculated scale options to save us generating them for each request.
     */
    protected $scales = array();

    /**
     * Delete one or more ratings. Specify either a rating id, an item id or just the context id.
     *
     * @global moodle_database $DB
     * @param stdClass $options {
     *            contextid => int the context in which the ratings exist [required]
     *            ratingid => int the id of an individual rating to delete [optional]
     *            userid => int delete the ratings submitted by this user. May be used in conjuction with itemid [optional]
     *            itemid => int delete all ratings attached to this item [optional]
     *            component => string The component to delete ratings from [optional]
     *            ratingarea => string The ratingarea to delete ratings from [optional]
     * }
     */
    public function delete_ratings($options) {
        global $DB;

        if (empty($options->contextid)) {
            throw new coding_exception('The context option is a required option when deleting ratings.');
        }

        $conditions = array('contextid' => $options->contextid);
        $possibleconditions = array(
            'ratingid'   => 'id',
            'userid'     => 'userid',
            'itemid'     => 'itemid',
            'component'  => 'component',
            'ratingarea' => 'ratingarea'
        );
        foreach ($possibleconditions as $option => $field) {
            if (isset($options->{$option})) {
                $conditions[$field] = $options->{$option};
            }
        }
        $DB->delete_records('rating', $conditions);
    }

    /**
     * Returns an array of ratings for a given item (forum post, glossary entry etc). This returns all users ratings for a single item
     *
     * @param stdClass $options {
     *            context => context the context in which the ratings exists [required]
     *            component => component using ratings ie mod_forum [required]
     *            ratingarea => ratingarea to associate this rating with [required]
     *            itemid  =>  int the id of the associated item (forum post, glossary item etc) [required]
     *            sort    => string SQL sort by clause [optional]
     * }
     * @return array an array of ratings
     */
    public function get_all_ratings_for_item($options) {
        global $DB;

        if (!isset($options->context)) {
            throw new coding_exception('The context option is a required option when getting ratings for an item.');
        }
        if (!isset($options->itemid)) {
            throw new coding_exception('The itemid option is a required option when getting ratings for an item.');
        }
        if (!isset($options->component)) {
            throw new coding_exception('The component option is now a required option when getting ratings for an item.');
        }
        if (!isset($options->ratingarea)) {
            throw new coding_exception('The ratingarea option is now a required option when getting ratings for an item.');
        }

        $sortclause = '';
        if( !empty($options->sort) ) {
            $sortclause = "ORDER BY $options->sort";
        }

        $params = array(
            'contextid'  => $options->context->id,
            'itemid'     => $options->itemid,
            'component'  => $options->component,
            'ratingarea' => $options->ratingarea,
        );
        $userfields = user_picture::fields('u', null, 'userid');
        $sql = "SELECT r.id, r.rating, r.itemid, r.userid, r.timemodified, r.component, r.ratingarea, $userfields
                  FROM {rating} r
             LEFT JOIN {user} u ON r.userid = u.id
                 WHERE r.contextid = :contextid AND
                       r.itemid  = :itemid AND
                       r.component = :component AND
                       r.ratingarea = :ratingarea
                       {$sortclause}";

        return $DB->get_records_sql($sql, $params);
    }

    /**
     * Adds rating objects to an array of items (forum posts, glossary entries etc). Rating objects are available at $item->rating
     *
     * @param stdClass $options {
     *            context          => context the context in which the ratings exists [required]
     *            component        => the component name ie mod_forum [required]
     *            ratingarea       => the ratingarea we are interested in [required]
     *            items            => array an array of items such as forum posts or glossary items. They must have an 'id' member ie $items[0]->id[required]
     *            aggregate        => int what aggregation method should be applied. RATING_AGGREGATE_AVERAGE, RATING_AGGREGATE_MAXIMUM etc [required]
     *            scaleid          => int the scale from which the user can select a rating [required]
     *            userid           => int the id of the current user [optional]
     *            returnurl        => string the url to return the user to after submitting a rating. Can be left null for ajax requests [optional]
     *            assesstimestart  => int only allow rating of items created after this timestamp [optional]
     *            assesstimefinish => int only allow rating of items created before this timestamp [optional]
     * @return array the array of items with their ratings attached at $items[0]->rating
     */
    public function get_ratings($options) {
        global $DB, $USER;

        if (!isset($options->context)) {
            throw new coding_exception('The context option is a required option when getting ratings.');
        }

        if (!isset($options->component)) {
            throw new coding_exception('The component option is a required option when getting ratings.');
        }

        if (!isset($options->ratingarea)) {
            throw new coding_exception('The ratingarea option is a required option when getting ratings.');
        }

        if (!isset($options->scaleid)) {
            throw new coding_exception('The scaleid option is a required option when getting ratings.');
        }

        if (!isset($options->items)) {
            throw new coding_exception('The items option is a required option when getting ratings.');
        } else if (empty($options->items)) {
            return array();
        }

        if (!isset($options->aggregate)) {
            throw new coding_exception('The aggregate option is a required option when getting ratings.');
        } else if ($options->aggregate == RATING_AGGREGATE_NONE) {
            // Ratings arn't enabled.
            return $options->items;
        }
        $aggregatestr = $this->get_aggregation_method($options->aggregate);

        // Default the userid to the current user if it is not set
        if (empty($options->userid)) {
            $userid = $USER->id;
        } else {
            $userid = $options->userid;
        }

        // Get the item table name, the item id field, and the item user field for the given rating item
        // from the related component.
        list($type, $name) = core_component::normalize_component($options->component);
        $default = array(null, 'id', 'userid');
        list($itemtablename, $itemidcol, $itemuseridcol) = plugin_callback($type, $name, 'rating', 'get_item_fields', array($options), $default);

        // Create an array of item ids
        $itemids = array();
        foreach ($options->items as $item) {
            $itemids[] = $item->{$itemidcol};
        }

        // get the items from the database
        list($itemidtest, $params) = $DB->get_in_or_equal($itemids, SQL_PARAMS_NAMED);
        $params['contextid'] = $options->context->id;
        $params['userid']    = $userid;
        $params['component']    = $options->component;
        $params['ratingarea'] = $options->ratingarea;

        $sql = "SELECT r.id, r.itemid, r.userid, r.scaleid, r.rating AS usersrating
                  FROM {rating} r
                 WHERE r.userid = :userid AND
                       r.contextid = :contextid AND
                       r.itemid {$itemidtest} AND
                       r.component = :component AND
                       r.ratingarea = :ratingarea
              ORDER BY r.itemid";
        $userratings = $DB->get_records_sql($sql, $params);

        $sql = "SELECT r.itemid, $aggregatestr(r.rating) AS aggrrating, COUNT(r.rating) AS numratings
                  FROM {rating} r
                 WHERE r.contextid = :contextid AND
                       r.itemid {$itemidtest} AND
                       r.component = :component AND
                       r.ratingarea = :ratingarea
              GROUP BY r.itemid, r.component, r.ratingarea, r.contextid
              ORDER BY r.itemid";
        $aggregateratings = $DB->get_records_sql($sql, $params);

        $ratingoptions = new stdClass;
        $ratingoptions->context = $options->context;
        $ratingoptions->component = $options->component;
        $ratingoptions->ratingarea = $options->ratingarea;
        $ratingoptions->settings = $this->generate_rating_settings_object($options);
        foreach ($options->items as $item) {
            $founduserrating = false;
            foreach($userratings as $userrating) {
                //look for an existing rating from this user of this item
                if ($item->{$itemidcol} == $userrating->itemid) {
                    // Note: rec->scaleid = the id of scale at the time the rating was submitted
                    // may be different from the current scale id
                    $ratingoptions->scaleid = $userrating->scaleid;
                    $ratingoptions->userid = $userrating->userid;
                    $ratingoptions->id = $userrating->id;
                    $ratingoptions->rating = min($userrating->usersrating, $ratingoptions->settings->scale->max);

                    $founduserrating = true;
                    break;
                }
            }
            if (!$founduserrating) {
                $ratingoptions->scaleid = null;
                $ratingoptions->userid = null;
                $ratingoptions->id = null;
                $ratingoptions->rating =  null;
            }

            if (array_key_exists($item->{$itemidcol}, $aggregateratings)) {
                $rec = $aggregateratings[$item->{$itemidcol}];
                $ratingoptions->itemid = $item->{$itemidcol};
                $ratingoptions->aggregate = min($rec->aggrrating, $ratingoptions->settings->scale->max);
                $ratingoptions->count = $rec->numratings;
            } else {
                $ratingoptions->itemid = $item->{$itemidcol};
                $ratingoptions->aggregate = null;
                $ratingoptions->count = 0;
            }

            $rating = new rating($ratingoptions);
            $rating->itemtimecreated = $this->get_item_time_created($item);
            if (!empty($item->{$itemuseridcol})) {
                $rating->itemuserid = $item->{$itemuseridcol};
            }
            $item->rating = $rating;
        }

        return $options->items;
    }

    /**
     * Generates a rating settings object based upon the options it is provided.
     *
     * @param stdClass $options {
     *      context           => context the context in which the ratings exists [required]
     *      component         => string The component the items belong to [required]
     *      ratingarea        => string The ratingarea the items belong to [required]
     *      aggregate         => int what aggregation method should be applied. RATING_AGGREGATE_AVERAGE, RATING_AGGREGATE_MAXIMUM etc [required]
     *      scaleid           => int the scale from which the user can select a rating [required]
     *      returnurl         => string the url to return the user to after submitting a rating. Can be left null for ajax requests [optional]
     *      assesstimestart   => int only allow rating of items created after this timestamp [optional]
     *      assesstimefinish  => int only allow rating of items created before this timestamp [optional]
     *      plugintype        => string plugin type ie 'mod' Used to find the permissions callback [optional]
     *      pluginname        => string plugin name ie 'forum' Used to find the permissions callback [optional]
     * }
     * @return stdClass rating settings object
     */
    protected function generate_rating_settings_object($options) {

        if (!isset($options->context)) {
            throw new coding_exception('The context option is a required option when generating a rating settings object.');
        }
        if (!isset($options->component)) {
            throw new coding_exception('The component option is now a required option when generating a rating settings object.');
        }
        if (!isset($options->ratingarea)) {
            throw new coding_exception('The ratingarea option is now a required option when generating a rating settings object.');
        }
        if (!isset($options->aggregate)) {
            throw new coding_exception('The aggregate option is now a required option when generating a rating settings object.');
        }
        if (!isset($options->scaleid)) {
            throw new coding_exception('The scaleid option is now a required option when generating a rating settings object.');
        }

        // settings that are common to all ratings objects in this context
        $settings = new stdClass;
        $settings->scale             = $this->generate_rating_scale_object($options->scaleid); // the scale to use now
        $settings->aggregationmethod = $options->aggregate;
        $settings->assesstimestart   = null;
        $settings->assesstimefinish  = null;

        // Collect options into the settings object
        if (!empty($options->assesstimestart)) {
            $settings->assesstimestart = $options->assesstimestart;
        }
        if (!empty($options->assesstimefinish)) {
            $settings->assesstimefinish = $options->assesstimefinish;
        }
        if (!empty($options->returnurl)) {
            $settings->returnurl = $options->returnurl;
        }

        // check site capabilities
        $settings->permissions = new stdClass;
        $settings->permissions->view    = has_capability('moodle/rating:view', $options->context); // can view the aggregate of ratings of their own items
        $settings->permissions->viewany = has_capability('moodle/rating:viewany', $options->context); // can view the aggregate of ratings of other people's items
        $settings->permissions->viewall = has_capability('moodle/rating:viewall', $options->context); // can view individual ratings
        $settings->permissions->rate    = has_capability('moodle/rating:rate', $options->context); // can submit ratings

        // check module capabilities (mostly for backwards compatability with old modules that previously implemented their own ratings)
        $pluginpermissionsarray = $this->get_plugin_permissions_array($options->context->id, $options->component, $options->ratingarea);
        $settings->pluginpermissions = new stdClass;
        $settings->pluginpermissions->view    = $pluginpermissionsarray['view'];
        $settings->pluginpermissions->viewany = $pluginpermissionsarray['viewany'];
        $settings->pluginpermissions->viewall = $pluginpermissionsarray['viewall'];
        $settings->pluginpermissions->rate    = $pluginpermissionsarray['rate'];

        return $settings;
    }

    /**
     * Generates a scale object that can be returned
     *
     * @global moodle_database $DB moodle database object
     * @param int $scaleid scale-type identifier
     * @return stdClass scale for ratings
     */
    protected function generate_rating_scale_object($scaleid) {
        global $DB;
        if (!array_key_exists('s'.$scaleid, $this->scales)) {
            $scale = new stdClass;
            $scale->id = $scaleid;
            $scale->name = null;
            $scale->courseid = null;
            $scale->scaleitems = array();
            $scale->isnumeric = true;
            $scale->max = $scaleid;

            if ($scaleid < 0) {
                // It is a proper scale (not numeric)
                $scalerecord = $DB->get_record('scale', array('id' => abs($scaleid)));
                if ($scalerecord) {
                    // We need to generate an array with string keys starting at 1
                    $scalearray = explode(',', $scalerecord->scale);
                    $c = count($scalearray);
                    for ($i = 0; $i < $c; $i++) {
                        // treat index as a string to allow sorting without changing the value
                        $scale->scaleitems[(string)($i + 1)] = $scalearray[$i];
                    }
                    krsort($scale->scaleitems); // have the highest grade scale item appear first
                    $scale->isnumeric = false;
                    $scale->name = $scalerecord->name;
                    $scale->courseid = $scalerecord->courseid;
                    $scale->max = count($scale->scaleitems);
                }
            } else {
                //generate an array of values for numeric scales
                for($i = 0; $i <= (int)$scaleid; $i++) {
                    $scale->scaleitems[(string)$i] = $i;
                }
            }
            $this->scales['s'.$scaleid] = $scale;
        }
        return $this->scales['s'.$scaleid];
    }

    /**
     * Gets the time the given item was created
     *
     * TODO: MDL-31511 - Find a better solution for this, its not ideal to test for fields really we should be
     * asking the component the item belongs to what field to look for or even the value we
     * are looking for.
     *
     * @param stdClass $item
     * @return int|null return null if the created time is unavailable, otherwise return a timestamp
     */
    protected function get_item_time_created($item) {
        if( !empty($item->created) ) {
            return $item->created;//the forum_posts table has created instead of timecreated
        }
        else if(!empty($item->timecreated)) {
            return $item->timecreated;
        }
        else {
            return null;
        }
    }

    /**
     * Returns an array of grades calculated by aggregating item ratings.
     *
     * @param stdClass $options {
     *            userid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
     *            aggregationmethod => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
     *            scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
     *            itemtable => int the table containing the items [required]
     *            itemtableusercolum => int the column of the user table containing the item owner's user id [required]
     *            component => The component for the ratings [required]
     *            ratingarea => The ratingarea for the ratings [required]
     *            contextid => int the context in which the rated items exist [optional]
     *            modulename => string the name of the module [optional]
     *            moduleid => int the id of the module instance [optional]
     * }
     * @return array the array of the user's grades
     */
    public function get_user_grades($options) {
        global $DB;

        $contextid = null;

        if (!isset($options->component)) {
            throw new coding_exception('The component option is now a required option when getting user grades from ratings.');
        }
        if (!isset($options->ratingarea)) {
            throw new coding_exception('The ratingarea option is now a required option when getting user grades from ratings.');
        }

        //if the calling code doesn't supply a context id we'll have to figure it out
        if( !empty($options->contextid) ) {
            $contextid = $options->contextid;
        }
        else if( !empty($options->cmid) ) {
            //not implemented as not currently used although cmid is potentially available (the forum supplies it)
            //Is there a convenient way to get a context id from a cm id?
            //$cmidnumber = $options->cmidnumber;
        }
        else if ( !empty($options->modulename) && !empty($options->moduleid) ) {
            $modulename = $options->modulename;
            $moduleid   = intval($options->moduleid);

            // Going direct to the db for the context id seems wrong.
            $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
            $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = cm.id AND ctx.contextlevel = :contextlevel)";
            $sql = "SELECT cm.* $ctxselect
                      FROM {course_modules} cm
                 LEFT JOIN {modules} mo ON mo.id = cm.module
                 LEFT JOIN {{$modulename}} m ON m.id = cm.instance $ctxjoin
                     WHERE mo.name=:modulename AND
                           m.id=:moduleid";
            $params = array('modulename' => $modulename, 'moduleid' => $moduleid, 'contextlevel' => CONTEXT_MODULE);
            $contextrecord = $DB->get_record_sql($sql, $params, '*', MUST_EXIST);
            $contextid = $contextrecord->ctxid;
        }

        $params = array();
        $params['contextid']  = $contextid;
        $params['component']  = $options->component;
        $params['ratingarea'] = $options->ratingarea;
        $itemtable            = $options->itemtable;
        $itemtableusercolumn  = $options->itemtableusercolumn;
        $scaleid              = $options->scaleid;
        $aggregationstring    = $this->get_aggregation_method($options->aggregationmethod);

        //if userid is not 0 we only want the grade for a single user
        $singleuserwhere = '';
        if ($options->userid != 0) {
            $params['userid1'] = intval($options->userid);
            $singleuserwhere = "AND i.{$itemtableusercolumn} = :userid1";
        }

        //MDL-24648 The where line used to be "WHERE (r.contextid is null or r.contextid=:contextid)"
        //r.contextid will be null for users who haven't been rated yet
        //no longer including users who haven't been rated to reduce memory requirements
        $sql = "SELECT u.id as id, u.id AS userid, $aggregationstring(r.rating) AS rawgrade
                  FROM {user} u
             LEFT JOIN {{$itemtable}} i ON u.id=i.{$itemtableusercolumn}
             LEFT JOIN {rating} r ON r.itemid=i.id
                 WHERE r.contextid = :contextid AND
                       r.component = :component AND
                       r.ratingarea = :ratingarea
                       $singleuserwhere
              GROUP BY u.id";
        $results = $DB->get_records_sql($sql, $params);

        if ($results) {

            $scale = null;
            $max = 0;
            if ($options->scaleid >= 0) {
                //numeric
                $max = $options->scaleid;
            } else {
                //custom scales
                $scale = $DB->get_record('scale', array('id' => -$options->scaleid));
                if ($scale) {
                    $scale = explode(',', $scale->scale);
                    $max = count($scale);
                } else {
                    debugging('rating_manager::get_user_grades() received a scale ID that doesnt exist');
                }
            }

            // it could throw off the grading if count and sum returned a rawgrade higher than scale
            // so to prevent it we review the results and ensure that rawgrade does not exceed the scale, if it does we set rawgrade = scale (i.e. full credit)
            foreach ($results as $rid=>$result) {
                if ($options->scaleid >= 0) {
                    //numeric
                    if ($result->rawgrade > $options->scaleid) {
                        $results[$rid]->rawgrade = $options->scaleid;
                    }
                } else {
                    //scales
                    if (!empty($scale) && $result->rawgrade > $max) {
                        $results[$rid]->rawgrade = $max;
                    }
                }
            }
        }

        return $results;
    }

    /**
     * Returns array of aggregate types. Used by ratings.
     *
     * @return array aggregate types
     */
    public function get_aggregate_types() {
        return array (RATING_AGGREGATE_NONE     => get_string('aggregatenone', 'rating'),
                      RATING_AGGREGATE_AVERAGE  => get_string('aggregateavg', 'rating'),
                      RATING_AGGREGATE_COUNT    => get_string('aggregatecount', 'rating'),
                      RATING_AGGREGATE_MAXIMUM  => get_string('aggregatemax', 'rating'),
                      RATING_AGGREGATE_MINIMUM  => get_string('aggregatemin', 'rating'),
                      RATING_AGGREGATE_SUM      => get_string('aggregatesum', 'rating'));
    }

    /**
     * Converts an aggregation method constant into something that can be included in SQL
     *
     * @param int $aggregate An aggregation constant. For example, RATING_AGGREGATE_AVERAGE.
     * @return string an SQL aggregation method
     */
    public function get_aggregation_method($aggregate) {
        $aggregatestr = null;
        switch($aggregate){
            case RATING_AGGREGATE_AVERAGE:
                $aggregatestr = 'AVG';
                break;
            case RATING_AGGREGATE_COUNT:
                $aggregatestr = 'COUNT';
                break;
            case RATING_AGGREGATE_MAXIMUM:
                $aggregatestr = 'MAX';
                break;
            case RATING_AGGREGATE_MINIMUM:
                $aggregatestr = 'MIN';
                break;
            case RATING_AGGREGATE_SUM:
                $aggregatestr = 'SUM';
                break;
            default:
                $aggregatestr = 'AVG'; // Default to this to avoid real breakage - MDL-22270
                debugging('Incorrect call to get_aggregation_method(), was called with incorrect aggregate method ' . $aggregate, DEBUG_DEVELOPER);
        }
        return $aggregatestr;
    }

    /**
     * Looks for a callback like forum_rating_permissions() to retrieve permissions from the plugin whose items are being rated
     *
     * @param int $contextid The current context id
     * @param string $component the name of the component that is using ratings ie 'mod_forum'
     * @param string $ratingarea The area the rating is associated with
     * @return array rating related permissions
     */
    public function get_plugin_permissions_array($contextid, $component, $ratingarea) {
        $pluginpermissionsarray = null;
        $defaultpluginpermissions = array('rate'=>false,'view'=>false,'viewany'=>false,'viewall'=>false);//deny by default
        if (!empty($component)) {
            list($type, $name) = core_component::normalize_component($component);
            $pluginpermissionsarray = plugin_callback($type, $name, 'rating', 'permissions', array($contextid, $component, $ratingarea), $defaultpluginpermissions);
        } else {
            $pluginpermissionsarray = $defaultpluginpermissions;
        }
        return $pluginpermissionsarray;
    }

    /**
     * Validates a submitted rating
     *
     * @param array $params submitted data
     *            context => object the context in which the rated items exists [required]
     *            component => The component the rating belongs to [required]
     *            ratingarea => The ratingarea the rating is associated with [required]
     *            itemid => int the ID of the object being rated [required]
     *            scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
     *            rating => int the submitted rating
     *            rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
     *            aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [optional]
     * @return boolean true if the rating is valid. False if callback wasnt found and will throw rating_exception if rating is invalid
     */
    public function check_rating_is_valid($params) {

        if (!isset($params['context'])) {
            throw new coding_exception('The context option is a required option when checking rating validity.');
        }
        if (!isset($params['component'])) {
            throw new coding_exception('The component option is now a required option when checking rating validity');
        }
        if (!isset($params['ratingarea'])) {
            throw new coding_exception('The ratingarea option is now a required option when checking rating validity');
        }
        if (!isset($params['itemid'])) {
            throw new coding_exception('The itemid option is now a required option when checking rating validity');
        }
        if (!isset($params['scaleid'])) {
            throw new coding_exception('The scaleid option is now a required option when checking rating validity');
        }
        if (!isset($params['rateduserid'])) {
            throw new coding_exception('The rateduserid option is now a required option when checking rating validity');
        }

        list($plugintype, $pluginname) = core_component::normalize_component($params['component']);

        //this looks for a function like forum_rating_validate() in mod_forum lib.php
        //wrapping the params array in another array as call_user_func_array() expands arrays into multiple arguments
        $isvalid = plugin_callback($plugintype, $pluginname, 'rating', 'validate', array($params), null);

        //if null then the callback doesn't exist
        if ($isvalid === null) {
            $isvalid = false;
            debugging('rating validation callback not found for component '.  clean_param($component, PARAM_ALPHANUMEXT));
        }
        return $isvalid;
    }

    /**
     * Initialises JavaScript to enable AJAX ratings on the provided page
     *
     * @param moodle_page $page
     * @return true always returns true
     */
    public function initialise_rating_javascript(moodle_page $page) {
        global $CFG;

        //only needs to be initialized once
        static $done = false;
        if ($done) {
            return true;
        }

        if (!empty($CFG->enableajax)) {
            $page->requires->js_init_call('M.core_rating.init');
        }
        $done = true;

        return true;
    }

    /**
     * Returns a string that describes the aggregation method that was provided.
     *
     * @param string $aggregationmethod
     * @return string describes the aggregation method that was provided
     */
    public function get_aggregate_label($aggregationmethod) {
        $aggregatelabel = '';
        switch ($aggregationmethod) {
            case RATING_AGGREGATE_AVERAGE :
                $aggregatelabel .= get_string("aggregateavg", "rating");
                break;
            case RATING_AGGREGATE_COUNT :
                $aggregatelabel .= get_string("aggregatecount", "rating");
                break;
            case RATING_AGGREGATE_MAXIMUM :
                $aggregatelabel .= get_string("aggregatemax", "rating");
                break;
            case RATING_AGGREGATE_MINIMUM :
                $aggregatelabel .= get_string("aggregatemin", "rating");
                break;
            case RATING_AGGREGATE_SUM :
                $aggregatelabel .= get_string("aggregatesum", "rating");
                break;
        }
        $aggregatelabel .= get_string('labelsep', 'langconfig');
        return $aggregatelabel;
    }

}//end rating_manager class definition

/**
 * The rating_exception class provides the ability to generate exceptions that can be easily identified as coming from the ratings system
 *
 * @package   core_rating
 * @category  rating
 * @copyright 2010 Andrew Davis
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since     Moodle 2.0
 */
class rating_exception extends moodle_exception {
    /**
     * @var string The message to accompany the thrown exception
     */
    public $message;
    /**
     * Generate exceptions that can be easily identified as coming from the ratings system
     *
     * @param string $errorcode the error code to generate
     */
    function __construct($errorcode) {
        $this->errorcode = $errorcode;
        $this->message = get_string($errorcode, 'error');
    }
}


text:
<?php

declare(strict_types=1);

/*
 * This file is part of the RollerworksSearch package.
 *
 * (c) Sebastiaan Stok <s.stok@rollerscapes.net>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Rollerworks\Component\Search\Doctrine\Dbal;

/**
 * StrategySupportedConversion, allows for different conversion strategies.
 *
 * @author Sebastiaan Stok <s.stok@rollerscapes.net>
 */
interface StrategySupportedConversion
{
    /**
     * Returns the conversion strategy for the provided value.
     *
     * This must either return: 0 (default) or a positive integer.
     * Each strategy will use a different 'slot' during the query building.
     *
     * For example searching by age/birthday.
     * * If the value is a DateTime object, strategy 1 is used and the input-value is converted to a date string.
     * * If the value is an integer, strategy 2 is used and the value is transformed using a custom SQL statement.
     *
     * Afterwards the conversion strategy is available as the `conversionStrategy`
     * property of the {@link \Rollerworks\Component\Search\Doctrine\Dbal\ConversionHints}.
     *
     * @param mixed           $value   The "model" value format
     * @param array           $options Options of the Field configuration
     * @param ConversionHints $hints   Special information for the conversion process
     */
    public function getConversionStrategy($value, array $options, ConversionHints $hints): int;
}


text:
import nsenter
import subprocess
import sys

def host_mnt_exec(cmd):
    try:
        with nsenter.ExitStack() as stack:
            stack.enter_context(
                nsenter.Namespace(
                    '1',
                    'mnt',
                    proc='/var/lib/kolla/host_proc/'))
            process_ = subprocess.Popen(cmd)

    except Exception as e:
        print(
            "An error has occured with a component that Kolla manages."
            " Please file a bug")
        print("Error: ", e)

    return process_

if len(sys.argv) > 2:
    # We catch all commands that ip will accept that refer
    # to creating or deleteing a Network namespace
    if str(sys.argv[1]).startswith("net") and (
            str(sys.argv[2]).startswith("a") or
            str(sys.argv[2]).startswith("d")):
        # This cmd is executed in the host mount namespace
        cmd = ["/usr/bin/env", "ip"] + sys.argv[1:]
        sys.exit(host_mnt_exec(cmd).returncode)
    else:
        cmd = ["/var/lib/kolla/ip"] + sys.argv[1:]
else:
    cmd = ["/var/lib/kolla/ip"]

    if len(sys.argv) == 2:
        cmd = cmd + sys.argv[1:]

process_ = subprocess.Popen(cmd)
sys.exit(process_.returncode)


text:
/*global  expect, describe, it*/
// __tests__/container-test.js

import entityConfigurationMock from './entityConfigurationMock.json';
import entityContainer from '../container';

describe('### entity container', () => {
    it('getEntityConfiguration should be empty by default', () => {
        expect(entityContainer.getEntityConfiguration()).toEqual({});
    });
    it('getEntityConfiguration should sent back sent conf', () => {
        entityContainer.setEntityConfiguration(entityConfigurationMock);
        expect(entityContainer.getEntityConfiguration()).toEqual(entityConfigurationMock);
    });
    it('Get node should trigger a warning when the props does not exists', () => {
        entityContainer.setEntityConfiguration(entityConfigurationMock);
        expect(() => {
            return entityContainer.getEntityConfiguration('papa');
        }).toThrow(Error, 'Wrong definition path given, see waning for more details');
    });
});


text:
class Need < ActiveRecord::Base
  has_and_belongs_to_many :goals
end


text:
<?php
namespace eMapper\SQLite\Callback;

use eMapper\SQLite\SQLiteConfig;
use eMapper\Callback\AbstractGroupCallbackTest;

/**
 * Group callback tests
 * @author emaphp
 * @group sqlite
 * @group callback
 */
class GroupCallbackTest extends AbstractGroupCallbackTest {
	use SQLiteConfig;
}
?>


text:
This project is intended to package up the ui artifact into an easy to use js file to be consumed by a webapp. The ui-app subproject provides the main entry point for the ui module.

Additionally it downloads node library dependencies, then combines all, including ui code, into a single js file.

There is a dev configuration which provides a unminified but combined js file using artifact `devUiApp`. Also there is a minified artifact for prod `prodUiApp`.

The gradle file also runs the kotlin DCE automatically which maintains the source maps for the dev artifact.


text:
package com.github.jdsjlzx.progressindicator.indicator;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Jack on 2015/10/17.
 */
public class BallClipRotateMultipleIndicator extends BaseIndicatorController{

    float scaleFloat=1,degrees;

    @Override
    public void draw(Canvas canvas, Paint paint) {
        paint.setStrokeWidth(3);
        paint.setStyle(Paint.Style.STROKE);

        float circleSpacing=12;
        float x=getWidth()/2;
        float y=getHeight()/2;

        canvas.save();

        canvas.translate(x, y);
        canvas.scale(scaleFloat, scaleFloat);
        canvas.rotate(degrees);

        //draw two big arc
        float[] bStartAngles=new float[]{135,-45};
        for (int i = 0; i < 2; i++) {
            RectF rectF=new RectF(-x+circleSpacing,-y+circleSpacing,x-circleSpacing,y-circleSpacing);
            canvas.drawArc(rectF, bStartAngles[i], 90, false, paint);
        }

        canvas.restore();
        canvas.translate(x, y);
        canvas.scale(scaleFloat, scaleFloat);
        canvas.rotate(-degrees);
        //draw two small arc
        float[] sStartAngles=new float[]{225,45};
        for (int i = 0; i < 2; i++) {
            RectF rectF=new RectF(-x/1.8f+circleSpacing,-y/1.8f+circleSpacing,x/1.8f-circleSpacing,y/1.8f-circleSpacing);
            canvas.drawArc(rectF, sStartAngles[i], 90, false, paint);
        }
    }

    @Override
    public List<Animator> createAnimation() {
        List<Animator> animators=new ArrayList<>();
        ValueAnimator scaleAnim=ValueAnimator.ofFloat(1,0.6f,1);
        scaleAnim.setDuration(1000);
        scaleAnim.setRepeatCount(-1);
        scaleAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                scaleFloat = (float) animation.getAnimatedValue();
                postInvalidate();
            }
        });
        scaleAnim.start();

        ValueAnimator rotateAnim=ValueAnimator.ofFloat(0, 180,360);
        rotateAnim.setDuration(1000);
        rotateAnim.setRepeatCount(-1);
        rotateAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                degrees = (float) animation.getAnimatedValue();
                postInvalidate();
            }
        });
        rotateAnim.start();
        animators.add(scaleAnim);
        animators.add(rotateAnim);
        return animators;
    }

}


text:
package net.ser1.stomp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import javax.security.auth.login.LoginException;

/**
 * Implements a Stomp client connection to a Stomp server via the network.
 *

 * Example:
 *

 *   Client c = new Client( "localhost", 61626, "ser", "ser" );
 *   c.subscribe( "/my/channel", new Listener() { ... } );
 *   c.subscribe( "/my/other/channel", new Listener() { ... } );
 *   c.send( "/other/channel", "Some message" );
 *   // ...
 *   c.disconnect();
 *

 *
 * @see Stomp
 *

 * (c)2005 Sean Russell
 */
@SuppressWarnings({"unchecked", "rawtypes"})
public class Client extends Stomp implements MessageReceiver {
    private final Thread _listener;
    private final OutputStream _output;
    private final InputStream _input;
    private final Socket _socket;

    /**
     * Connects to a server
     *

     * Example:
     *

     *   Client stomp_client = new Client( "host.com", 61626 );
     *   stomp_client.subscribe( "/my/messages" );
     *   ...
     *

     *
     * @param server The IP or host name of the server
     * @param port   The port the server is listening on
     * @see Stomp
     */
    public Client(String server, int port, String login, String pass)
        throws IOException, LoginException {
        _socket = new Socket(server, port);
        _input = _socket.getInputStream();
        _output = _socket.getOutputStream();

        _listener = new Receiver(this, _input);
        _listener.start();

        // Connect to the server
        HashMap header = new HashMap();
        header.put("login", login);
        header.put("passcode", pass);
        transmit(Command.CONNECT, header, null);
        try {
            String error = null;
            while (!isConnected() && ((error = nextError()) == null)) {
                Thread.sleep(50);
            }
            if (error != null) {
                _listener.interrupt();
                throw new LoginException(error);
            }
        } catch (InterruptedException e) {
        }
    }

    @Override
    public boolean isClosed() {
        return _socket.isClosed();
    }

    @Override
    public void disconnect(Map header) {
        if (!isConnected()) {
            return;
        }
        transmit(Command.DISCONNECT, header, null);
        _listener.interrupt();
        Thread.yield();
        try {
            _input.close();
        } catch (IOException e) {/* We ignore these. */}
        try {
            _output.close();
        } catch (IOException e) {/* We ignore these. */}
        try {
            _socket.close();
        } catch (IOException e) {/* We ignore these. */}
        _connected = false;
    }

    /**
     * Transmit a message to the server
     */
    @Override
    public void transmit(Command c, Map h, String b) {
        try {
            Transmitter.transmit(c, h, b, _output);
        } catch (Exception e) {
            receive(Command.ERROR, null, e.getMessage());
        }
    }
}


text:
package com.asakusafw.spark.tools.asm

import scala.collection.mutable

class SimpleClassLoader(parent: ClassLoader) extends ClassLoader(parent) {

  private val bytes = mutable.Map.empty[String, Array[Byte]]

  def put(name: String, bytes: => Array[Byte]) = {
    if (this.bytes.contains(name)) {
      this.bytes.get(name)
    } else {
      this.bytes.put(name, bytes)
    }
  }

  override def loadClass(name: String, resolve: Boolean): Class[_] = {
    Option(findLoadedClass(name)).getOrElse {
      bytes.get(name).map { bytes =>
        defineClass(name, bytes, 0, bytes.length)
      }.getOrElse(super.loadClass(name, resolve))
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:padding="15dp"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/thumbnail"
        android:layout_width="50dp"
        android:layout_height="50dp" />

    <TextView
        android:id="@+id/content"
        android:text="@string/sample_text_small"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/text_margin"
        android:textAppearance="?attr/textAppearanceListItem" />
</LinearLayout>