text:
namespace v8 {
namespace internal {

class BytecodeArray;
class FixedArray;
class Isolate;

namespace interpreter {

class SourcePositionTableBuilder {
 public:
  explicit SourcePositionTableBuilder(Isolate* isolate, Zone* zone)
      : isolate_(isolate), entries_(zone) {}

  void AddStatementPosition(size_t bytecode_offset, int source_position);
  void AddExpressionPosition(size_t bytecode_offset, int source_position);
  void RevertPosition(size_t bytecode_offset);
  Handle<FixedArray> ToFixedArray();

 private:
  struct Entry {
    int bytecode_offset;
    uint32_t source_position_and_type;
  };

  bool CodeOffsetHasPosition(int bytecode_offset) {
    // Return whether bytecode offset already has a position assigned.
    return entries_.size() > 0 &&
           entries_.back().bytecode_offset == bytecode_offset;
  }

  Isolate* isolate_;
  ZoneVector<Entry> entries_;
};

class SourcePositionTableIterator {
 public:
  explicit SourcePositionTableIterator(BytecodeArray* bytecode_array);

  void Advance();

  int bytecode_offset() const {
    DCHECK(!done());
    return bytecode_offset_;
  }
  int source_position() const {
    DCHECK(!done());
    return source_position_;
  }
  bool is_statement() const {
    DCHECK(!done());
    return is_statement_;
  }
  bool done() const { return index_ > length_; }

 private:
  FixedArray* table_;
  int index_;
  int length_;
  bool is_statement_;
  int bytecode_offset_;
  int source_position_;
  DisallowHeapAllocation no_gc;
};

}  // namespace interpreter
}  // namespace internal
}  // namespace v8

#endif  // V8_INTERPRETER_SOURCE_POSITION_TABLE_H_


text:
package is.hail.annotations

import is.hail.HailSuite
import is.hail.asm4s._
import is.hail.check.{Gen, Prop}
import is.hail.expr.ir.{EmitCode, EmitFunctionBuilder, IEmitCode, RequirednessSuite}
import is.hail.types.physical._
import is.hail.types.physical.stypes.concrete.SStringPointer
import is.hail.types.physical.stypes.interfaces._
import is.hail.types.physical.stypes.primitives.SInt32Value
import is.hail.types.virtual._
import is.hail.utils._
import org.apache.spark.sql.Row
import org.testng.annotations.Test

class StagedConstructorSuite extends HailSuite {

  val showRVInfo = true

  @Test
  def testCanonicalString() {
    val rt = PCanonicalString()
    val input = "hello"
    val fb = EmitFunctionBuilder[Region, String, Long](ctx, "fb")

    fb.emitWithBuilder { cb =>
      val st = SStringPointer(rt)
      val region = fb.emb.getCodeParam[Region](1)
      rt.store(cb, region, st.constructFromString(cb, region, fb.getCodeParam[String](2)), deepCopy = false)
    }

    val region = Region(pool=pool)
    val rv = RegionValue(region)
    rv.setOffset(fb.result(ctx)(theHailClassLoader)(region, input))

    if (showRVInfo) {
      printRegion(region, "string")
      println(rv.pretty(rt))
    }

    val region2 = Region(pool=pool)
    val rv2 = RegionValue(region2)
    val bytes = input.getBytes()
    val bt = PCanonicalBinary()
    val boff = bt.allocate(region2, bytes.length)
    bt.store(boff, bytes)
    rv2.setOffset(boff)

    if (showRVInfo) {
      printRegion(region2, "string")
      println(rv2.pretty(rt))
    }

    assert(rv.pretty(rt) == rv2.pretty(rt))
    assert(rt.loadString(rv.offset) ==
      rt.loadString(rv2.offset))
  }

  @Test
  def testInt() {
    val rt = PInt32()
    val input = 3
    val fb = EmitFunctionBuilder[Region, Int, Long](ctx, "fb")

    fb.emitWithBuilder { cb =>
      rt.store(cb, fb.emb.getCodeParam[Region](1), primitive(fb.getCodeParam[Int](2)), deepCopy = false)
    }

    val region = Region(pool=pool)
    val rv = RegionValue(region)
    rv.setOffset(fb.result(ctx)(theHailClassLoader)(region, input))

    if (showRVInfo) {
      printRegion(region, "int")
      println(rv.pretty(rt))
    }

    val region2 = Region(pool=pool)
    val rv2 = RegionValue(region2)
    rv2.setOffset(region2.allocate(4, 4))
    Region.storeInt(rv2.offset, input)

    if (showRVInfo) {
      printRegion(region2, "int")
      println(rv2.pretty(rt))
    }

    assert(rv.pretty(rt) == rv2.pretty(rt))
    assert(Region.loadInt(rv.offset) == Region.loadInt(rv2.offset))
  }

  @Test
  def testArray() {
    val rt = PCanonicalArray(PInt32())
    val input = 3
    val fb = EmitFunctionBuilder[Region, Int, Long](ctx, "fb")

    fb.emitWithBuilder { cb =>
      val region = fb.emb.getCodeParam[Region](1)
      val elt = fb.getCodeParam[Int](2)
      rt.constructFromElements(cb, region, const(1), false) { (cb, idx) =>
        IEmitCode.present(cb, primitive(elt))
      }.a
    }

    val region = Region(pool=pool)
    val rv = RegionValue(region)
    rv.setOffset(fb.result(ctx)(theHailClassLoader)(region, input))

    if (showRVInfo) {
      printRegion(region, "array")
      println(rv.pretty(rt))
    }

    val region2 = Region(pool=pool)
    val rv2 = RegionValue(region2)
    rv2.setOffset(ScalaToRegionValue(region2, rt, FastIndexedSeq(input)))

    if (showRVInfo) {
      printRegion(region2, "array")
      println(rv2.pretty(rt))
    }

    assert(rt.loadLength(rv.offset) == 1)
    assert(rv.pretty(rt) == rv2.pretty(rt))
    assert(Region.loadInt(rt.loadElement(rv.offset, 0)) ==
      Region.loadInt(rt.loadElement(rv2.offset, 0)))
  }

  @Test
  def testStruct() {
    val pstring = PCanonicalString()
    val rt = PCanonicalStruct("a" -> pstring, "b" -> PInt32())
    val input = 3
    val fb = EmitFunctionBuilder[Region, Int, Long](ctx, "fb")

    fb.emitWithBuilder { cb =>
      val region = fb.emb.getCodeParam[Region](1)
      rt.constructFromFields(cb, region, FastIndexedSeq(
        EmitCode.fromI(cb.emb) { cb =>
          val st = SStringPointer(pstring)
          IEmitCode.present(cb, st.constructFromString(cb, region, const("hello")))
        },
        EmitCode.fromI(cb.emb) { cb =>
          IEmitCode.present(cb, primitive(fb.getCodeParam[Int](2)))
        }
      ), deepCopy = false).a
    }

    val region = Region(pool=pool)
    val rv = RegionValue(region)
    rv.setOffset(fb.result(ctx)(theHailClassLoader)(region, input))

    if (showRVInfo) {
      printRegion(region, "struct")
      println(rv.pretty(rt))
    }

    val region2 = Region(pool=pool)
    val rv2 = RegionValue(region2)
    rv2.setOffset(ScalaToRegionValue(region2, rt, Annotation("hello", input)))

    if (showRVInfo) {
      printRegion(region2, "struct")
      println(rv2.pretty(rt))
    }

    assert(rv.pretty(rt) == rv2.pretty(rt))
    assert(rt.types(0).asInstanceOf[PString].loadString(rt.loadField(rv.offset, 0)) ==
      rt.types(0).asInstanceOf[PString].loadString(rt.loadField(rv2.offset, 0)))
    assert(Region.loadInt(rt.loadField(rv.offset, 1)) ==
      Region.loadInt(rt.loadField(rv2.offset, 1)))
  }

  @Test
  def testArrayOfStruct() {
    val structType = PCanonicalStruct("a" -> PInt32(), "b" -> PCanonicalString())
    val arrayType = PCanonicalArray(structType)
    val input = "hello"
    val fb = EmitFunctionBuilder[Region, String, Long](ctx, "fb")

    fb.emitWithBuilder { cb =>
      val region = fb.emb.getCodeParam[Region](1)

      arrayType.constructFromElements(cb, region, const(2), false) { (cb, idx) =>
        val st = SStringPointer(PCanonicalString())
        IEmitCode.present(cb, structType.constructFromFields(cb, region, FastIndexedSeq(
          EmitCode.fromI(cb.emb)(cb => IEmitCode.present(cb, primitive(cb.memoize(idx + 1)))),
          EmitCode.fromI(cb.emb)(cb => IEmitCode.present(cb, st.constructFromString(cb, region, fb.getCodeParam[String](2))))
        ), deepCopy = false))
      }.a
    }

    val region = Region(pool=pool)
    val rv = RegionValue(region)
    rv.setOffset(fb.result(ctx)(theHailClassLoader)(region, input))

    if (showRVInfo) {
      printRegion(region, "array of struct")
      println(rv.pretty(arrayType))
    }

    val region2 = Region(pool=pool)
    val rv2 = RegionValue(region2)
    val rvb = new RegionValueBuilder(region2)
    rvb.start(arrayType)
    rvb.startArray(2)
    for (i <- 1 to 2) {
      rvb.startStruct()
      rvb.addInt(i)
      rvb.addString(input)
      rvb.endStruct()
    }
    rvb.endArray()
    rv2.setOffset(rvb.end())

    if (showRVInfo) {
      printRegion(region2, "array of struct")
      println(rv2.pretty(arrayType))
    }

    assert(rv.pretty(arrayType) == rv2.pretty(arrayType))
    assert(new UnsafeIndexedSeq(arrayType, rv.region, rv.offset).sameElements(
      new UnsafeIndexedSeq(arrayType, rv2.region, rv2.offset)))
  }

  @Test
  def testMissingRandomAccessArray() {
    val rt = PCanonicalArray(PCanonicalStruct("a" -> PInt32(), "b" -> PCanonicalString()))
    val intVal = 20
    val strVal = "a string with a partner of 20"
    val region = Region(pool=pool)
    val region2 = Region(pool=pool)
    val rvb = new RegionValueBuilder(region)
    val rvb2 = new RegionValueBuilder(region2)
    val rv = RegionValue(region)
    val rv2 = RegionValue(region2)
    rvb.start(rt)
    rvb.startMissingArray(4)
    rvb.setArrayIndex(2)
    rvb.setPresent()
    rvb.startStruct()
    rvb.addInt(intVal)
    rvb.addString(strVal)
    rvb.endStruct()
    rvb.endArrayUnchecked()
    rv.setOffset(rvb.end())

    rvb2.start(rt)
    rvb2.startArray(4)
    for (i <- 0 to 3) {
      if (i == 2) {
        rvb2.startStruct()
        rvb2.addInt(intVal)
        rvb2.addString(strVal)
        rvb2.endStruct()
      } else {
        rvb2.setMissing()
      }
    }
    rvb2.endArray()
    rv2.setOffset(rvb2.end())
    assert(rv.pretty(rt) == rv2.pretty(rt))
    assert(new UnsafeIndexedSeq(rt, rv.region, rv.offset).sameElements(
      new UnsafeIndexedSeq(rt, rv2.region, rv2.offset)))
  }

  @Test
  def testSetFieldPresent() {
    val rt = PCanonicalStruct("a" -> PInt32(), "b" -> PCanonicalString(), "c" -> PFloat64())
    val intVal = 30
    val floatVal = 39.273d
    val r = Region(pool=pool)
    val r2 = Region(pool=pool)
    val rv = RegionValue(r)
    val rv2 = RegionValue(r2)
    val rvb = new RegionValueBuilder(r)
    val rvb2 = new RegionValueBuilder(r2)
    rvb.start(rt)
    rvb.startStruct()
    rvb.setMissing()
    rvb.setMissing()
    rvb.addDouble(floatVal)
    rvb.setFieldIndex(0)
    rvb.setPresent()
    rvb.addInt(intVal)
    rvb.setFieldIndex(3)
    rvb.endStruct()
    rv.setOffset(rvb.end())

    rvb2.start(rt)
    rvb2.startStruct()
    rvb2.addInt(intVal)
    rvb2.setMissing()
    rvb2.addDouble(floatVal)
    rvb2.endStruct()
    rv2.setOffset(rvb2.end())

    assert(rv.pretty(rt) == rv2.pretty(rt))
    assert(Region.loadInt(rt.loadField(rv.offset, 0)) ==
      Region.loadInt(rt.loadField(rv2.offset, 0)))
    assert(Region.loadDouble(rt.loadField(rv.offset, 2)) ==
      Region.loadDouble(rt.loadField(rv2.offset, 2)))
  }

  @Test
  def testStructWithArray() {
    val tArray = PCanonicalArray(PInt32())
    val rt = PCanonicalStruct("a" -> PCanonicalString(), "b" -> tArray)
    val input = "hello"
    val fb = EmitFunctionBuilder[Region, String, Long](ctx, "fb")

    fb.emitWithBuilder { cb =>
      val region = fb.emb.getCodeParam[Region](1)
      rt.constructFromFields(cb, region, FastIndexedSeq(
        EmitCode.fromI(cb.emb)(cb =>
          IEmitCode.present(cb,
            SStringPointer(PCanonicalString()).constructFromString(cb, region, fb.getCodeParam[String](2)))),
        EmitCode.fromI(cb.emb)(cb =>
          IEmitCode.present(cb,
            tArray.constructFromElements(cb, region, const(2), deepCopy = false) { (cb, idx) =>
              IEmitCode.present(cb, primitive(cb.memoize(idx + 1)))
            }))
      ), deepCopy = false).a
    }

    val region = Region(pool=pool)
    val rv = RegionValue(region)
    rv.setOffset(fb.result(ctx)(theHailClassLoader)(region, input))

    if (showRVInfo) {
      printRegion(region, "struct with array")
      println(rv.pretty(rt))
    }

    val region2 = Region(pool=pool)
    val rv2 = RegionValue(region2)
    val rvb = new RegionValueBuilder(region2)

    rvb.start(rt)
    rvb.startStruct()
    rvb.addString(input)
    rvb.startArray(2)
    for (i <- 1 to 2) {
      rvb.addInt(i)
    }
    rvb.endArray()
    rvb.endStruct()

    rv2.setOffset(rvb.end())

    if (showRVInfo) {
      printRegion(region2, "struct with array")
      println(rv2.pretty(rt))
    }

    assert(rv.pretty(rt) == rv2.pretty(rt))
    assert(new UnsafeRow(rt, rv.region, rv.offset) ==
      new UnsafeRow(rt, rv2.region, rv2.offset))
  }

  @Test
  def testMissingArray() {
    val rt = PCanonicalArray(PInt32())
    val input = 3
    val fb = EmitFunctionBuilder[Region, Int, Long](ctx, "fb")

    fb.emitWithBuilder { cb =>
      val region = fb.emb.getCodeParam[Region](1)
      rt.constructFromElements(cb, region, const(2), deepCopy = false) { (cb, idx) =>
        IEmitCode(cb, idx > 0, new SInt32Value(fb.getCodeParam[Int](2)))
      }.a
    }

    val region = Region(pool=pool)
    val rv = RegionValue(region)
    rv.setOffset(fb.result(ctx)(theHailClassLoader)(region, input))

    if (showRVInfo) {
      printRegion(region, "missing array")
      println(rv.pretty(rt))
    }

    val region2 = Region(pool=pool)
    val rv2 = RegionValue(region2)
    rv2.setOffset(ScalaToRegionValue(region2, rt, FastIndexedSeq(input, null)))

    if (showRVInfo) {
      printRegion(region2, "missing array")
      println(rv2.pretty(rt))
    }

    assert(rv.pretty(rt) == rv2.pretty(rt))
    assert(new UnsafeIndexedSeq(rt, rv.region, rv.offset).sameElements(
      new UnsafeIndexedSeq(rt, rv2.region, rv2.offset)))
  }

  def printRegion(region: Region, string: String) {
    println(region.prettyBits())
  }

  @Test
  def testAddPrimitive() {
    val t = PCanonicalStruct("a" -> PInt32(), "b" -> PBoolean(), "c" -> PFloat64())
    val fb = EmitFunctionBuilder[Region, Int, Boolean, Double, Long](ctx, "fb")

    fb.emitWithBuilder { cb =>
      val region = fb.emb.getCodeParam[Region](1)

      t.constructFromFields(cb, region, FastIndexedSeq(
        EmitCode.fromI(cb.emb)(cb => IEmitCode.present(cb, primitive(fb.getCodeParam[Int](2)))),
        EmitCode.fromI(cb.emb)(cb => IEmitCode.present(cb, primitive(fb.getCodeParam[Boolean](3)))),
        EmitCode.fromI(cb.emb)(cb => IEmitCode.present(cb, primitive(fb.getCodeParam[Double](4))))
      ), deepCopy = false).a
    }

    val region = Region(pool=pool)
    val f = fb.result(ctx)(theHailClassLoader)
    def run(i: Int, b: Boolean, d: Double): (Int, Boolean, Double) = {
      val off = f(region, i, b, d)
      (Region.loadInt(t.loadField(off, 0)),
        Region.loadBoolean(t.loadField(off, 1)),
        Region.loadDouble(t.loadField(off, 2)))
    }

    assert(run(3, true, 42.0) == ((3, true, 42.0)))
    assert(run(42, false, -1.0) == ((42, false, -1.0)))
  }

  @Test def testDeepCopy() {
    val g = Type.genStruct
      .flatMap(t => Gen.zip(Gen.const(t), t.genValue))
      .filter { case (t, a) => a != null }
      .map { case (t, a) => (PType.canonical(t).asInstanceOf[PStruct], a) }

    val p = Prop.forAll(g) { case (t, a) =>
      assert(t.virtualType.typeCheck(a))
      val copy = pool.scopedRegion { region =>
        val copyOff = pool.scopedRegion { srcRegion =>
          val src = ScalaToRegionValue(srcRegion, t, a)

          val fb = EmitFunctionBuilder[Region, Long, Long](ctx, "deep_copy")
          fb.emitWithBuilder[Long](cb => t.store(cb,
            fb.apply_method.getCodeParam[Region](1),
            t.loadCheapSCode(cb, fb.apply_method.getCodeParam[Long](2)),
              deepCopy = true))
          val copyF = fb.resultWithIndex()(theHailClassLoader, ctx.fs, 0, region)
          val newOff = copyF(region, src)

          //clear old stuff
          val len = srcRegion.allocate(0) - src
          Region.storeBytes(src, Array.fill(len.toInt)(0.toByte))
          newOff
        }
        SafeRow(t, copyOff)
      }
      copy == a
    }
    p.check()
  }

  @Test def testUnstagedCopy() {
    val t1 = PCanonicalArray(PCanonicalStruct(
      true,
      "x1" -> PInt32(),
      "x2" -> PCanonicalArray(PInt32(), required = true),
      "x3" -> PCanonicalArray(PInt32(true), required = true),
      "x4" -> PCanonicalSet(PCanonicalStruct(true, "y" -> PCanonicalString(true)), required = false)
    ), required = false)
    val t2 = RequirednessSuite.deepInnerRequired(t1, false)

    val value = IndexedSeq(
      Row(1, IndexedSeq(1,2,3), IndexedSeq(0, -1), Set(Row("asdasdasd"), Row(""))),
      Row(1, IndexedSeq(), IndexedSeq(-1), Set(Row("aa")))
    )

    pool.scopedRegion { r =>
      val rvb = new RegionValueBuilder(r)
      val v1 = t2.unstagedStoreJavaObject(value, r)
      assert(SafeRow.read(t2, v1) == value)

      rvb.clear()
      rvb.start(t1)
      rvb.addRegionValue(t2, r, v1)
      val v2 = rvb.end()
      assert(SafeRow.read(t1, v2) == value)
    }
  }

  @Test def testStagedCopy() {
    val t1 = PCanonicalStruct(false, "a" -> PCanonicalArray(PCanonicalStruct(
      true,
      "x1" -> PInt32(),
      "x2" -> PCanonicalArray(PInt32(), required = true),
      "x3" -> PCanonicalArray(PInt32(true), required = true),
      "x4" -> PCanonicalSet(PCanonicalStruct(true, "y" -> PCanonicalString(true)), required = false)
    ), required = false))
    val t2 = RequirednessSuite.deepInnerRequired(t1, false).asInstanceOf[PCanonicalStruct]

    val value = IndexedSeq(
      Row(1, IndexedSeq(1,2,3), IndexedSeq(0, -1), Set(Row("asdasdasd"), Row(""))),
      Row(1, IndexedSeq(), IndexedSeq(-1), Set(Row("aa")))
    )

    val valueT2 = t2.types(0)
    pool.scopedRegion { r =>
      val v1 = valueT2.unstagedStoreJavaObject(value, r)
      assert(SafeRow.read(valueT2, v1) == value)

      val f1 = EmitFunctionBuilder[Long](ctx, "stagedCopy1")
      f1.emitWithBuilder { cb =>
        val region = f1.partitionRegion
        t2.constructFromFields(cb, region, FastIndexedSeq(EmitCode.present(cb.emb, t2.types(0).loadCheapSCode(cb, v1))), deepCopy = false).a
      }
      val cp1 = f1.resultWithIndex()(theHailClassLoader, ctx.fs, 0, r)()
      assert(SafeRow.read(t2, cp1) == Row(value))

      val f2 = EmitFunctionBuilder[Long](ctx, "stagedCopy2")
      f2.emitWithBuilder { cb =>
        val region = f2.partitionRegion
        t1.constructFromFields(cb, region, FastIndexedSeq(EmitCode.present(cb.emb, t2.types(0).loadCheapSCode(cb, v1))), deepCopy = false).a
      }
      val cp2 = f2.resultWithIndex()(theHailClassLoader, ctx.fs, 0, r)()
      assert(SafeRow.read(t1, cp2) == Row(value))
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<it.gmariotti.cardslib.library.view.CardViewNative xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/carddemo"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardBackgroundColor="@android:color/white"
    android:layout_marginLeft="15dp"
    android:layout_marginRight="15dp"
    android:layout_marginTop="15dp">

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp">

    <ImageView
        android:layout_width="100dp"
        android:layout_height="70dp"
        android:id="@+id/ivFoodImage"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:background="#ff2669c2"
        android:maxHeight="20dp"
        android:maxWidth="20dp"
        android:layout_marginRight="10dp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Option"
        android:id="@+id/tvOptionName"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/ivFoodImage"
        android:layout_toEndOf="@+id/ivFoodImage"
        android:textColor="#ff1622ff"
        android:paddingBottom="5dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="comment"
        android:id="@+id/tvComment"
        android:layout_below="@+id/tvOptionName"
        android:layout_toRightOf="@+id/ivFoodImage"
        android:layout_alignBottom="@+id/ivFoodImage"
        android:layout_toEndOf="@+id/ivFoodImage" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="price"
        android:id="@+id/tvPrice"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <RatingBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/ratingBar"
        android:layout_below="@+id/tvComment"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:focusable="false"
        android:isIndicator="true"
        android:progressDrawable="@drawable/ratingbar_red"
            />

<!--    style="?android:attr/ratingBarStyleSmall" -->

</RelativeLayout>
</it.gmariotti.cardslib.library.view.CardViewNative>


text:
<?php
namespace Concrete\Controller\SinglePage;

use PageController;
use Core;
use Page;
use Permissions;
use Concrete\Core\Entity\File\File as FileEntity;
use Concrete\Core\File\File;

class DownloadFile extends PageController
{
    protected $force = 0;

    /**
     * @param int $fID File ID
     * @param null|int $rcID
     */
    public function view($fID = 0, $rcID = null)
    {
        // get the file
        if ($fID > 0 && $this->app->make('helper/validation/numbers')->integer($fID)) {
            $file = File::getByID($fID);
            if ($file instanceof FileEntity && $file->getFileID() > 0) {
                $rcID = $this->app->make('helper/security')->sanitizeInt($rcID);
                if ($rcID > 0) {
                    $rc = Page::getByID($rcID, 'ACTIVE');
                    if (is_object($rc) && !$rc->isError()) {
                        $rcp = new Permissions($rc);
                        if ($rcp->canViewPage()) {
                            $this->set('rc', $rc);
                        }
                    }
                }
                $fp = new Permissions($file);
                if (!$fp->canViewFile()) {
                    return false;
                }

                // if file password is blank, download
                if (!$file->getPassword()) {
                    if ($this->force) {
                        return $this->force_download($file, $rcID);
                    } else {
                        return $this->download($file, $rcID);
                    }
                }
                // otherwise show the form
                $this->set('force', $this->force);
                $this->set('rcID', $rcID);
                $this->set('fID', $fID);
                $this->set('filename', $file->getFilename());
                $fre = $file->getFileResource();
                $this->set('filesize', $fre->getSize());
            }
        }
    }

    /**
     * @param int $fID File ID
     * @param null|int $rcID
     */
    public function force($fID = 0, $rcID = null)
    {
        $this->force = true;

        return $this->view($fID, $rcID);
    }

    /**
     * @param int $fID File ID
     */
    public function view_inline($fID = 0)
    {
        if ($fID > 0 && $this->app->make('helper/validation/numbers')->integer($fID)) {
            $file = File::getByID($fID);
            $fp = new Permissions($file);
            if (!$fp->canViewFile()) {
                return false;
            }

            $fre = $file->getFileResource();
            $fsl = $file->getFileStorageLocationObject()->getFileSystemObject();
            $mimeType = $file->getMimeType();
            header("Content-type: $mimeType");
            echo $file->getFileContents();
            $this->app->shutdown();
        }
    }

    /**
     * @param int $fID File ID
     */
    public function submit_password($fID = 0)
    {
        if ($fID > 0 && $this->app->make('helper/validation/numbers')->integer($fID)) {
            $f = File::getByID($fID);

            $rcID = $this->post('rcID');
            $rcID = $this->app->make('helper/security')->sanitizeInt($rcID);

            if ($f->getPassword() == $this->post('password')) {
                if ($this->post('force')) {
                    return $this->force_download($f);
                } else {
                    return $this->download($f);
                }
            }

            $this->set('error', t("Password incorrect. Please try again."));
            $this->set('force', ($this->post('force') ? 1 : 0));

            $this->view($fID, $rcID);
        }
    }

    /**
     * @param \Concrete\Core\Entity\File\File $file
     * @param null|int $rcID
     */
    protected function download(\Concrete\Core\Entity\File\File $file, $rcID = null)
    {
        $filename = $file->getFilename();
        $file->trackDownload($rcID);
        $fsl = $file->getFileStorageLocationObject();
        $configuration = $fsl->getConfigurationObject();
        $fv = $file->getVersion();
        if ($configuration->hasPublicURL()) {
            return \Redirect::url($fv->getURL(),'303')->send();
        } else {
            return $fv->forceDownload();
        }
    }

    /**
     * Forces the download of a file and shuts down.
     * Returns null if approved version wasn't found.
     *
     * @param File $file
     * @param null|int $rcID
     */
    protected function force_download($file, $rcID = null)
    {
        $file->trackDownload($rcID);

        // Magic call to approved FileVersion
        return $file->forceDownload();
    }
}


text:
import main

def test():
    main.test()


text:
<?php

namespace Koalamon\GraphiteBundle\Graphite;

use Koalamon\IncidentDashboardBundle\Entity\Event;
use Koalamon\IncidentDashboardBundle\Entity\EventIdentifier;

interface Connector
{
    const TYPE_STATUS = 'status';
    const TYPE_VALUE = 'value';

    public function getPlainGraphUrl(EventIdentifier $eventIdentifier, $timeSpan = '24h');

    public function getAvgValue(EventIdentifier $eventIdentifier, $type = Connector::TYPE_STATUS, $time = '24h', $from = "-1month");

    public function sendEvent(Event $event);

    public function isRunning();
}


text:
package jfmi.gui;

import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;

/** A SortOptionsDialog provides a JDialog wrapper frame for a SortOptionsBox.
  It provides methods for clients to display the options to the user, and
  determine what action the user took (e.g. changed an option selection).
  */
public class SortOptionsDialog extends JDialog {

	// PRIVATE Instance Fields
	JButton confirmButton;

	SortOptionsBox optionsBox;
	String fieldWhenDisplayed;
	String orderWhenDisplayed;

	//************************************************************
	// PUBLIC Instance Methods
	//************************************************************

	/** Constructs a new SortOptionsDialog with the specified parent frame,
	  the specified ActionListener for a confirmation click, and the specified
	  sort options box.
	  @param parent this dialog's parent JFrame
	  @param confirmListener ActionListener to alert when user confirms
	  @param opBox the SortOptionsBox this instance wraps
	  @throws NullPointerException if opBox is null
	  */
	public SortOptionsDialog(
			JFrame parent,
			ActionListener confirmListener,
			SortOptionsBox opBox
	)
	{
		// Initialize the Dialog itself
		super(parent, "Sorting Options", true);
		setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
		setMinimumSize(new Dimension(200, 150));
		setResizable(false);
		setVisible(false);
		addWindowListener(
			new WindowAdapter() {
				public void windowClosing(WindowEvent e)
				{
					cancelSelections();
					setVisible(false);
				}
			}
		);

		// Initialize options box
		if (opBox == null) {
			throw new NullPointerException("opBox cannot be null");
		}
		optionsBox = opBox;

		// Initialize buttons
		confirmButton = new JButton("Confirm");
		confirmButton.addActionListener(confirmListener);

		// Set up components/layout
		Box contentBox = Box.createVerticalBox();
		contentBox.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentBox.add(optionsBox);
		contentBox.add(Box.createVerticalStrut(5));
		contentBox.add(confirmButton);

		add(contentBox);
		pack();
	}

	/** Checks whether the last selected field and currently selected field
	  differ.
	  @return true if the old and new field values are different
	  */
	public boolean fieldChanged()
	{
		return optionsBox.fieldChanged();
	}

	/** Accesses the button used to confirm a selection.
	  @return a reference to the button which generates a confirming ActionEvent
	  */
	public JButton getConfirmButton()
	{
		return confirmButton;
	}

	/** Returns a possible null reference to the last selected field. */
	public String getLastSelectedField()
	{
		return optionsBox.getLastSelectedField();
	}

	/** Returns a possible null reference to the last selected order. */
	public String getLastSelectedOrder()
	{
		return optionsBox.getLastSelectedOrder();
	}

	/** Gets the value of the currently selected field sorting option.
	  @return the selected field; null if empty set or none selected
	  */
	public String getSelectedField()
	{
		return optionsBox.getSelectedField();
	}

	/** Gets the value of the currently selected order sorting option.
	  @return the selected order; null if empty set or none selected
	  */
	public String getSelectedOrder()
	{
		return optionsBox.getSelectedOrder();
	}

	/** Checks whether the last selected order and currently selected order
	  differ.
	  @return true if the old and new order values are different
	  */
	public boolean orderChanged()
	{
		return optionsBox.orderChanged();
	}

	@Override
	/**
	  */
	public void setVisible(boolean b)
	{
		if (isVisible() && b == false) {
			super.setVisible(false);

		} else if (!isVisible() && b == true) {
			fieldWhenDisplayed = optionsBox.getSelectedField();
			orderWhenDisplayed = optionsBox.getSelectedOrder();

			super.setVisible(true);
		}
	}

	//************************************************************
	// PRIVATE Instance Methods
	//************************************************************

	/** Sets the selected field and order of this instance's child options
	  box to the values recorded when this instance dialog was displayed.
	  */
	private void cancelSelections()
	{
		optionsBox.setSelectedField(fieldWhenDisplayed);
		optionsBox.setSelectedOrder(orderWhenDisplayed);
	}

}


text:
<?php

declare(strict_types=1);

namespace App\Tests\Endpoints;

use App\Tests\Fixture\LoadCohortData;
use App\Tests\Fixture\LoadCourseClerkshipTypeData;
use App\Tests\Fixture\LoadCourseData;
use App\Tests\Fixture\LoadCourseLearningMaterialData;
use App\Tests\Fixture\LoadCourseObjectiveData;
use App\Tests\Fixture\LoadIlmSessionData;
use App\Tests\Fixture\LoadOfferingData;
use App\Tests\Fixture\LoadProgramYearData;
use App\Tests\Fixture\LoadProgramYearObjectiveData;
use App\Tests\Fixture\LoadSchoolData;
use App\Tests\Fixture\LoadSessionData;
use App\Tests\Fixture\LoadSessionLearningMaterialData;
use App\Tests\Fixture\LoadSessionObjectiveData;
use App\Tests\Fixture\LoadTermData;
use App\Tests\Fixture\LoadUserData;
use DateTime;
use Symfony\Component\HttpFoundation\Response;
use App\Tests\DataLoader\IlmSessionData;
use App\Tests\DataLoader\OfferingData;
use App\Tests\DataLoader\SessionData;
use App\Tests\ReadWriteEndpointTest;

/**
 * Course API endpoint Test.
 * @group api_2
 */
class CourseTest extends ReadWriteEndpointTest
{
    protected string $testName =  'courses';

    protected function getFixtures(): array
    {
        return [
            LoadCourseData::class,
            LoadCourseClerkshipTypeData::class,
            LoadSchoolData::class,
            LoadUserData::class,
            LoadCohortData::class,
            LoadTermData::class,
            LoadCourseLearningMaterialData::class,
            LoadSessionData::class,
            LoadOfferingData::class,
            LoadProgramYearData::class,
            LoadSessionLearningMaterialData::class,
            LoadIlmSessionData::class,
            LoadProgramYearObjectiveData::class,
            LoadCourseObjectiveData::class,
            LoadSessionObjectiveData::class,
        ];
    }

    /**
     * @inheritDoc
     */
    public function putsToTest(): array
    {
        return [
            'title' => ['title', 'icicles are not a snack'],
            'level' => ['level', 3],
            'year' => ['year', 2022],
            'startDate' => ['startDate', '2017-02-14T00:00:00+00:00'],
            'endDate' => ['endDate', '2017-02-14T00:00:00+00:00'],
            'externalId' => ['externalId', 'devnull'],
            'externalIdNull' => ['externalId', null],
            'locked' => ['locked', true],
            'archived' => ['archived', true],
            'publishedAsTbd' => ['publishedAsTbd', true],
            'published' => ['published', false],
            'clerkshipType' => ['clerkshipType', 2],
            'removeClerkshipType' => ['clerkshipType', null],
            'school' => ['school', 2],
            'directors' => ['directors', [2]],
            'removeDirectors' => ['directors', []],
            'replaceDirectors' => ['directors', [4]],
            'administrators' => ['administrators', [2]],
            'studentAdvisors' => ['studentAdvisors', [1]],
            'cohorts' => ['cohorts', [2]],
            'terms' => ['terms', [2]],
            'courseObjectives' => ['courseObjectives', [1]],
            'meshDescriptors' => ['meshDescriptors', ['abc3']],
            'learningMaterials' => ['learningMaterials', [1], $skipped = true],
            'sessions' => ['sessions', [1], $skipped = true],
            'ancestor' => ['ancestor', 2],
            'descendants' => ['descendants', ['3'], $skipped = true],
        ];
    }

    /**
     * @inheritDoc
     */
    public function readOnlyPropertiesToTest(): array
    {
        return [
            'id' => ['id', 1, 99],
        ];
    }

    /**
     * @inheritDoc
     */
    public function filtersToTest(): array
    {
        return [
            'id' => [[0], ['id' => 1]],
            'ids' => [[0, 2], ['id' => [1, 3]]],
            'title' => [[0], ['title' => 'firstCourse']],
            'level' => [[3, 4], ['level' => 3]],
            'year' => [[1, 2], ['year' => 2012]],
            'startDate' => [[1], ['startDate' => '2013-09-01T00:00:00+00:00'], $skipped = true],
            'endDate' => [[2], ['endDate' => '2013-12-14T00:00:00+00:00'], $skipped = true],
            'externalId' => [[2], ['externalId' => 'course3']],
            'locked' => [[4], ['locked' => true]],
            'archived' => [[4], ['archived' => true]],
            'publishedAsTbd' => [[4], ['publishedAsTbd' => true]],
            'published' => [[0, 4], ['published' => true]],
            'clerkshipType' => [[0, 1], ['clerkshipType' => 1]],
            'school' => [[2, 3, 4], ['school' => 2]],
            'schools' => [[2, 3, 4], ['schools' => [2]]],
            'directors' => [[1, 3], ['directors' => [2]], $skipped = true],
            'administrators' => [[0], ['administrators' => [1]], $skipped = true],
            'cohorts' => [[2], ['cohorts' => [2]], $skipped = true],
            'terms' => [[0, 1], ['terms' => [1]]],
            'meshDescriptors' => [[0, 1, 3], ['meshDescriptors' => ['abc1', 'abc2']]],
            'learningMaterials' => [[0, 1, 3], ['learningMaterials' => [1, 3]]],
            'sessions' => [[1], ['sessions' => [3]]],
            'ancestor' => [[3], ['ancestor' => 3]],
            'ancestors' => [[3], ['ancestors' => [3]]],
            'descendants' => [[0], ['descendants' => [1]], $skipped = true],
            'programs' => [[3, 4], ['programs' => [2]]],
            'instructors' => [[0, 1, 3], ['instructors' => [1, 2]]],
            'instructorGroups' => [[0, 1], ['instructorGroups' => [1]]],
            'programYears' => [[2], ['programYears' => [2]]],
            'competencies' => [[0], ['competencies' => [1]]],
            'yearAndLevel' => [[3, 4], ['level' => 3, 'year' => 2013]],
            'yearAndSchool' => [[3, 4], ['school' => 2, 'year' => 2013]],
        ];
    }

    public function testGetMyCourses()
    {
        $dataLoader = $this->getDataLoader();
        $all = $dataLoader->getAll();
        $this->filterTest(
            ['my' => true],
            [$all[0], $all[1], $all[3]]
        );
    }

    public function testGetMyCoursesSorted()
    {
        $dataLoader = $this->getDataLoader();
        $all = $dataLoader->getAll();
        $this->filterTest(
            ['my' => true, 'order_by[year]' => 'ASC', 'order_by[id]' => 'DESC'],
            [$all[1], $all[3], $all[0]]
        );
    }

    public function testGetMyCoursesFailureOnBogusOrderBy()
    {
        $this->badFilterTest(
            ['my' => true, 'order_by[glefarknik]' => 'ASC']
        );
    }

    public function testGetMyCoursesFailureOnBogusFilterBy()
    {
        $this->badFilterTest(
            ['my' => true, 'filters[farnk]' => 1]
        );
    }

    public function testGetMyCoursesWithLimit()
    {
        $dataLoader = $this->getDataLoader();
        $all = $dataLoader->getAll();
        $this->filterTest(
            ['my' => true, 'limit' => 2],
            [$all[0], $all[1]]
        );
    }

    public function testGetMyCoursesWithLimitAndOffset()
    {
        $dataLoader = $this->getDataLoader();
        $all = $dataLoader->getAll();
        $this->filterTest(
            ['my' => true, 'limit' => 1, 'offset' => 1],
            [$all[1]]
        );
    }

    public function testGetMyCoursesFilteredByYear()
    {
        $dataLoader = $this->getDataLoader();
        $all = $dataLoader->getAll();
        $this->filterTest(
            ['my' => true, 'filters[year]' => '2012'],
            [$all[1]]
        );

        $this->filterTest(
            ['my' => true, 'filters[year]' => '2013'],
            [$all[3]]
        );

        $this->filterTest(
            ['my' => true, 'filters[year]' => ['2012', '2013']],
            [$all[1], $all[3]]
        );
    }

    /**
     * Ember doesn't send the non-owning side of many2one relationships
     */
    public function testPutCourseWithoutSessionsAndLms()
    {
        $dataLoader = $this->getDataLoader();
        $data = $dataLoader->getOne();

        $postData = $data;
        unset($postData['sessions']);
        unset($postData['learningMaterials']);

        $this->putTest($data, $postData, $data['id']);
    }

    public function testRolloverCourse()
    {
        $dataLoader = $this->getDataLoader();
        $course = $dataLoader->getOne();

        $newCourse = $this->rolloverCourse([
            'id' => $course['id'],
            'year' => 2023,
            'newStartDate' => 'false',
            'skipOfferings' => 'false',
        ]);

        $this->assertSame($course['title'], $newCourse['title']);
        $this->assertSame($course['level'], $newCourse['level']);
        $this->assertSame($course['externalId'], $newCourse['externalId']);
        $this->assertSame(2023, $newCourse['year']);
        $this->assertSame('2023-09-03T00:00:00+00:00', $newCourse['startDate']);
        $this->assertSame('2023-12-31T00:00:00+00:00', $newCourse['endDate']);
        $this->assertFalse($newCourse['locked']);
        $this->assertFalse($newCourse['archived']);
        $this->assertFalse($newCourse['published']);
        $this->assertFalse($newCourse['publishedAsTbd']);

        $this->assertEquals($course['clerkshipType'], $newCourse['clerkshipType']);
        $this->assertEquals($course['school'], $newCourse['school']);
        $this->assertEquals($course['directors'], $newCourse['directors']);
        $this->assertEmpty($newCourse['cohorts']);
        $this->assertEquals($course['terms'], $newCourse['terms']);
        $this->assertSame(count($course['courseObjectives']), count($newCourse['courseObjectives']));
        $this->assertEquals($course['meshDescriptors'], $newCourse['meshDescriptors']);
        $this->assertSame(count($course['learningMaterials']), count($newCourse['learningMaterials']));
        $this->assertEquals($course['id'], $newCourse['ancestor']);

        $newSessions = $newCourse['sessions'];
        $this->assertEquals(count($newSessions), 2);
        $sessions = self::getContainer()->get(SessionData::class)->getAll();
        $lastSessionId = array_pop($sessions)['id'];

        $this->assertEquals($lastSessionId + 1, $newSessions[0], 'incremented session id 1');
        $this->assertEquals($lastSessionId + 2, $newSessions[1], 'incremented session id 2');

        $newSessionsData = $this->getFiltered('sessions', 'sessions', ['filters[id]' => $newSessions]);
        $offerings = self::getContainer()->get(OfferingData::class)->getAll();
        $lastOfferingId = array_pop($offerings)['id'];

        $firstSessionOfferings = array_map('strval', [$lastOfferingId + 1, $lastOfferingId + 2]);
        $secondSessionOfferings = array_map('strval', [$lastOfferingId + 3, $lastOfferingId + 4, $lastOfferingId + 5]);

        $this->assertEquals($firstSessionOfferings, $newSessionsData[0]['offerings']);
        $this->assertEquals($secondSessionOfferings, $newSessionsData[1]['offerings']);
    }

    public function testRolloverCourseWithStartDate()
    {
        $dataLoader = $this->getDataLoader();
        $course = $dataLoader->getOne();

        $newCourse = $this->rolloverCourse([
            'id' => $course['id'],
            'year' => 2023,
            'newStartDate' => '2023-02-05'
        ]);

        $this->assertSame(2023, $newCourse['year']);
        $this->assertSame('2023-02-05T00:00:00+00:00', $newCourse['startDate'], 'start date is correct');
        $this->assertSame('2023-06-04T00:00:00+00:00', $newCourse['endDate'], 'end date is correct');

        $newSessions = $newCourse['sessions'];
        $this->assertEquals(count($newSessions), 2);

        $newSessionsData = $this->getFiltered('sessions', 'sessions', ['filters[id]' => $newSessions]);

        $session1Offerings = $newSessionsData[0]['offerings'];
        $session1OfferingData = $this->getFiltered('offerings', 'offerings', ['filters[id]' => $session1Offerings]);

        $this->assertEquals('2023-02-09T15:00:00+00:00', $session1OfferingData[0]['startDate']);
    }

    public function testRolloverCourseWithNoOfferings()
    {
        $dataLoader = $this->getDataLoader();
        $course = $dataLoader->getOne();

        $newCourse = $this->rolloverCourse([
            'id' => $course['id'],
            'year' => 2030,
            'skipOfferings' => true
        ]);

        $this->assertSame(2030, $newCourse['year']);
        $newSessions = $newCourse['sessions'];
        $this->assertEquals(count($newSessions), 2);
        $sessions = self::getContainer()->get(SessionData::class)->getAll();
        $lastSessionId = array_pop($sessions)['id'];

        $this->assertEquals($lastSessionId + 1, $newSessions[0], 'incremented session id 1');
        $this->assertEquals($lastSessionId + 2, $newSessions[1], 'incremented session id 2');

        $data = $this->getFiltered('sessions', 'sessions', ['filters[id]' => $newSessions]);

        $this->assertEmpty($data[0]['offerings']);
        $this->assertEmpty($data[1]['offerings']);
    }

    public function testRolloverCourseWithNewTitle()
    {
        $dataLoader = $this->getDataLoader();
        $course = $dataLoader->getOne();
        /* KLUDGE!
         * Fix up the course's year to be last year.
         * Otherwise, rollover may bomb out with a "Courses cannot be rolled over to a new year before YYYY" error,
         * with YYYY being last year.
         * [ST 2018/01/02].
         */
        $course['year'] = intval(date('Y'), 10) - 1;
        $newCourseTitle = 'New (very cool) course title';

        $newCourse = $this->rolloverCourse([
            'id' => $course['id'],
            'year' => $course['year'],
            'newCourseTitle' => $newCourseTitle
        ]);

        $this->assertSame($course['year'], $newCourse['year']);
        $this->assertSame($newCourseTitle, $newCourse['title']);
    }

    public function testFailRolloverToPassedYear()
    {
        $dataLoader = $this->getDataLoader();
        $course = $dataLoader->getOne();
        $course['year'] = 2001; // most definitely yesteryear
        $newCourseTitle = 'Does not matter';

        $parameters = [
            'version' => $this->apiVersion,
            'id' => $course['id'],
            'year' => $course['year'],
            'newCourseTitle' => $newCourseTitle
        ];

        $this->createJsonRequest(
            'POST',
            $this->getUrl(
                $this->kernelBrowser,
                "app_api_courses_rollover",
                $parameters
            ),
            null,
            $this->getAuthenticatedUserToken($this->kernelBrowser)
        );

        $response = $this->kernelBrowser->getResponse();
        $this->assertJsonResponse($response, Response::HTTP_INTERNAL_SERVER_ERROR);
        $data = json_decode($response->getContent(), true);
        $this->assertStringContainsString('Courses cannot be rolled over to a new year before', $data['detail']);
    }

    public function testRolloverIlmSessions()
    {
        $dataLoader = $this->getDataLoader();
        $all = $dataLoader->getAll();
        $course = $all[1];

        $newCourse = $this->rolloverCourse([
            'id' => $course['id'],
            'year' => 2023,
        ]);

        $newSessionIds = $newCourse['sessions'];
        $this->assertEquals(count($newSessionIds), 5);

        $newSessionData = $this->getFiltered('sessions', 'sessions', ['filters[id]' => $newSessionIds]);

        $newSessionsWithILMs = array_filter($newSessionData, fn(array $session) => !empty($session['ilmSession']));
        $this->assertEquals(4, count($newSessionsWithILMs));

        $newIlmIds = array_map(fn(array $session) => $session['ilmSession'], $newSessionsWithILMs);
        $newIlmIds = array_values($newIlmIds);

        $ilms = self::getContainer()->get(IlmSessionData::class)->getAll();
        $lastIlmId = $ilms[key(array_slice($ilms, -1, 1, true))]['id'];

        $this->assertEquals($lastIlmId + 1, $newIlmIds[0], 'incremented ilm id 1');
        $this->assertEquals($lastIlmId + 2, $newIlmIds[1], 'incremented ilm id 2');
        $this->assertEquals($lastIlmId + 3, $newIlmIds[2], 'incremented ilm id 3');
        $this->assertEquals($lastIlmId + 4, $newIlmIds[3], 'incremented ilm id 4');

        $newIlmData = $this->getFiltered('ilmsessions', 'ilmSessions', ['filters[id]' => $newIlmIds]);

        $this->assertEquals($newIlmData[0]['hours'], $ilms[0]['hours']);
        $this->assertEquals($newIlmData[1]['hours'], $ilms[1]['hours']);
    }

    public function testRolloverCourseWithCohorts()
    {
        $dataLoader = $this->getDataLoader();
        $course = $dataLoader->getOne();

        $newCourse = $this->rolloverCourse([
            'id' => $course['id'],
            'year' => 2023,
            'newStartDate' => 'false',
            'skipOfferings' => 'true',
            'newCohorts' => [5]
        ]);

        $this->assertSame($course['title'], $newCourse['title']);
        $this->assertCount(1, $newCourse['cohorts']);
        $this->assertSame('5', $newCourse['cohorts'][0]);
        $this->assertSame(count($course['courseObjectives']), count($newCourse['courseObjectives']));
        $oldCourseObjectiveData = $this->getFiltered(
            'courseobjectives',
            'courseObjectives',
            ['filters[id]' => $course['courseObjectives']]
        );
        $newCourseObjectivesData = $this->getFiltered(
            'courseobjectives',
            'courseObjectives',
            ['filters[id]' => $newCourse['courseObjectives']]
        );

        $this->assertCount(count($oldCourseObjectiveData), $newCourseObjectivesData);
        $this->assertCount(1, $newCourseObjectivesData[0]['programYearObjectives']);
        $this->assertEquals('2', $newCourseObjectivesData[0]['programYearObjectives'][0]);
    }

    protected function rolloverCourse(array $rolloverDetails)
    {
        $parameters = array_merge([
            'version' => $this->apiVersion,
        ], $rolloverDetails);

        $this->createJsonRequest(
            'POST',
            $this->getUrl(
                $this->kernelBrowser,
                "app_api_courses_rollover",
                $parameters
            ),
            null,
            $this->getAuthenticatedUserToken($this->kernelBrowser)
        );

        $response = $this->kernelBrowser->getResponse();
        $this->assertJsonResponse($response, Response::HTTP_CREATED);
        $data = json_decode($response->getContent(), true)['courses'];

        $this->assertArrayHasKey(0, $data);

        return $data[0];
    }

    public function testRejectUnprivilegedPostCourse()
    {
        $dataLoader = $this->getDataLoader();
        $course = $dataLoader->getOne();
        $userId = 3;

        $this->canNot(
            $this->kernelBrowser,
            $userId,
            'POST',
            $this->getUrl(
                $this->kernelBrowser,
                "app_api_courses_post",
                ['version' => $this->apiVersion]
            ),
            json_encode(['courses' => [$course]])
        );
    }

    public function testRejectUnprivilegedPutCourse()
    {
        $dataLoader = $this->getDataLoader();
        $course = $dataLoader->getOne();
        $userId = 3;
        $id = $course['id'];

        $this->canNot(
            $this->kernelBrowser,
            $userId,
            'PUT',
            $this->getUrl(
                $this->kernelBrowser,
                "app_api_courses_put",
                ['version' => $this->apiVersion, 'id' => $id]
            ),
            json_encode(['course' => $course])
        );
    }

    public function testRejectUnprivilegedPutCourseWithWrongId()
    {
        $dataLoader = $this->getDataLoader();
        $course = $dataLoader->getOne();
        $userId = 3;
        $id = $course['id'];

        $this->canNot(
            $this->kernelBrowser,
            $userId,
            'PUT',
            $this->getUrl(
                $this->kernelBrowser,
                "app_api_courses_put",
                ['version' => $this->apiVersion, 'id' => $id * 10000]
            ),
            json_encode(['course' => $course])
        );
    }

    public function testRejectUnprivilegedDeleteCourse()
    {
        $dataLoader = $this->getDataLoader();
        $course = $dataLoader->getOne();
        $userId = 3;
        $id = $course['id'];

        $this->canNot(
            $this->kernelBrowser,
            $userId,
            'DELETE',
            $this->getUrl(
                $this->kernelBrowser,
                "app_api_courses_delete",
                ['version' => $this->apiVersion, 'id' => $id]
            )
        );
    }

    public function testRejectUnprivilegedRollover()
    {
        $dataLoader = $this->getDataLoader();
        $course = $dataLoader->getOne();
        $userId = 3;
        $id = $course['id'];

        $rolloverData = [
            'version' => $this->apiVersion,
            'id' => $id,
            'year' => 2023,
            'newStartDate' => 'false',
            'skipOfferings' => 'false',
        ];
        $this->canNot(
            $this->kernelBrowser,
            $userId,
            'POST',
            $this->getUrl($this->kernelBrowser, "app_api_courses_rollover", $rolloverData)
        );
    }

    public function testCourseCanBeUnlocked()
    {
        $dataLoader = $this->getDataLoader();
        $data = $dataLoader->getOne();
        $data['locked'] = true;
        $postData = $data;
        $responseData = $this->putTest($data, $postData, $data['id']);
        $this->assertTrue(
            $responseData['locked']
        );

        $dataLoader = $this->getDataLoader();
        $data = $dataLoader->getOne();
        $data['locked'] = false;
        $postData = $data;
        $responseData = $this->putTest($data, $postData, $data['id']);
        $this->assertFalse(
            $responseData['locked']
        );
    }

    public function testRemovingCourseObjectiveRemovesSessionObjectivesToo()
    {
        $dataLoader = $this->getDataLoader();
        $data = $dataLoader->getOne();
        $courseObjectiveId = $data['courseObjectives'][0];
        $courseObjective = $this->getOne('courseobjectives', 'courseObjectives', $courseObjectiveId);
        $sessionObjectiveId = $courseObjective['sessionObjectives'][0];
        $sessionObjective = $this->getOne('sessionobjectives', 'sessionObjectives', $sessionObjectiveId);
        // session objective is linked to course objective
        $this->assertTrue(in_array($courseObjective['id'], $sessionObjective['courseObjectives']));

        // remove course objective
        $data['courseObjectives'] = [];
        $postData = $data;
        $this->putOne('courses', 'course', $postData['id'], $postData);

        // verify that session objective is no longer linked to removed course objective
        $sessionObjective = $this->getOne('sessionobjectives', 'sessionObjectives', $sessionObjectiveId);
        $this->assertFalse(in_array($courseObjective['id'], $sessionObjective['courseObjectives']));
    }

    public function testPutCourseWithBadSchoolId()
    {
        $dataLoader = $this->getDataLoader();
        $data = $dataLoader->create();
        $data['school'] = 99;

        $this->badPostTest($data);
    }

    public function testPutCourseWithBadSessionId()
    {
        $dataLoader = $this->getDataLoader();
        $data = $dataLoader->create();
        $data['sessions'] = [1, 99, 14];

        $this->badPostTest($data);
    }

    public function testGetMyCoursesIncludesAdministeredCourses()
    {
        $dataLoader = $this->getDataLoader();
        $all = $dataLoader->getAll();
        $this->filterTest(
            ['my' => true],
            [$all[0], $all[2], $all[4]],
            4
        );
    }

    public function testIncludeBothProgramYearProgramAndObjectivesWithCohort()
    {
        $includes = $this->getJsonApiIncludes(
            'courses',
            '1',
            'cohorts.programYear.program,cohorts.programYear.programYearObjectives'
        );

        $this->assertArrayHasKey('programYears', $includes);
        $this->assertArrayHasKey('programs', $includes);
        $this->assertArrayHasKey('programYearObjectives', $includes);

        $this->assertIsArray($includes['programYears']);
        $this->assertEquals(['1'], $includes['programYears']);
        $this->assertIsArray($includes['programs']);
        $this->assertEquals(['1'], $includes['programs']);
        $this->assertIsArray($includes['programYearObjectives']);
        $this->assertEquals(['1'], $includes['programYearObjectives']);
    }

    public function testIncludeSessionDetails()
    {
        $sessionRelationships = [
            'learningMaterials.learningMaterial.owningUser',
            'sessionObjectives.courseObjectives',
            'sessionObjectives.meshDescriptors',
            'sessionObjectives.terms.vocabulary',
            'offerings.learners',
            'offerings.instructors',
            'offerings.instructorGroups.users',
            'offerings.learnerGroups.users',
            'ilmSession.learners',
            'ilmSession.instructors',
            'ilmSession.instructorGroups.users',
            'ilmSession.learnerGroups.users',
            'terms.vocabulary',
            'meshDescriptors.trees',
        ];
        $sessionIncludes = array_reduce($sessionRelationships, fn($carry, $item) => "${carry}sessions.${item},", '');

        $includes = $this->getJsonApiIncludes(
            'courses',
            '1',
            $sessionIncludes
        );

        $this->assertArrayHasKey('sessions', $includes);
        $this->assertArrayHasKey('terms', $includes);
        $this->assertArrayHasKey('vocabularies', $includes);
        $this->assertArrayHasKey('sessionObjectives', $includes);
        $this->assertArrayHasKey('courseObjectives', $includes);
        $this->assertArrayHasKey('meshDescriptors', $includes);
        $this->assertArrayHasKey('sessionLearningMaterials', $includes);
        $this->assertArrayHasKey('learningMaterials', $includes);
        $this->assertArrayHasKey('users', $includes);
        $this->assertArrayHasKey('offerings', $includes);
        $this->assertArrayHasKey('learnerGroups', $includes);
        $this->assertArrayHasKey('instructorGroups', $includes);

        $this->assertIsArray($includes['sessions']);
        $this->assertEquals(['1', '2'], $includes['sessions']);
        $this->assertIsArray($includes['terms']);
        $this->assertEquals(['1', '2', '3', '4', '5'], $includes['terms']);
        $this->assertIsArray($includes['vocabularies']);
        $this->assertEquals(['1', '2'], $includes['vocabularies']);
        $this->assertIsArray($includes['sessionObjectives']);
        $this->assertEquals(['1'], $includes['sessionObjectives']);
        $this->assertIsArray($includes['courseObjectives']);
        $this->assertEquals(['1'], $includes['courseObjectives']);
        $this->assertIsArray($includes['meshDescriptors']);
        $this->assertEquals(['abc1', 'abc2'], $includes['meshDescriptors']);
        $this->assertIsArray($includes['sessionLearningMaterials']);
        $this->assertEquals(['1'], $includes['sessionLearningMaterials']);
        $this->assertIsArray($includes['learningMaterials']);
        $this->assertEquals(['1'], $includes['learningMaterials']);
        $this->assertIsArray($includes['users']);
        $this->assertEquals(['1', '2', '4', '5'], $includes['users']);
        $this->assertIsArray($includes['offerings']);
        $this->assertEquals(['1', '2', '3', '4', '5'], $includes['offerings']);
        $this->assertIsArray($includes['learnerGroups']);
        $this->assertEquals(['1', '2', '5'], $includes['learnerGroups']);
        $this->assertIsArray($includes['instructorGroups']);
        $this->assertEquals(['1', '2'], $includes['instructorGroups']);
    }

    public function testIncludedDataNotLoadedForUnprivilegedUsers()
    {
        $url = $this->getUrl(
            $this->kernelBrowser,
            "app_api_courses_getone",
            [
                'version' => $this->apiVersion,
                'id' => 1,
                'include' => 'sessions.administrators'
            ]
        );
        $this->createJsonApiRequest(
            'GET',
            $url,
            null,
            $this->getTokenForUser($this->kernelBrowser, 5)
        );

        $response = $this->kernelBrowser->getResponse();

        if (Response::HTTP_NOT_FOUND === $response->getStatusCode()) {
            $this->fail("Unable to load url: {$url}");
        }

        $this->assertJsonApiResponse($response, Response::HTTP_OK);
        $content = json_decode($response->getContent());
        $this->assertObjectHasAttribute('included', $content);

        $types = array_column($content->included, 'type');
        $this->assertCount(2, $content->included);
        $this->assertNotContains('users', $types);
    }
}


text:
$(function(){
	//hide S,M,L,X,XXL,XXXL forms
	$(".size-group").hide();

	$(".checkbox").click(function(){
		switch($(this).val()){
			case "S":
				$(".size-group.S").removeClass("show");
				$(".size-group.S").removeClass("yes");
				if($(this).is(':checked')){
					$(".size-group.S").addClass("yes");
					if($("#feature2").val() == "Y")
						$("#S-sizegroup-up").addClass("show");
					else
						$("#S-sizegroup-down").addClass("show");
				}
				break;
			case "M":
				$(".size-group.M").removeClass("show");
				$(".size-group.M").removeClass("yes");
				if($(this).is(':checked')){
					$(".size-group.M").addClass("yes");
					if($("#feature2").val() == "Y")
						$("#M-sizegroup-up").addClass("show");
					else
						$("#M-sizegroup-down").addClass("show");
				}
				break;
			case "L":
				$(".size-group.L").removeClass("show");
				$(".size-group.L").removeClass("yes");
				if($(this).is(':checked')){
					$(".size-group.L").addClass("yes");
					if($("#feature2").val() == "Y")
						$("#L-sizegroup-up").addClass("show");
					else
						$("#L-sizegroup-down").addClass("show");
				}
				break;
			case "XL":
				$(".size-group.XL").removeClass("show");
				$(".size-group.XL").removeClass("yes");
				if($(this).is(':checked')){
					$(".size-group.XL").addClass("yes");
					if($("#feature2").val() == "Y")
						$("#XL-sizegroup-up").addClass("show");
					else
						$("#XL-sizegroup-down").addClass("show");
				}
				break;
			case "XXL":
				$(".size-group.XXL").removeClass("show");
				$(".size-group.XXL").removeClass("yes");
				if($(this).is(':checked')){
					$(".size-group.XXL").addClass("yes");
					if($("#feature2").val() == "Y")
						$("#XXL-sizegroup-up").addClass("show");
					else
						$("#XXL-sizegroup-down").addClass("show");
				}
				break;
			case "XXXL":
				$(".size-group.XXXL").removeClass("show");
				$(".size-group.XXXL").removeClass("yes");
				if($(this).is(':checked')){
					$(".size-group.XXXL").addClass("yes");
					if($("#feature2").val() == "Y")
						$("#XXXL-sizegroup-up").addClass("show");
					else
						$("#XXXL-sizegroup-down").addClass("show");
				}
				break;
			default:
				break;
		}
		$.getScript("admin/js/editProduct/validateSizeDetail.js");
	});

	$("#feature2").change(function(){
		var $dot = $(".size-group");
		for(var i=0, len=$dot.length; i < len; i++){
			if($($dot[i]).hasClass("yes")){
				if($("#feature2").val() == 'Y'){
					if($($dot[i]).hasClass("up")){
						$($dot[i]).addClass("show");
					}
					else
						$($dot[i]).removeClass("show");
				}
				else {
					if($($dot[i]).hasClass("up")){
						$($dot[i]).removeClass("show");
					}
					else
						$($dot[i]).addClass("show");
				}
			}
		}
		$.getScript("admin/js/addProduct/validateSizeDetail.js");
	});

	//hide & show color, size, tags collapse
	$("#colorcollapse").hide();
	$("#tagcollapse").hide();

	$('#addproductform :input').focus(function(){
		// if color is focus
		if($(this).is('#newproductcolor')) {
			$("#colorcollapse").show();
			$("#tagcollapse").hide();

			$.post("admin/php/editProduct/getColor.php", function (dataa, status){
				//alert("Rec: "+dataa);
				$.getScript("admin/json/color.json", function (data){
					data = JSON.parse(data);
					$($("#colorcollapse").children()[0]).empty();
					//var content = '<button type="button" id="shishi" class="btn btn-default btn-xs">黄色</button>';
					var content = '';
					$.each( data, function (index, colorinfo){
						content += '<button type="button" data-whatever="' + colorinfo['color_id'] + '" class="btn btn-default btn-xs">' + colorinfo['color_name'] + '</button>';
					});
					$($("#colorcollapse").children()[0]).append(content);
					// when click the color button
					$.getScript("admin/js/addProduct/colorButtonAdd.js");
				});
			});
		}
		// if tag is foucus
		if($(this).is('#newproducttag')) {
			$("#colorcollapse").hide();
			$("#tagcollapse").show();

			$.post("admin/php/addProduct/getTag.php", function (dataa, status){

				$.getScript("admin/json/tag.json", function (data){
					data = JSON.parse(data);
					$($("#tagcollapse").children()[0]).empty();
					var content = '';
					$.each( data, function (index, taginfo){
						content += '<button type="button" data-whatever="' + taginfo['tag_id'] + '" class="btn btn-default btn-xs">' + taginfo['tag_name'] + '</button>';
					});
					$($("#tagcollapse").children()[0]).append(content);
					// when click the size button
					$.getScript("admin/js/addProduct/tagButtonAdd.js");
				});
			});
		}
	});

	$('#addproductform :input').blur(function(){
		var $parent = $(this).parent();			//divs
		$parent.parent().parent().removeClass("has-success");
		$parent.parent().parent().find(".alert").remove();
		$parent.parent().find(".fa-check").remove();

		//validate new product name
		if($(this).is('#newproductname')) {
			if( this.value == "" ) {
				var errorMsg = "请输入产品名称.";
				$parent.after('
' + errorMsg + '
');
			}
			else {
				$parent.parent().addClass("has-success");
				$parent.append('');
			}
		}
		//validate new product pre price
		if($(this).is('#newproductpreprice') || $(this).is('#newproductcurprice')) {
		//	$parent.parent().parent().removeClass("has-success");
		//	$parent.parent().parent().find(".alert").remove();
		//	$parent.parent().find(".fa-check").remove();

			if( this.value == "" || /^\d+(\.\d+)?$/.test($(this).val()) == false) {
				var errorMsg = "请输入正确的价格格式.";
				$parent.parent().after('
' + errorMsg + '
');
			}
			else {
				$parent.parent().parent().addClass("has-success");
				$parent.parent().append('');
			}
		}
		// color
		// tag
		if($(this).is('#newproductinfo')) {
			if( this.value == "" ) {
				var errorMsg = "请输入关于本产品简单描述.";
				$parent.after('
' + errorMsg + '
');
			}
			else {
				$parent.parent().addClass("has-success");
				$parent.append('');
			}
		}
	});

	// for upload mutil picture
	$("#newproductimg").change(function(){
		var data = new FormData();
		$.each($('#newproductimg')[0].files, function(i, file){
			data.append('upload'+i, file);//serialize
		});
		$.ajax({
			url:'admin/php/editProduct/upload_image.php',
			type:'POST',
			data:data,
			cache:false,
			contentType:false,
			processData:false,
			success:function(data) {
				data = $(data).html();
				//data = '
' + data + '
';
				//var output1 = "
<input type='radio' name='imgselect' value='{$filename}'>'" + data + "
";
				//var output2 = ""

				if($("#inputimg img").length == 0)
					$("#inputimg .new").append(data.replace(/</g,'<').replace(/>/g,'>'));
				else
					$("#inputimg .new").prepend(data.replace(/</g,'<').replace(/>/g,'>'));

				data = data.replace(/coverimg/g, "deleteimg");
				if($("#outputimg img").length == 0)

					$("#outputimg .new").append(data.replace(/</g,'<').replace(/>/g,'>'));
				else
					$("#outputimg .new").prepend(data.replace(/</g,'<').replace(/>/g,'>'));

				//$.getScript("admin/js/editProduct/setcover.js");
			},
			error:function(){
				alert('上传出错.');
			}
		});
	});

	//validate before submit
	$('#allsubmit').click(function(){
		$("#allsubmit :input").trigger('blur');
		var $test = $("#addproductform").serialize();
		var $test1 = $("#newproductname").val();
		var numError = $('form .alert').length;
		if(numError){
			alert("有必填项目未填写");
			return false;
		}

		// if no img uploaded
		if($('#inputimg img').length == 0) {
			alert("请选择图片上传");
			return false;
		}
		// get array for img name
		var $imgname = new Array();
		$('#inputimg .new img').each(function(){
			$imgname.push($(this).attr("title"));
		});
		//alert("imgname: "+$imgname[0]+$imgname[1]);

		//for detail
		var $sizedetail = [];
		for(var i = 0; i < $(".checkbox:checked").length; i++){
			var $temp = $($(".checkbox:checked")[i]).val();
			$temp =".size-group.show." + $temp + " :input";
			if($("#feature2").val() == 'Y'){//cloth
				$sizedetail.push({ shoulder:$($($temp)[0]).val(), breast:$($($temp)[1]).val(), sleeve:$($($temp)[2]).val(), cloth_len:$($($temp)[3]).val(), waist:$($($temp)[4]).val(), collar:$($($temp)[5]).val(), size_name:$($(".checkbox:checked")[i]).val(), sex:$("#feature1").val(), type:$("#feature2").val() });
			}
			else {
				$sizedetail.push({ waist:$($($temp)[0]).val(), buttocks:$($($temp)[1]).val(), leg:$($($temp)[2]).val(), shank:$($($temp)[3]).val(), trous_len:$($($temp)[4]).val(), size_name:$($(".checkbox:checked")[i]).val(), sex:$("#feature1").val(), type:$("#feature2").val()});
			}
		}
		$.post("admin/php/editProduct/add_product.php", {
				product_id:$("#productid").val(),
				newproductname:$('#newproductname').val(),
				newproductpreprice:$('#newproductpreprice').val(),
				newproductcurprice:$('#newproductcurprice').val(),
				newproductimg:$imgname,

				type:$("#feature2").val(),
				newproductsizedetail:$sizedetail,
				style:$($("#productparameter :input")[0]).val(),
				material:$($("#productparameter :input")[1]).val(),
				component:$($("#productparameter :input")[2]).val(),
				sleeve_style:$($("#productparameter :input")[3]).val(),
				type_version:$($("#productparameter :input")[4]).val(),
				collar:$($("#productparameter :input")[5]).val(),

				newproductcolor:$('#newproductcolor').val(),
				//newproductsize:$('#newproductsize').val(),
				newproducttag:$('#newproducttag').val(),
				newproductinfo:$('#newproductinfo').val()
			},
			function (data, status){
				if(data == 'Success'){
					$("#addproductform").hide();
					$("#addproducttitle small").text("编辑成功");
					$("#addproducttitle").after('

');
					var t1 = setTimeout("$('#timedown').text('3秒后自动跳转到首页.')",0);
					var t2 = setTimeout("$('#timedown').text('2秒后自动跳转到首页.')",1000);
					var t3 = setTimeout("$('#timedown').text('1秒后自动跳转到首页.')",2000);
					var t4 = setTimeout("window.location.assign('index.html')",3000);
				}
				else {
					$("#addproductform").hide();
					$("#addproducttitle small").text("编辑失败");
					$("#addproducttitle").after('

');
					var t1 = setTimeout("$('#timedown').text('3秒后自动跳转到首页.')",0000);
					var t2 = setTimeout("$('#timedown').text('2秒后自动跳转到首页.')",1000);
					var t3 = setTimeout("$('#timedown').text('1秒后自动跳转到首页.')",2000);
					var t4 = setTimeout("window.location.assign('index.html')",3000);
				}
			}
		);
	});
});


text:
package com.redislabs.provider.redis.df.cluster

import java.nio.charset.StandardCharsets.UTF_8

import com.redislabs.provider.redis.df.BinaryDataframeSuite
import com.redislabs.provider.redis.env.RedisClusterEnv
import org.apache.spark.sql.redis.RedisSourceRelation.dataKey
import redis.clients.jedis.{HostAndPort, JedisCluster}

/**
  * @author The Viet Nguyen
  */
class BinaryDataframeClusterSuite extends BinaryDataframeSuite with RedisClusterEnv {

  override def saveMap(tableName: String, key: String, value: Map[String, String]): Unit = {
    val host = redisConfig.initialHost
    val hostAndPort = new HostAndPort(host.host, host.port)
    val conn = new JedisCluster(hostAndPort)
    conn.set(dataKey(tableName, key).getBytes(UTF_8), serialize(value))
    conn.close()
  }
}


text:
import json

from django.core.exceptions import ObjectDoesNotExist
from django.db.models import get_model
from django.http import (HttpResponse, HttpResponseNotFound,
                         HttpResponseBadRequest, HttpResponseForbidden)
from django.utils.translation import ugettext as _
from django.views.decorators.clickjacking import xframe_options_sameorigin
from django.views.decorators.http import require_POST

from kitsune.access.decorators import login_required
from kitsune.upload.models import ImageAttachment
from kitsune.upload.utils import upload_imageattachment, FileTooLargeError

ALLOWED_MODELS = ['questions.Question', 'questions.Answer', 'auth.User']

@login_required
@require_POST
@xframe_options_sameorigin
def up_image_async(request, model_name, object_pk):
    """Upload all images in request.FILES."""

    # Verify the model agaist our white-list
    if model_name not in ALLOWED_MODELS:
        message = _('Model not allowed.')
        return HttpResponseBadRequest(
            json.dumps({'status': 'error', 'message': message}))

    # Get the model
    m = get_model(*model_name.split('.'))

    # Then look up the object by pk
    try:
        obj = m.objects.get(pk=object_pk)
    except ObjectDoesNotExist:
        message = _('Object does not exist.')
        return HttpResponseNotFound(
            json.dumps({'status': 'error', 'message': message}))

    try:
        file_info = upload_imageattachment(request, obj)
    except FileTooLargeError as e:
        return HttpResponseBadRequest(
            json.dumps({'status': 'error', 'message': e.args[0]}))

    if isinstance(file_info, dict) and 'thumbnail_url' in file_info:
        return HttpResponse(
            json.dumps({'status': 'success', 'file': file_info}))

    message = _('Invalid or no image received.')
    return HttpResponseBadRequest(
        json.dumps({'status': 'error', 'message': message,
                    'errors': file_info}))

@require_POST
@xframe_options_sameorigin
def del_image_async(request, image_id):
    """Delete an image given its object id."""
    user = request.user
    if not user.is_authenticated():
        message = _('You are not logged in.')
        return HttpResponseForbidden(
            json.dumps({'status': 'error', 'message': message}))

    try:
        image = ImageAttachment.objects.get(pk=image_id)
    except ImageAttachment.DoesNotExist:
        message = _('The requested image could not be found.')
        return HttpResponseNotFound(
            json.dumps({'status': 'error', 'message': message}))

    if not ((user == image.creator) or
            (user.has_perm('upload.delete_imageattachment'))):
        message = _('You do not have permission to do that.')
        return HttpResponseForbidden(
            json.dumps({'status': 'error', 'message': message}))

    image.file.delete()
    if image.thumbnail:
        image.thumbnail.delete()
    image.delete()

    return HttpResponse(json.dumps({'status': 'success'}))


text:
#pragma once
#include <aws/fsx/FSx_EXPORTS.h>
#include <aws/fsx/FSxRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/fsx/model/CreateOntapVolumeConfiguration.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/fsx/model/Tag.h>
#include <utility>
#include <aws/core/utils/UUID.h>

namespace Aws
{
namespace FSx
{
namespace Model
{

  /**
   */
  class AWS_FSX_API CreateVolumeFromBackupRequest : public FSxRequest
  {
  public:
    CreateVolumeFromBackupRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "CreateVolumeFromBackup"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    inline const Aws::String& GetBackupId() const{ return m_backupId; }

    inline bool BackupIdHasBeenSet() const { return m_backupIdHasBeenSet; }

    inline void SetBackupId(const Aws::String& value) { m_backupIdHasBeenSet = true; m_backupId = value; }

    inline void SetBackupId(Aws::String&& value) { m_backupIdHasBeenSet = true; m_backupId = std::move(value); }

    inline void SetBackupId(const char* value) { m_backupIdHasBeenSet = true; m_backupId.assign(value); }

    inline CreateVolumeFromBackupRequest& WithBackupId(const Aws::String& value) { SetBackupId(value); return *this;}

    inline CreateVolumeFromBackupRequest& WithBackupId(Aws::String&& value) { SetBackupId(std::move(value)); return *this;}

    inline CreateVolumeFromBackupRequest& WithBackupId(const char* value) { SetBackupId(value); return *this;}

    inline const Aws::String& GetClientRequestToken() const{ return m_clientRequestToken; }

    inline bool ClientRequestTokenHasBeenSet() const { return m_clientRequestTokenHasBeenSet; }

    inline void SetClientRequestToken(const Aws::String& value) { m_clientRequestTokenHasBeenSet = true; m_clientRequestToken = value; }

    inline void SetClientRequestToken(Aws::String&& value) { m_clientRequestTokenHasBeenSet = true; m_clientRequestToken = std::move(value); }

    inline void SetClientRequestToken(const char* value) { m_clientRequestTokenHasBeenSet = true; m_clientRequestToken.assign(value); }

    inline CreateVolumeFromBackupRequest& WithClientRequestToken(const Aws::String& value) { SetClientRequestToken(value); return *this;}

    inline CreateVolumeFromBackupRequest& WithClientRequestToken(Aws::String&& value) { SetClientRequestToken(std::move(value)); return *this;}

    inline CreateVolumeFromBackupRequest& WithClientRequestToken(const char* value) { SetClientRequestToken(value); return *this;}

    /**
     *
The name of the new volume you're creating.

     */
    inline const Aws::String& GetName() const{ return m_name; }

    /**
     *
The name of the new volume you're creating.

     */
    inline bool NameHasBeenSet() const { return m_nameHasBeenSet; }

    /**
     *
The name of the new volume you're creating.

     */
    inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }

    /**
     *
The name of the new volume you're creating.

     */
    inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }

    /**
     *
The name of the new volume you're creating.

     */
    inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }

    /**
     *
The name of the new volume you're creating.

     */
    inline CreateVolumeFromBackupRequest& WithName(const Aws::String& value) { SetName(value); return *this;}

    /**
     *
The name of the new volume you're creating.

     */
    inline CreateVolumeFromBackupRequest& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}

    /**
     *
The name of the new volume you're creating.

     */
    inline CreateVolumeFromBackupRequest& WithName(const char* value) { SetName(value); return *this;}

    /**
     *
Specifies the configuration of the ONTAP volume that you are creating.

     */
    inline const CreateOntapVolumeConfiguration& GetOntapConfiguration() const{ return m_ontapConfiguration; }

    /**
     *
Specifies the configuration of the ONTAP volume that you are creating.

     */
    inline bool OntapConfigurationHasBeenSet() const { return m_ontapConfigurationHasBeenSet; }

    /**
     *
Specifies the configuration of the ONTAP volume that you are creating.

     */
    inline void SetOntapConfiguration(const CreateOntapVolumeConfiguration& value) { m_ontapConfigurationHasBeenSet = true; m_ontapConfiguration = value; }

    /**
     *
Specifies the configuration of the ONTAP volume that you are creating.

     */
    inline void SetOntapConfiguration(CreateOntapVolumeConfiguration&& value) { m_ontapConfigurationHasBeenSet = true; m_ontapConfiguration = std::move(value); }

    /**
     *
Specifies the configuration of the ONTAP volume that you are creating.

     */
    inline CreateVolumeFromBackupRequest& WithOntapConfiguration(const CreateOntapVolumeConfiguration& value) { SetOntapConfiguration(value); return *this;}

    /**
     *
Specifies the configuration of the ONTAP volume that you are creating.

     */
    inline CreateVolumeFromBackupRequest& WithOntapConfiguration(CreateOntapVolumeConfiguration&& value) { SetOntapConfiguration(std::move(value)); return *this;}

    inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; }

    inline bool TagsHasBeenSet() const { return m_tagsHasBeenSet; }

    inline void SetTags(const Aws::Vector<Tag>& value) { m_tagsHasBeenSet = true; m_tags = value; }

    inline void SetTags(Aws::Vector<Tag>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); }

    inline CreateVolumeFromBackupRequest& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;}

    inline CreateVolumeFromBackupRequest& WithTags(Aws::Vector<Tag>&& value) { SetTags(std::move(value)); return *this;}

    inline CreateVolumeFromBackupRequest& AddTags(const Tag& value) { m_tagsHasBeenSet = true; m_tags.push_back(value); return *this; }

    inline CreateVolumeFromBackupRequest& AddTags(Tag&& value) { m_tagsHasBeenSet = true; m_tags.push_back(std::move(value)); return *this; }

  private:

    Aws::String m_backupId;
    bool m_backupIdHasBeenSet = false;

    Aws::String m_clientRequestToken;
    bool m_clientRequestTokenHasBeenSet = false;

    Aws::String m_name;
    bool m_nameHasBeenSet = false;

    CreateOntapVolumeConfiguration m_ontapConfiguration;
    bool m_ontapConfigurationHasBeenSet = false;

    Aws::Vector<Tag> m_tags;
    bool m_tagsHasBeenSet = false;
  };

} // namespace Model
} // namespace FSx
} // namespace Aws


text:
package org.lwjgl.fmod;

import javax.annotation.*;

import java.nio.*;

import org.lwjgl.*;
import org.lwjgl.system.*;

import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;

/**
 *
Layout

 *
 *

 * struct FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES {
 *     char const * name;
 *     FMOD_DSP * dsp;
 * }

 */
public class FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES extends Struct implements NativeResource {

    /** The struct size in bytes. */
    public static final int SIZEOF;

    /** The struct alignment in bytes. */
    public static final int ALIGNOF;

    /** The struct member offsets. */
    public static final int
        NAME,
        DSP;

    static {
        Layout layout = __struct(
            __member(POINTER_SIZE),
            __member(POINTER_SIZE)
        );

        SIZEOF = layout.getSize();
        ALIGNOF = layout.getAlignment();

        NAME = layout.offsetof(0);
        DSP = layout.offsetof(1);
    }

    /**
     * Creates a {@code FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
     * visible to the struct instance and vice versa.
     *
     *
The created instance holds a strong reference to the container object.

     */
    public FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES(ByteBuffer container) {
        super(memAddress(container), __checkContainer(container, SIZEOF));
    }

    @Override
    public int sizeof() { return SIZEOF; }

    /** @return a {@link ByteBuffer} view of the null-terminated string pointed to by the {@code name} field. */
    @NativeType("char const *")
    public ByteBuffer name() { return nname(address()); }
    /** @return the null-terminated string pointed to by the {@code name} field. */
    @NativeType("char const *")
    public String nameString() { return nnameString(address()); }
    /** @return the value of the {@code dsp} field. */
    @NativeType("FMOD_DSP *")
    public long dsp() { return ndsp(address()); }

    /** Sets the address of the specified encoded string to the {@code name} field. */
    public FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES name(@NativeType("char const *") ByteBuffer value) { nname(address(), value); return this; }
    /** Sets the specified value to the {@code dsp} field. */
    public FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES dsp(@NativeType("FMOD_DSP *") long value) { ndsp(address(), value); return this; }

    /** Initializes this struct with the specified values. */
    public FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES set(
        ByteBuffer name,
        long dsp
    ) {
        name(name);
        dsp(dsp);

        return this;
    }

    /**
     * Copies the specified struct data to this struct.
     *
     * @param src the source struct
     *
     * @return this struct
     */
    public FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES set(FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES src) {
        memCopy(src.address(), address(), SIZEOF);
        return this;
    }

    // -----------------------------------

    /** Returns a new {@code FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
    public static FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES malloc() {
        return wrap(FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.class, nmemAllocChecked(SIZEOF));
    }

    /** Returns a new {@code FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
    public static FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES calloc() {
        return wrap(FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.class, nmemCallocChecked(1, SIZEOF));
    }

    /** Returns a new {@code FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES} instance allocated with {@link BufferUtils}. */
    public static FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES create() {
        ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF);
        return wrap(FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.class, memAddress(container), container);
    }

    /** Returns a new {@code FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES} instance for the specified memory address. */
    public static FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES create(long address) {
        return wrap(FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.class, address);
    }

    /** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */
    @Nullable
    public static FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES createSafe(long address) {
        return address == NULL ? null : wrap(FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.class, address);
    }

    /**
     * Returns a new {@link FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
     *
     * @param capacity the buffer capacity
     */
    public static FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.Buffer malloc(int capacity) {
        return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity);
    }

    /**
     * Returns a new {@link FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
     *
     * @param capacity the buffer capacity
     */
    public static FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.Buffer calloc(int capacity) {
        return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity);
    }

    /**
     * Returns a new {@link FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.Buffer} instance allocated with {@link BufferUtils}.
     *
     * @param capacity the buffer capacity
     */
    public static FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.Buffer create(int capacity) {
        ByteBuffer container = __create(capacity, SIZEOF);
        return wrap(Buffer.class, memAddress(container), capacity, container);
    }

    /**
     * Create a {@link FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.Buffer} instance at the specified memory.
     *
     * @param address  the memory address
     * @param capacity the buffer capacity
     */
    public static FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.Buffer create(long address, int capacity) {
        return wrap(Buffer.class, address, capacity);
    }

    /** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */
    @Nullable
    public static FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.Buffer createSafe(long address, int capacity) {
        return address == NULL ? null : wrap(Buffer.class, address, capacity);
    }

    /**
     * Returns a new {@code FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES} instance allocated on the specified {@link MemoryStack}.
     *
     * @param stack the stack from which to allocate
     */
    public static FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES malloc(MemoryStack stack) {
        return wrap(FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.class, stack.nmalloc(ALIGNOF, SIZEOF));
    }

    /**
     * Returns a new {@code FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
     *
     * @param stack the stack from which to allocate
     */
    public static FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES calloc(MemoryStack stack) {
        return wrap(FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.class, stack.ncalloc(ALIGNOF, 1, SIZEOF));
    }

    /**
     * Returns a new {@link FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.Buffer} instance allocated on the specified {@link MemoryStack}.
     *
     * @param stack    the stack from which to allocate
     * @param capacity the buffer capacity
     */
    public static FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.Buffer malloc(int capacity, MemoryStack stack) {
        return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
    }

    /**
     * Returns a new {@link FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
     *
     * @param stack    the stack from which to allocate
     * @param capacity the buffer capacity
     */
    public static FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.Buffer calloc(int capacity, MemoryStack stack) {
        return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
    }

    // -----------------------------------

    /** Unsafe version of {@link #name}. */
    public static ByteBuffer nname(long struct) { return memByteBufferNT1(memGetAddress(struct + FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.NAME)); }
    /** Unsafe version of {@link #nameString}. */
    public static String nnameString(long struct) { return memUTF8(memGetAddress(struct + FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.NAME)); }
    /** Unsafe version of {@link #dsp}. */
    public static long ndsp(long struct) { return memGetAddress(struct + FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.DSP); }

    /** Unsafe version of {@link #name(ByteBuffer) name}. */
    public static void nname(long struct, ByteBuffer value) {
        if (CHECKS) { checkNT1(value); }
        memPutAddress(struct + FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.NAME, memAddress(value));
    }
    /** Unsafe version of {@link #dsp(long) dsp}. */
    public static void ndsp(long struct, long value) { memPutAddress(struct + FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.DSP, check(value)); }

    /**
     * Validates pointer members that should not be {@code NULL}.
     *
     * @param struct the struct to validate
     */
    public static void validate(long struct) {
        check(memGetAddress(struct + FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.NAME));
        check(memGetAddress(struct + FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.DSP));
    }

    // -----------------------------------

    /** An array of {@link FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES} structs. */
    public static class Buffer extends StructBuffer<FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES, Buffer> implements NativeResource {

        private static final FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES ELEMENT_FACTORY = FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.create(-1L);

        /**
         * Creates a new {@code FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.Buffer} instance backed by the specified container.
         *
         * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
         * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
         * by {@link FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES#SIZEOF}, and its mark will be undefined.
         *
         *
The created buffer instance holds a strong reference to the container object.

         */
        public Buffer(ByteBuffer container) {
            super(container, container.remaining() / SIZEOF);
        }

        public Buffer(long address, int cap) {
            super(address, null, -1, 0, cap, cap);
        }

        Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) {
            super(address, container, mark, pos, lim, cap);
        }

        @Override
        protected Buffer self() {
            return this;
        }

        @Override
        protected FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES getElementFactory() {
            return ELEMENT_FACTORY;
        }

        /** @return a {@link ByteBuffer} view of the null-terminated string pointed to by the {@code name} field. */
        @NativeType("char const *")
        public ByteBuffer name() { return FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.nname(address()); }
        /** @return the null-terminated string pointed to by the {@code name} field. */
        @NativeType("char const *")
        public String nameString() { return FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.nnameString(address()); }
        /** @return the value of the {@code dsp} field. */
        @NativeType("FMOD_DSP *")
        public long dsp() { return FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.ndsp(address()); }

        /** Sets the address of the specified encoded string to the {@code name} field. */
        public FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.Buffer name(@NativeType("char const *") ByteBuffer value) { FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.nname(address(), value); return this; }
        /** Sets the specified value to the {@code dsp} field. */
        public FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.Buffer dsp(@NativeType("FMOD_DSP *") long value) { FMOD_STUDIO_PLUGIN_INSTANCE_PROPERTIES.ndsp(address(), value); return this; }

    }

}


text:
#ifndef ECDAA_ISSUER_KEYPAIR_ZZZ_H
#define ECDAA_ISSUER_KEYPAIR_ZZZ_H
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#include <ecdaa/group_public_key_ZZZ.h>
#include <ecdaa/rand.h>

#include <amcl/big_XXX.h>

/*
 * Issuer's public key.
 */
struct ecdaa_issuer_public_key_ZZZ {
    struct ecdaa_group_public_key_ZZZ gpk;
    BIG_XXX c;
    BIG_XXX sx;
    BIG_XXX sy;
};

#define ECDAA_ISSUER_PUBLIC_KEY_ZZZ_LENGTH (ECDAA_GROUP_PUBLIC_KEY_ZZZ_LENGTH + MODBYTES_XXX + MODBYTES_XXX + MODBYTES_XXX)
size_t ecdaa_issuer_public_key_ZZZ_length(void);

/*
 * Issuer's secret key.
 */
struct ecdaa_issuer_secret_key_ZZZ {
    BIG_XXX x;
    BIG_XXX y;
};

#define ECDAA_ISSUER_SECRET_KEY_ZZZ_LENGTH (2*MODBYTES_XXX)
size_t ecdaa_issuer_secret_key_ZZZ_length(void);

/*
 * Generate a fresh `ecdaa_issuer_public_key_ZZZ`, `ecdaa_issuer_secret_key_ZZZ` keypair.
 *
 * Returns:
 * 0 on success
 * -1 on error
 */
int ecdaa_issuer_key_pair_ZZZ_generate(struct ecdaa_issuer_public_key_ZZZ *pk_out,
                                       struct ecdaa_issuer_secret_key_ZZZ *sk_out,
                                       ecdaa_rand_func get_random);

/*
 * Check the signature on an `ecdaa_issuer_public_key_ZZZ`.
 *
 * Returns:
 * 0 on success
 * -1 if the signature is invalid
 */
int ecdaa_issuer_public_key_ZZZ_validate(struct ecdaa_issuer_public_key_ZZZ *ipk);

/*
 * Serialize an `ecdaa_issuer_public_key_ZZZ`
 *
 * The serialized format is:
 *  ( gpk | c | sx | sy )
 *  where c, sx, and sy are zero-padded and in big-endian byte-order.
 *  Cf. `group_public_key_ZZZ.h` for the serialization of `gpk`.
 *
 * The provided buffer is assumed to be large enough.
 */
void ecdaa_issuer_public_key_ZZZ_serialize(uint8_t *buffer_out,
                                            struct ecdaa_issuer_public_key_ZZZ *ipk);

int ecdaa_issuer_public_key_ZZZ_serialize_fp(FILE *p,
                                            struct ecdaa_issuer_public_key_ZZZ *ipk);

int ecdaa_issuer_public_key_ZZZ_serialize_file(const char* file,
                                           struct ecdaa_issuer_public_key_ZZZ *ipk);

/*
 * De-serialize an `ecdaa_issuer_public_key_ZZZ` and check its validity and signature.
 *
 * The expected serialized format is:
 *  ( gpk | c | sx | sy )
 *  where c, sx, and sy are zero-padded and in big-endian byte-order.
 *  Cf. `group_public_key_ZZZ.h` for the serialization of `gpk`.
 *
 *  Returns:
 *  0 on success
 *  -1 if gpk is invalid
 *  -1 if format of c, sx, or sy is invalid
 *  -2 if (c, sx, sy) don't verify
 */
int ecdaa_issuer_public_key_ZZZ_deserialize(struct ecdaa_issuer_public_key_ZZZ *ipk_out,
                                             uint8_t *buffer_in);

int ecdaa_issuer_public_key_ZZZ_deserialize_file(struct ecdaa_issuer_public_key_ZZZ *ipk_out,
                                            const char* file);

int ecdaa_issuer_public_key_ZZZ_deserialize_fp(struct ecdaa_issuer_public_key_ZZZ *ipk_out,
                                            FILE* fp);

/*
 * Serialize an `ecdaa_issuer_secret_key_ZZZ`
 *
 * The serialized format is:
 *  ( x | y )
 *  as zero-padded numbers in big-endian byte-order.
 *
 * The provided buffer is assumed to be large enough.
 */
void ecdaa_issuer_secret_key_ZZZ_serialize(uint8_t *buffer_out,
                                           struct ecdaa_issuer_secret_key_ZZZ *isk);

int ecdaa_issuer_secret_key_ZZZ_serialize_file(const char* file, struct ecdaa_issuer_secret_key_ZZZ *isk);

int ecdaa_issuer_secret_key_ZZZ_serialize_fp(FILE* fp, struct ecdaa_issuer_secret_key_ZZZ *isk);

/*
 * De-serialize an `ecdaa_issuer_secret_key_ZZZ`
 *
 * The expected serialized format is:
 *  ( x | y )
 *  as zero-padded numbers in big-endian byte-order.
 *
 *  Returns:
 *  0 on success
 */
int ecdaa_issuer_secret_key_ZZZ_deserialize(struct ecdaa_issuer_secret_key_ZZZ *isk_out,
                                             uint8_t *buffer_in);

int ecdaa_issuer_secret_key_ZZZ_deserialize_file(struct ecdaa_issuer_secret_key_ZZZ *isk_out,
                                            const char* file);

int ecdaa_issuer_secret_key_ZZZ_deserialize_fp(struct ecdaa_issuer_secret_key_ZZZ *isk_out,
                                            FILE* fp);

#ifdef __cplusplus
}
#endif

#endif


text:
Permian Homes - Odessa and Midland Texas

432-362-3436

Home

Advantages

Financing

Communities

Quick Move In

Customer Care

Contact us


text:
/*
 * @(#)NullHandle.java 5.2
 *
 */

package CH.ifa.draw.standard;

import java.awt.*;
import CH.ifa.draw.framework.*;

/**
 * A handle that doesn't change the owned figure. Its only purpose is
 * to show feedback that a figure is selected.
 *

 * Design Patterns

 *
 * NullObject

 * NullObject enables to treat handles that don't do
 * anything in the same way as other handles.
 *
 */
public class NullHandle extends LocatorHandle {

    /**
     * The handle's locator.
     */
    protected Locator fLocator;

    public NullHandle(Figure owner, Locator locator) {
        super(owner, locator);
    }

    /**
     * Draws the NullHandle. NullHandles are drawn as a
     * red framed rectangle.
     */
    public void draw(Graphics g) {
        Rectangle r = displayBox();

        g.setColor(Color.black);
        g.drawRect(r.x, r.y, r.width, r.height);
    }
}