text:
package io.quarkus.arc.processor;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Collection;
import java.util.Collections;

import javax.enterprise.util.AnnotationLiteral;

import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.DotName;
import org.jboss.jandex.Index;
import org.jboss.jandex.IndexView;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.Opcodes;

import io.quarkus.arc.AbstractAnnotationLiteral;
import io.quarkus.gizmo.ClassCreator;
import io.quarkus.gizmo.MethodCreator;
import io.quarkus.gizmo.ResultHandle;
import io.quarkus.gizmo.TestClassLoader;

public class AnnotationLiteralProcessorTest {
    public enum SimpleEnum {
        FOO,
        BAR,
        BAZ,
    }

    @Retention(RetentionPolicy.CLASS)
    public @interface ClassRetainedAnnotation {
    }

    @Retention(RetentionPolicy.RUNTIME)
    public @interface SimpleAnnotation {
        String value();

        class Literal extends AnnotationLiteral<SimpleAnnotation> implements SimpleAnnotation {
            private final String value;

            public Literal(String value) {
                this.value = value;
            }

            @Override
            public String value() {
                return value;
            }
        }
    }

    @Retention(RetentionPolicy.RUNTIME)
    public @interface ComplexAnnotation {
        boolean bool();

        byte b();

        short s();

        int i();

        long l();

        float f();

        double d();

        char ch();

        String str();

        SimpleEnum en();

        Class<?> cls();

        SimpleAnnotation nested();

        boolean[] boolArray();

        byte[] bArray();

        short[] sArray();

        int[] iArray();

        long[] lArray();

        float[] fArray();

        double[] dArray();

        char[] chArray();

        String[] strArray();

        SimpleEnum[] enArray();

        Class<?>[] clsArray();

        SimpleAnnotation[] nestedArray();

        class Literal extends AnnotationLiteral<ComplexAnnotation> implements ComplexAnnotation {
            private final boolean bool;
            private final byte b;
            private final short s;
            private final int i;
            private final long l;
            private final float f;
            private final double d;
            private final char ch;
            private final String str;
            private final SimpleEnum en;
            private final Class<?> cls;
            private final SimpleAnnotation nested;

            private final boolean[] boolArray;
            private final byte[] bArray;
            private final short[] sArray;
            private final int[] iArray;
            private final long[] lArray;
            private final float[] fArray;
            private final double[] dArray;
            private final char[] chArray;
            private final String[] strArray;
            private final SimpleEnum[] enArray;
            private final Class<?>[] clsArray;
            private final SimpleAnnotation[] nestedArray;

            public Literal(boolean bool, byte b, short s, int i, long l, float f, double d, char ch, String str, SimpleEnum en,
                    Class<?> cls, SimpleAnnotation nested, boolean[] boolArray, byte[] bArray, short[] sArray, int[] iArray,
                    long[] lArray, float[] fArray, double[] dArray, char[] chArray, String[] strArray, SimpleEnum[] enArray,
                    Class<?>[] clsArray, SimpleAnnotation[] nestedArray) {
                this.bool = bool;
                this.b = b;
                this.s = s;
                this.i = i;
                this.l = l;
                this.f = f;
                this.d = d;
                this.ch = ch;
                this.str = str;
                this.en = en;
                this.cls = cls;
                this.nested = nested;
                this.boolArray = boolArray;
                this.bArray = bArray;
                this.sArray = sArray;
                this.iArray = iArray;
                this.lArray = lArray;
                this.fArray = fArray;
                this.dArray = dArray;
                this.chArray = chArray;
                this.strArray = strArray;
                this.enArray = enArray;
                this.clsArray = clsArray;
                this.nestedArray = nestedArray;
            }

            @Override
            public boolean bool() {
                return bool;
            }

            @Override
            public byte b() {
                return b;
            }

            @Override
            public short s() {
                return s;
            }

            @Override
            public int i() {
                return i;
            }

            @Override
            public long l() {
                return l;
            }

            @Override
            public float f() {
                return f;
            }

            @Override
            public double d() {
                return d;
            }

            @Override
            public char ch() {
                return ch;
            }

            @Override
            public String str() {
                return str;
            }

            @Override
            public SimpleEnum en() {
                return en;
            }

            @Override
            public Class<?> cls() {
                return cls;
            }

            @Override
            public SimpleAnnotation nested() {
                return nested;
            }

            @Override
            public boolean[] boolArray() {
                return boolArray;
            }

            @Override
            public byte[] bArray() {
                return bArray;
            }

            @Override
            public short[] sArray() {
                return sArray;
            }

            @Override
            public int[] iArray() {
                return iArray;
            }

            @Override
            public long[] lArray() {
                return lArray;
            }

            @Override
            public float[] fArray() {
                return fArray;
            }

            @Override
            public double[] dArray() {
                return dArray;
            }

            @Override
            public char[] chArray() {
                return chArray;
            }

            @Override
            public String[] strArray() {
                return strArray;
            }

            @Override
            public SimpleEnum[] enArray() {
                return enArray;
            }

            @Override
            public Class<?>[] clsArray() {
                return clsArray;
            }

            @Override
            public SimpleAnnotation[] nestedArray() {
                return nestedArray;
            }
        }
    }

    private final String generatedClass = "io.quarkus.arc.processor.test.GeneratedClass";
    private final IndexView index;

    public AnnotationLiteralProcessorTest() throws IOException {
        index = Index.of(SimpleEnum.class, SimpleAnnotation.class, ComplexAnnotation.class);
    }

    @Test
    public void test() throws ReflectiveOperationException {
        AnnotationLiteralProcessor literals = new AnnotationLiteralProcessor(index, ignored -> true);

        TestClassLoader cl = new TestClassLoader(getClass().getClassLoader());
        try (ClassCreator creator = ClassCreator.builder().classOutput(cl).className(generatedClass).build()) {
            MethodCreator method = creator.getMethodCreator("get", ComplexAnnotation.class)
                    .setModifiers(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC);
            ResultHandle annotation = literals.create(method,
                    index.getClassByName(DotName.createSimple(ComplexAnnotation.class.getName())), complexAnnotationJandex());
            method.returnValue(annotation);
        }

        Collection<ResourceOutput.Resource> resources = new AnnotationLiteralGenerator(false)
                .generate(literals.getCache(), Collections.emptySet());
        for (ResourceOutput.Resource resource : resources) {
            if (resource.getType() == ResourceOutput.Resource.Type.JAVA_CLASS) {
                cl.write(resource.getName(), resource.getData());
            } else {
                throw new IllegalStateException("Unexpected " + resource.getType() + " " + resource.getName());
            }
        }

        Class<?> clazz = cl.loadClass(generatedClass);
        ComplexAnnotation annotation = (ComplexAnnotation) clazz.getMethod("get").invoke(null);
        verify(annotation);

        assertTrue(annotation instanceof AbstractAnnotationLiteral);
        AbstractAnnotationLiteral annotationLiteral = (AbstractAnnotationLiteral) annotation;
        assertEquals(annotation.annotationType(), annotationLiteral.annotationType());

        // verify both ways, to ensure our generated classes interop correctly with `AnnotationLiteral`
        assertEquals(complexAnnotationRuntime(), annotation);
        assertEquals(annotation, complexAnnotationRuntime());

        assertEquals(complexAnnotationRuntime().hashCode(), annotation.hashCode());

        assertEquals(
                "@io.quarkus.arc.processor.AnnotationLiteralProcessorTest$ComplexAnnotation(bool=true, b=1, s=2, i=3, l=4, f=5.0, d=6.0, ch=a, str=bc, en=FOO, cls=class java.lang.Object, nested=@io.quarkus.arc.processor.AnnotationLiteralProcessorTest$SimpleAnnotation(value=one), boolArray=[true, false], bArray=[7, 8], sArray=[9, 10], iArray=[11, 12], lArray=[13, 14], fArray=[15.0, 16.0], dArray=[17.0, 18.0], chArray=[d, e], strArray=[fg, hi], enArray=[BAR, BAZ], clsArray=[class java.lang.String, class java.lang.Number], nestedArray=[@io.quarkus.arc.processor.AnnotationLiteralProcessorTest$SimpleAnnotation(value=two), @io.quarkus.arc.processor.AnnotationLiteralProcessorTest$SimpleAnnotation(value=three)])",
                annotation.toString());
    }

    @Test
    public void missingAnnotationClass() {
        AnnotationLiteralProcessor literals = new AnnotationLiteralProcessor(index, ignored -> true);

        TestClassLoader cl = new TestClassLoader(getClass().getClassLoader());
        try (ClassCreator creator = ClassCreator.builder().classOutput(cl).className(generatedClass).build()) {
            MethodCreator method = creator.getMethodCreator("hello", void.class);

            assertThrows(NullPointerException.class, () -> {
                literals.create(method, null, simpleAnnotationJandex("foobar"));
            });
        }
    }

    @Test
    public void classRetainedAnnotation() {
        AnnotationLiteralProcessor literals = new AnnotationLiteralProcessor(index, ignored -> true);

        TestClassLoader cl = new TestClassLoader(getClass().getClassLoader());
        try (ClassCreator creator = ClassCreator.builder().classOutput(cl).className(generatedClass).build()) {
            MethodCreator method = creator.getMethodCreator("hello", void.class);

            assertThrows(IllegalArgumentException.class, () -> {
                literals.create(method, Index.singleClass(ClassRetainedAnnotation.class),
                        AnnotationInstance.builder(ClassRetainedAnnotation.class).build());
            });
        }
    }

    private static void verify(ComplexAnnotation ann) {
        assertEquals(true, ann.bool());
        assertEquals((byte) 1, ann.b());
        assertEquals((short) 2, ann.s());
        assertEquals(3, ann.i());
        assertEquals(4L, ann.l());
        assertEquals(5.0F, ann.f());
        assertEquals(6.0, ann.d());
        assertEquals('a', ann.ch());
        assertEquals("bc", ann.str());
        assertEquals(SimpleEnum.FOO, ann.en());
        assertEquals(Object.class, ann.cls());
        assertEquals("one", ann.nested().value());

        assertEquals(2, ann.boolArray().length);
        assertEquals(true, ann.boolArray()[0]);
        assertEquals(false, ann.boolArray()[1]);
        assertEquals(2, ann.bArray().length);
        assertEquals((byte) 7, ann.bArray()[0]);
        assertEquals((byte) 8, ann.bArray()[1]);
        assertEquals(2, ann.sArray().length);
        assertEquals((short) 9, ann.sArray()[0]);
        assertEquals((short) 10, ann.sArray()[1]);
        assertEquals(2, ann.iArray().length);
        assertEquals(11, ann.iArray()[0]);
        assertEquals(12, ann.iArray()[1]);
        assertEquals(2, ann.lArray().length);
        assertEquals(13L, ann.lArray()[0]);
        assertEquals(14L, ann.lArray()[1]);
        assertEquals(2, ann.fArray().length);
        assertEquals(15.0F, ann.fArray()[0]);
        assertEquals(16.0F, ann.fArray()[1]);
        assertEquals(2, ann.dArray().length);
        assertEquals(17.0, ann.dArray()[0]);
        assertEquals(18.0, ann.dArray()[1]);
        assertEquals(2, ann.chArray().length);
        assertEquals('d', ann.chArray()[0]);
        assertEquals('e', ann.chArray()[1]);
        assertEquals(2, ann.strArray().length);
        assertEquals("fg", ann.strArray()[0]);
        assertEquals("hi", ann.strArray()[1]);
        assertEquals(2, ann.enArray().length);
        assertEquals(SimpleEnum.BAR, ann.enArray()[0]);
        assertEquals(SimpleEnum.BAZ, ann.enArray()[1]);
        assertEquals(2, ann.clsArray().length);
        assertEquals(String.class, ann.clsArray()[0]);
        assertEquals(Number.class, ann.clsArray()[1]);
        assertEquals(2, ann.nestedArray().length);
        assertEquals("two", ann.nestedArray()[0].value());
        assertEquals("three", ann.nestedArray()[1].value());
    }

    private static AnnotationInstance complexAnnotationJandex() {
        return AnnotationInstance.builder(ComplexAnnotation.class)
                .add("bool", true)
                .add("b", (byte) 1)
                .add("s", (short) 2)
                .add("i", 3)
                .add("l", 4L)
                .add("f", 5.0F)
                .add("d", 6.0)
                .add("ch", 'a')
                .add("str", "bc")
                .add("en", SimpleEnum.FOO)
                .add("cls", Object.class)
                .add("nested", simpleAnnotationJandex("one"))
                .add("boolArray", new boolean[] { true, false })
                .add("bArray", new byte[] { (byte) 7, (byte) 8 })
                .add("sArray", new short[] { (short) 9, (short) 10 })
                .add("iArray", new int[] { 11, 12 })
                .add("lArray", new long[] { 13L, 14L })
                .add("fArray", new float[] { 15.0F, 16.0F })
                .add("dArray", new double[] { 17.0, 18.0 })
                .add("chArray", new char[] { 'd', 'e' })
                .add("strArray", new String[] { "fg", "hi" })
                .add("enArray", new SimpleEnum[] { SimpleEnum.BAR, SimpleEnum.BAZ })
                .add("clsArray", new Class[] { String.class, Number.class })
                .add("nestedArray", new AnnotationInstance[] { simpleAnnotationJandex("two"), simpleAnnotationJandex("three") })
                .build();
    }

    private static AnnotationInstance simpleAnnotationJandex(String value) {
        return AnnotationInstance.builder(SimpleAnnotation.class)
                .add("value", value)
                .build();
    }

    private static ComplexAnnotation complexAnnotationRuntime() {
        return new ComplexAnnotation.Literal(
                true,
                (byte) 1,
                (short) 2,
                3,
                4L,
                5.0F,
                6.0,
                'a',
                "bc",
                SimpleEnum.FOO,
                Object.class,
                simpleAnnotationRuntime("one"),
                new boolean[] { true, false },
                new byte[] { (byte) 7, (byte) 8 },
                new short[] { (short) 9, (short) 10 },
                new int[] { 11, 12 },
                new long[] { 13L, 14L },
                new float[] { 15.0F, 16.0F },
                new double[] { 17.0, 18.0 },
                new char[] { 'd', 'e' },
                new String[] { "fg", "hi" },
                new SimpleEnum[] { SimpleEnum.BAR, SimpleEnum.BAZ },
                new Class[] { String.class, Number.class },
                new SimpleAnnotation[] { simpleAnnotationRuntime("two"), simpleAnnotationRuntime("three") });
    }

    private static SimpleAnnotation simpleAnnotationRuntime(String value) {
        return new SimpleAnnotation.Literal(value);
    }
}


text:
'use strict';

/**
 * Application logs to file system configuration.
 *
 */
class FileSystemApplicationLogsConfig {
  /**
   * Create a FileSystemApplicationLogsConfig.
   * @member {string} [level] Log level. Possible values include: 'Off',
   * 'Verbose', 'Information', 'Warning', 'Error'. Default value: 'Off' .
   */
  constructor() {
  }

  /**
   * Defines the metadata of FileSystemApplicationLogsConfig
   *
   * @returns {object} metadata of FileSystemApplicationLogsConfig
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'FileSystemApplicationLogsConfig',
      type: {
        name: 'Composite',
        className: 'FileSystemApplicationLogsConfig',
        modelProperties: {
          level: {
            required: false,
            serializedName: 'level',
            defaultValue: 'Off',
            type: {
              name: 'Enum',
              allowedValues: [ 'Off', 'Verbose', 'Information', 'Warning', 'Error' ]
            }
          }
        }
      }
    };
  }
}

module.exports = FileSystemApplicationLogsConfig;

redpajama_set_name: RedPajamaGithub


text:
package org.apache.spark.streaming

import org.apache.spark.streaming.dstream.{NetworkInputDStream, NetworkReceiver}
import org.apache.spark.streaming.dstream.{StopReceiver, ReportBlock, ReportError}
import org.apache.spark.Logging
import org.apache.spark.SparkEnv
import org.apache.spark.SparkContext._

import scala.collection.mutable.HashMap
import scala.collection.mutable.Queue

import akka.actor._
import akka.pattern.ask
import akka.util.duration._
import akka.dispatch._
import org.apache.spark.storage.BlockId

private[streaming] sealed trait NetworkInputTrackerMessage
private[streaming] case class RegisterReceiver(streamId: Int, receiverActor: ActorRef) extends NetworkInputTrackerMessage
private[streaming] case class AddBlocks(streamId: Int, blockIds: Seq[BlockId], metadata: Any) extends NetworkInputTrackerMessage
private[streaming] case class DeregisterReceiver(streamId: Int, msg: String) extends NetworkInputTrackerMessage

/**
 * This class manages the execution of the receivers of NetworkInputDStreams.
 */
private[streaming]
class NetworkInputTracker(
    @transient ssc: StreamingContext,
    @transient networkInputStreams: Array[NetworkInputDStream[_]])
  extends Logging {

  val networkInputStreamMap = Map(networkInputStreams.map(x => (x.id, x)): _*)
  val receiverExecutor = new ReceiverExecutor()
  val receiverInfo = new HashMap[Int, ActorRef]
  val receivedBlockIds = new HashMap[Int, Queue[BlockId]]
  val timeout = 5000.milliseconds

  var currentTime: Time = null

  /** Start the actor and receiver execution thread. */
  def start() {
    ssc.env.actorSystem.actorOf(Props(new NetworkInputTrackerActor), "NetworkInputTracker")
    receiverExecutor.start()
  }

  /** Stop the receiver execution thread. */
  def stop() {
    // TODO: stop the actor as well
    receiverExecutor.interrupt()
    receiverExecutor.stopReceivers()
  }

  /** Return all the blocks received from a receiver. */
  def getBlockIds(receiverId: Int, time: Time): Array[BlockId] = synchronized {
    val queue =  receivedBlockIds.synchronized {
      receivedBlockIds.getOrElse(receiverId, new Queue[BlockId]())
    }
    val result = queue.synchronized {
      queue.dequeueAll(x => true)
    }
    logInfo("Stream " + receiverId + " received " + result.size + " blocks")
    result.toArray
  }

  /** Actor to receive messages from the receivers. */
  private class NetworkInputTrackerActor extends Actor {
    def receive = {
      case RegisterReceiver(streamId, receiverActor) => {
        if (!networkInputStreamMap.contains(streamId)) {
          throw new Exception("Register received for unexpected id " + streamId)
        }
        receiverInfo += ((streamId, receiverActor))
        logInfo("Registered receiver for network stream " + streamId + " from " + sender.path.address)
        sender ! true
      }
      case AddBlocks(streamId, blockIds, metadata) => {
        val tmp = receivedBlockIds.synchronized {
          if (!receivedBlockIds.contains(streamId)) {
            receivedBlockIds += ((streamId, new Queue[BlockId]))
          }
          receivedBlockIds(streamId)
        }
        tmp.synchronized {
          tmp ++= blockIds
        }
        networkInputStreamMap(streamId).addMetadata(metadata)
      }
      case DeregisterReceiver(streamId, msg) => {
        receiverInfo -= streamId
        logError("De-registered receiver for network stream " + streamId
          + " with message " + msg)
        //TODO: Do something about the corresponding NetworkInputDStream
      }
    }
  }

  /** This thread class runs all the receivers on the cluster.  */
  class ReceiverExecutor extends Thread {
    val env = ssc.env

    override def run() {
      try {
        SparkEnv.set(env)
        startReceivers()
      } catch {
        case ie: InterruptedException => logInfo("ReceiverExecutor interrupted")
      } finally {
        stopReceivers()
      }
    }

    /**
     * Get the receivers from the NetworkInputDStreams, distributes them to the
     * worker nodes as a parallel collection, and runs them.
     */
    def startReceivers() {
      val receivers = networkInputStreams.map(nis => {
        val rcvr = nis.getReceiver()
        rcvr.setStreamId(nis.id)
        rcvr
      })

      // Right now, we only honor preferences if all receivers have them
      val hasLocationPreferences = receivers.map(_.getLocationPreference().isDefined).reduce(_ && _)

      // Create the parallel collection of receivers to distributed them on the worker nodes
      val tempRDD =
        if (hasLocationPreferences) {
          val receiversWithPreferences = receivers.map(r => (r, Seq(r.getLocationPreference().toString)))
          ssc.sc.makeRDD[NetworkReceiver[_]](receiversWithPreferences)
        }
        else {
          ssc.sc.makeRDD(receivers, receivers.size)
        }

      // Function to start the receiver on the worker node
      val startReceiver = (iterator: Iterator[NetworkReceiver[_]]) => {
        if (!iterator.hasNext) {
          throw new Exception("Could not start receiver as details not found.")
        }
        iterator.next().start()
      }
      // Run the dummy Spark job to ensure that all slaves have registered.
      // This avoids all the receivers to be scheduled on the same node.
      ssc.sparkContext.makeRDD(1 to 50, 50).map(x => (x, 1)).reduceByKey(_ + _, 20).collect()

      // Distribute the receivers and start them
      ssc.sparkContext.runJob(tempRDD, startReceiver)
    }

    /** Stops the receivers. */
    def stopReceivers() {
      // Signal the receivers to stop
      receiverInfo.values.foreach(_ ! StopReceiver)
    }
  }
}


text:
/**
 * This code was generated by
 * \ / _    _  _|   _  _
 *  | (_)\/(_)(_|\/| |(/_  v1.0.0
 *       /       /
 */

import Page = require('../../../../base/Page');
import Response = require('../../../../http/response');
import V2 = require('../../V2');
import serialize = require('../../../../base/serialize');
import { InviteList } from './channel/invite';
import { InviteListInstance } from './channel/invite';
import { MemberList } from './channel/member';
import { MemberListInstance } from './channel/member';
import { MessageList } from './channel/message';
import { MessageListInstance } from './channel/message';
import { SerializableClass } from '../../../../interfaces';
import { WebhookList } from './channel/webhook';
import { WebhookListInstance } from './channel/webhook';

type ChannelChannelType = 'public'|'private';

type ChannelWebhookEnabledType = 'true'|'false';

/**
 * @description Initialize the ChannelList
 *
 * @param version - Version of the resource
 * @param serviceSid - The unique id of the Service this channel belongs to.
 */
declare function ChannelList(version: V2, serviceSid: string): ChannelListInstance;

/**
 * Options to pass to update
 *
 * @property attributes - An optional string metadata field you can use to store any data you wish.
 * @property createdBy - Optional field to specify the Identity of the User that created the Channel.
 * @property dateCreated - The optional ISO8601 time specifying the datetime the Channel should be set as being created.
 * @property dateUpdated - The optional ISO8601 time specifying the datetime the Channel should be set as having been last updated.
 * @property friendlyName - A human-readable name for the Channel.
 * @property uniqueName - A unique, addressable name for the Channel.
 */
interface ChannelInstanceUpdateOptions {
  attributes?: string;
  createdBy?: string;
  dateCreated?: Date;
  dateUpdated?: Date;
  friendlyName?: string;
  uniqueName?: string;
}

interface ChannelListInstance {
  /**
   * @param sid - sid of instance
   */
  (sid: string): ChannelContext;
  /**
   * create a ChannelInstance
   *
   * @param opts - Options for request
   * @param callback - Callback to handle processed record
   */
  create(opts?: ChannelListInstanceCreateOptions, callback?: (error: Error | null, item: ChannelInstance) => any): Promise<ChannelInstance>;
  /**
   * Streams ChannelInstance records from the API.
   *
   * This operation lazily loads records as efficiently as possible until the limit
   * is reached.
   *
   * The results are passed into the callback function, so this operation is memory efficient.
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @param opts - Options for request
   * @param callback - Function to process each record
   */
  each(opts?: ChannelListInstanceEachOptions, callback?: (item: ChannelInstance, done: (err?: Error) => void) => void): void;
  /**
   * Constructs a channel
   *
   * @param sid - Key that uniquely defines the channel to fetch.
   */
  get(sid: string): ChannelContext;
  /**
   * Retrieve a single target page of ChannelInstance records from the API.
   * Request is executed immediately
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @param targetUrl - API-generated URL for the requested results page
   * @param callback - Callback to handle list of records
   */
  getPage(targetUrl?: string, callback?: (error: Error | null, items: ChannelPage) => any): Promise<ChannelPage>;
  /**
   * Lists ChannelInstance records from the API as a list.
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @param opts - Options for request
   * @param callback - Callback to handle list of records
   */
  list(opts?: ChannelListInstanceOptions, callback?: (error: Error | null, items: ChannelInstance[]) => any): Promise<ChannelInstance[]>;
  /**
   * Retrieve a single page of ChannelInstance records from the API.
   * Request is executed immediately
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @param opts - Options for request
   * @param callback - Callback to handle list of records
   */
  page(opts?: ChannelListInstancePageOptions, callback?: (error: Error | null, items: ChannelPage) => any): Promise<ChannelPage>;
}

/**
 * Options to pass to create
 *
 * @property attributes - An optional string metadata field you can use to store any data you wish.
 * @property createdBy - Optional field to specify the Identity of the User that created the Channel.
 * @property dateCreated - The optional ISO8601 time specifying the datetime the Channel should be set as being created.
 * @property dateUpdated - The optional ISO8601 time specifying the datetime the Channel should be set as having been last updated.
 * @property friendlyName - A human-readable name for the Channel.
 * @property type - The visibility of the channel - public or private.
 * @property uniqueName - A unique, addressable name for the Channel.
 */
interface ChannelListInstanceCreateOptions {
  attributes?: string;
  createdBy?: string;
  dateCreated?: Date;
  dateUpdated?: Date;
  friendlyName?: string;
  type?: ChannelChannelType;
  uniqueName?: string;
}

/**
 * Options to pass to each
 *
 * @property callback -
 *                         Function to process each record. If this and a positional
 *                         callback are passed, this one will be used
 * @property done - Function to be called upon completion of streaming
 * @property limit -
 *                         Upper limit for the number of records to return.
 *                         each() guarantees never to return more than limit.
 *                         Default is no limit
 * @property pageSize -
 *                         Number of records to fetch per request,
 *                         when not set will use the default value of 50 records.
 *                         If no pageSize is defined but a limit is defined,
 *                         each() will attempt to read the limit with the most efficient
 *                         page size, i.e. min(limit, 1000)
 * @property type - The visibility of the channel - public or private.
 */
interface ChannelListInstanceEachOptions {
  callback?: (item: ChannelInstance, done: (err?: Error) => void) => void;
  done?: Function;
  limit?: number;
  pageSize?: number;
  type?: string[];
}

/**
 * Options to pass to list
 *
 * @property limit -
 *                         Upper limit for the number of records to return.
 *                         list() guarantees never to return more than limit.
 *                         Default is no limit
 * @property pageSize -
 *                         Number of records to fetch per request,
 *                         when not set will use the default value of 50 records.
 *                         If no page_size is defined but a limit is defined,
 *                         list() will attempt to read the limit with the most
 *                         efficient page size, i.e. min(limit, 1000)
 * @property type - The visibility of the channel - public or private.
 */
interface ChannelListInstanceOptions {
  limit?: number;
  pageSize?: number;
  type?: string[];
}

/**
 * Options to pass to page
 *
 * @property pageNumber - Page Number, this value is simply for client state
 * @property pageSize - Number of records to return, defaults to 50
 * @property pageToken - PageToken provided by the API
 * @property type - The visibility of the channel - public or private.
 */
interface ChannelListInstancePageOptions {
  pageNumber?: number;
  pageSize?: number;
  pageToken?: string;
  type?: string[];
}

interface ChannelPayload extends ChannelResource, Page.TwilioResponsePayload {
}

interface ChannelResource {
  account_sid: string;
  attributes: string;
  created_by: string;
  date_created: Date;
  date_updated: Date;
  friendly_name: string;
  links: string;
  members_count: number;
  messages_count: number;
  service_sid: string;
  sid: string;
  type: ChannelChannelType;
  unique_name: string;
  url: string;
}

interface ChannelSolution {
  serviceSid?: string;
}

declare class ChannelContext {
  /**
   * Initialize the ChannelContext
   *
   * @property members - members resource
   * @property messages - messages resource
   * @property invites - invites resource
   * @property webhooks - webhooks resource
   *
   * @param version - Version of the resource
   * @param serviceSid - Sid of the Service this channel belongs to.
   * @param sid - Key that uniquely defines the channel to fetch.
   */
  constructor(version: V2, serviceSid: string, sid: string);

  /**
   * fetch a ChannelInstance
   *
   * @param callback - Callback to handle processed record
   */
  fetch(callback?: (error: Error | null, items: ChannelInstance) => any): Promise<ChannelInstance>;
  invites: InviteListInstance;
  members: MemberListInstance;
  messages: MessageListInstance;
  /**
   * remove a ChannelInstance
   *
   * @param callback - Callback to handle processed record
   */
  remove(callback?: (error: Error | null, items: ChannelInstance) => any): void;
  /**
   * update a ChannelInstance
   *
   * @param opts - Options for request
   * @param callback - Callback to handle processed record
   */
  update(opts?: ChannelInstanceUpdateOptions, callback?: (error: Error | null, items: ChannelInstance) => any): Promise<ChannelInstance>;
  webhooks: WebhookListInstance;
}

declare class ChannelInstance extends SerializableClass {
  /**
   * Initialize the ChannelContext
   *
   * @property sid - A 34 character string that uniquely identifies this resource.
   * @property accountSid - The unique id of the Account responsible for this channel.
   * @property serviceSid - The unique id of the Service this channel belongs to.
   * @property friendlyName - The human-readable name of this channel.
   * @property uniqueName - The unique, addressable name of this channel.
   * @property attributes - An optional string metadata field you can use to store any data you wish.
   * @property type - The visibility of this channel - either public or private
   * @property dateCreated - The date that this resource was created.
   * @property dateUpdated - The date that this resource was last updated.
   * @property createdBy - Identity of the channel's creator.
   * @property membersCount - The number of Members in the Channel
   * @property messagesCount - The number of Messages in the Channel
   * @property url - An absolute URL for this channel.
   * @property links - Absolute URLs to access the Members, Messages , Invites and, if it exists the last Message for this Channel.
   *
   * @param version - Version of the resource
   * @param payload - The instance payload
   * @param serviceSid - The unique id of the Service this channel belongs to.
   * @param sid - Key that uniquely defines the channel to fetch.
   */
  constructor(version: V2, payload: ChannelPayload, serviceSid: string, sid: string);

  private _proxy: ChannelContext;
  accountSid: string;
  attributes: string;
  createdBy: string;
  dateCreated: Date;
  dateUpdated: Date;
  /**
   * fetch a ChannelInstance
   *
   * @param callback - Callback to handle processed record
   */
  fetch(callback?: (error: Error | null, items: ChannelInstance) => any): void;
  friendlyName: string;
  /**
   * Access the invites
   */
  invites(): InviteListInstance;
  links: string;
  /**
   * Access the members
   */
  members(): MemberListInstance;
  membersCount: number;
  /**
   * Access the messages
   */
  messages(): MessageListInstance;
  messagesCount: number;
  /**
   * remove a ChannelInstance
   *
   * @param callback - Callback to handle processed record
   */
  remove(callback?: (error: Error | null, items: ChannelInstance) => any): void;
  serviceSid: string;
  sid: string;
  /**
   * Produce a plain JSON object version of the ChannelInstance for serialization.
   * Removes any circular references in the object.
   */
  toJSON(): any;
  type: ChannelChannelType;
  uniqueName: string;
  /**
   * update a ChannelInstance
   *
   * @param opts - Options for request
   * @param callback - Callback to handle processed record
   */
  update(opts?: ChannelInstanceUpdateOptions, callback?: (error: Error | null, items: ChannelInstance) => any): void;
  url: string;
  /**
   * Access the webhooks
   */
  webhooks(): WebhookListInstance;
}

declare class ChannelPage extends Page<V2, ChannelPayload, ChannelResource, ChannelInstance> {
  /**
   * Initialize the ChannelPage
   *
   * @param version - Version of the resource
   * @param response - Response from the API
   * @param solution - Path solution
   */
  constructor(version: V2, response: Response<string>, solution: ChannelSolution);

  /**
   * Build an instance of ChannelInstance
   *
   * @param payload - Payload response from the API
   */
  getInstance(payload: ChannelPayload): ChannelInstance;
}

export { ChannelContext, ChannelInstance, ChannelList, ChannelListInstance, ChannelListInstanceCreateOptions, ChannelListInstanceEachOptions, ChannelListInstanceOptions, ChannelListInstancePageOptions, ChannelPage, ChannelPayload, ChannelResource, ChannelSolution }


text:
package ru.job4j.principle_004;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.AfterClass;
import org.junit.Ignore;
import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
import static ru.job4j.principle_004.ConnectionRollback.create;

/**
 * Tests for hibernate.
 */
@Ignore
public class HibernateStoreTest {
    /**
     * Create a new user and check id.
     */
    @Test
    public void whenCreateUser() {
        SessionFactory factory = create(HibernateFactory.FACTORY);
        HibernateStore store = new HibernateStore(factory);
        User user = store.add(new User(-1, "Petr Arsentev"));
        assertThat(
                user.getId(),
                not(-1)
        );
        factory.close();
    }

    /**
     * Create a new user and find it.
     */
    @Test
    public void whenCreateAndFind() {
        SessionFactory factory = create(HibernateFactory.FACTORY);
        Session session = factory.openSession();
        HibernateStore store = new HibernateStore(factory);
        User user = store.add(new User(-1, "Petr Arsentev"));
        assertThat(
                store.findById(user.getId()).getLogin(),
                is("Petr Arsentev")
        );
        session.clear();
        assertThat(store.findAll().isEmpty(), is(true));
        factory.close();
    }

    /**
     * Clean tests data.
     */
    @AfterClass
    public static void close() {
        HibernateFactory.FACTORY.close();
    }
}


text:
package edu.uci.ics.asterix.fuzzyjoin.tokenorder;

import java.util.Collection;
import java.util.HashMap;
import java.util.TreeSet;

public class TokenRankFrequency implements TokenRank {
    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private final HashMap<String, Integer> ranksMap = new HashMap<String, Integer>();
    private int crtRank = 0;

    public int add(String token) {
        int prevRank = crtRank;
        ranksMap.put(token, prevRank);
        crtRank++;
        return prevRank;
    }

    public Integer getRank(String token) {
        return ranksMap.get(token);
    }

    public Collection<Integer> getTokenRanks(Iterable<String> tokens) {
        TreeSet<Integer> ranksCol = new TreeSet<Integer>();
        for (String token : tokens) {
            Integer rank = getRank(token);
            if (rank != null) {
                ranksCol.add(rank);
            }
        }
        return ranksCol;
    }

    @Override
    public String toString() {
        return "[" + crtRank + ",\n " + ranksMap + "\n]";
    }
}


text:
set -e
# if you dont have internet access from your cluster nodes, you will
# not be able to "knife bootstrap" nodes to get them ready for
# chef. Instead you need to install chef separately. Assuming the
# necessary bits are hosted on your binary_server_url as setup by
# build_bins.sh this will allow you to proceed

BINARY_SERVER_HOST=${1:?"Need a Binary Server Host"}
BINARY_SERVER_URL=${2:?"Need a Binary Server URL"}
CHEF_SERVER_IP=${3:?"Need a Chef Server IP"}
CHEF_SERVER_HOSTNAME=${4:?"Need a Chef Server hostname"}

echo -e "${CHEF_SERVER_IP}\t$CHEF_SERVER_HOSTNAME" >> /etc/hosts
grep -q $BINARY_SERVER_HOST /etc/apt/apt.conf || echo "Acquire::http::Proxy::$BINARY_SERVER_HOST 'DIRECT';" >> /etc/apt/apt.conf
echo "deb [arch=amd64] $BINARY_SERVER_URL 0.5.0 main" > /etc/apt/sources.list.d/bcpc.list
wget --no-proxy -O - ${BINARY_SERVER_URL}/apt_key.pub | apt-key add -
apt-get update
apt-get install -y chef

# setup OpenStack hint
mkdir -p /etc/chef/ohai/hints/
touch /etc/chef/ohai/hints/openstack.json

# remove rubygems and install only our gemserver
/opt/chef/embedded/bin/gem sources --add ${BINARY_SERVER_URL}
/opt/chef/embedded/bin/gem sources --remove http://rubygems.org/


text:
var joinOrCreate;
var responseData;

$(function() {
    loadHome();
 });

function loadHome() {
    $("#root").hide().load("home.part.html", function() {
	formDefaultBehavior("#create-new-game", "/create-room/", {
	    username: {required: true, minlength: 3}
	});
	formDefaultBehavior("#join-game", "/join-room/", {
	    username: {required: true, minlength: 3, url: '/validate-username'},
	    code: {required: true, url: '/validate-code/'}
	});
    }).fadeIn('slow');
}

function formDefaultBehavior(form, url, rules) {
    $(form).hide();
    $(form + "-btn").click(function() {
	joinOrCreate = this.id;
	$(form + "-btn").toggleClass("btn-primary btn-dark");
	$(form).slideToggle("fast");
    });

    var validationRules = {};

    for (var field in rules) {
	validationRules[field] = {};
	validationRules[field]['required'] = rules[field]['required'] || false;
	if (rules[field]['minlength']) {
	    validationRules[field]['minlength'] = rules[field]['minlength'];
	}
	if (rules[field]['url']) {
	    validationRules[field]['remote'] = {
		url: rules[field]['url'],
		type: "post",
		data: {
		    code: function() {
			return $(form + " input[name=" + field + "]").val();
		    }
		}
	    };
	}
    }

    $(form).validate({
	onkeyup: false,
	onfocusout: false,

	rules: validationRules,

	messages: {
	    username: {
		required: "this is required",
		minlength: "at least 3 characters"
	    },
	    code: {
		required: "this is required"
	    }
	},

	submitHandler: function() {
	    $.post(url, $(form).serialize(), function(data){
		responseData = data;
		console.log(responseData);
		if (responseData) {
		    loadWaitingRoom();
		}
	    });
	}

    });

    $(document).mouseup(function(event) {
	if (!$(form).is(event.target) && !$(form + "-btn").is(event.target) && $(form).has(event.target).length === 0) {
	    $(form).slideUp("fast");
	    $(form + "-btn").removeClass("btn-dark");
	    $(form + "-btn").addClass("btn-primary");
	}
    });
}

function loadWaitingRoom() {
    $("#root").hide().load("waiting-room.part.html", function() {
	waitingRoomDefaultBehavior();
	if (joinOrCreate == "create-new-game-btn") {
	    $("#join-waiting").remove();
	    $("#code").text(responseData['code']);
	} else if (joinOrCreate == "join-game-btn") {
	    $("#game-code").remove();
	    $("#start-game").remove();
	    $("#creator-name").text(responseData['creator'] + "'s game");
	}
    }).fadeIn('slow');
}

function waitingRoomDefaultBehavior() {
    $("#back-btn").click(function() {
	loadHome();
    });
    $("#p1-ready-btn").click(function() {
	$("#p1-ready").toggleClass("fa-question fa-check");
    });

    $("#p2-ready-btn").click(function() {
	$("#p2-ready").toggleClass("fa-question fa-check");
    });
}


text:
class Upload < ApplicationRecord
  include Checksummable
  # Upper limit for foreground checksum processing
  CHECKSUM_THRESHOLD = 100.megabytes

  belongs_to :model, polymorphic: true # rubocop:disable Cop/PolymorphicAssociations

  validates :size, presence: true
  validates :path, presence: true
  validates :model, presence: true
  validates :uploader, presence: true

  scope :with_files_stored_locally, -> { where(store: ObjectStorage::Store::LOCAL) }
  scope :with_files_stored_remotely, -> { where(store: ObjectStorage::Store::REMOTE) }

  before_save  :calculate_checksum!, if: :foreground_checksummable?
  after_commit :schedule_checksum,   if: :needs_checksum?

  # as the FileUploader is not mounted, the default CarrierWave ActiveRecord
  # hooks are not executed and the file will not be deleted
  after_destroy :delete_file!, if: -> { uploader_class <= FileUploader }

  class << self
    ##
    # FastDestroyAll concerns
    def begin_fast_destroy
      {
        Uploads::Local => Uploads::Local.new.keys(with_files_stored_locally),
        Uploads::Fog => Uploads::Fog.new.keys(with_files_stored_remotely)
      }
    end

    ##
    # FastDestroyAll concerns
    def finalize_fast_destroy(keys)
      keys.each do |store_class, paths|
        store_class.new.delete_keys_async(paths)
      end
    end
  end

  def absolute_path
    raise ObjectStorage::RemoteStoreError, _("Remote object has no absolute path.") unless local?
    return path unless relative_path?

    uploader_class.absolute_path(self)
  end

  def calculate_checksum!
    self.checksum = nil
    return unless needs_checksum?

    self.checksum = self.class.hexdigest(absolute_path)
  end

  # Initialize the associated Uploader class with current model
  #
  # @param [String] mounted_as
  # @return [GitlabUploader] one of the subclasses, defined at the model's uploader attribute
  def build_uploader(mounted_as = nil)
    uploader_class.new(model, mounted_as || mount_point).tap do |uploader|
      uploader.upload = self
    end
  end

  # Initialize the associated Uploader class with current model and
  # retrieve existing file from the store to a local cache
  #
  # @param [String] mounted_as
  # @return [GitlabUploader] one of the subclasses, defined at the model's uploader attribute
  def retrieve_uploader(mounted_as = nil)
    build_uploader(mounted_as).tap do |uploader|
      uploader.retrieve_from_store!(identifier)
    end
  end

  # This checks for existence of the upload on storage
  #
  # @return [Boolean] whether upload exists on storage
  def exist?
    exist = if local?
              File.exist?(absolute_path)
            else
              retrieve_uploader.exists?
            end

    # Help sysadmins find missing upload files
    if persisted? && !exist
      if Gitlab::Sentry.enabled?
        Raven.capture_message(_("Upload file does not exist"), extra: self.attributes)
      end

      Gitlab::Metrics.counter(:upload_file_does_not_exist_total, _('The number of times an upload record could not find its file')).increment
    end

    exist
  end

  def uploader_context
    {
      identifier: identifier,
      secret: secret
    }.compact
  end

  def local?
    store == ObjectStorage::Store::LOCAL
  end

  # Returns whether generating checksum is needed
  #
  # This takes into account whether file exists, if any checksum exists
  # or if the storage has checksum generation code implemented
  #
  # @return [Boolean] whether generating a checksum is needed
  def needs_checksum?
    checksum.nil? && local? && exist?
  end

  private

  def delete_file!
    retrieve_uploader.remove!
  end

  def foreground_checksummable?
    needs_checksum? && size <= CHECKSUM_THRESHOLD
  end

  def schedule_checksum
    UploadChecksumWorker.perform_async(id)
  end

  def relative_path?
    !path.start_with?('/')
  end

  def uploader_class
    Object.const_get(uploader, false)
  end

  def identifier
    File.basename(path)
  end

  def mount_point
    super&.to_sym
  end
end

Upload.prepend_if_ee('EE::Upload')


text:
require 'time'

module AmazonDrs
  class Base
    attr_accessor :status_code, :request_id, :date, :error_type, :error_description_url

    def initialize(response)
      @response = response
      @status_code = response.code.to_i
      parse_header(response)
      parse_body(response.body)
    end

    private def parse_header(response)
      response.each do |key, value|
        case key.downcase
        when 'x-amzn-errortype'
          # Examples:
          #   InvalidTokenException:http://internal.amazon.com/coral/com.amazon.parkeraccioservice/
          #   OA2InvalidRequestException:http://internal.amazon.com/coral/com.amazon.panda/
          @error_type, @error_description_url = value.split(':', 2)
        when 'x-amzn-requestid'
          # Example:
          #   X-Amzn-Requestid: d296d296-d1d1-1111-8c8c-0b43820b4382
          @request_id = value
        when 'x-amz-date'
          # Example:
          #   X-Amz-Date: Mon, 02 Jan 2017 22:35:53 GMT
          @date = Time.rfc2822(value)
        end
      end
    end

    private def parse_body(body)
      # abstract
    end

    def inspect
      if @status_code == 200
        self.class.name
      else
        resp = "ERROR #{@status_code} : "
        resp += @message if instance_variable_defined?(:@message) && @message
        resp += @error_description if instance_variable_defined?(:@error_description) && @error_description
        resp
      end
    end
  end
end


text:
<?php

namespace EscapeWork\Moip\Resources;

use EscapeWork\Moip\Exceptions\RemoteException;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;

class OAuthAuthorization extends Resource
{
    /**
     * Models needed
     */
    protected $required = [
        'response_type',
        'client_id',
        'redirect_uri',
    ];

    public function generateAuthorizationLink()
    {
        $data = [
            'response_type' => 'code',
            'client_id'     => $this->client_id,
            'redirect_uri'  => $this->redirect_uri,
        ];

        $endpoint = $this->endpoints['connect'][$this->config->getEnvironment()];

        return $endpoint . 'oauth/authorize?' . http_build_query($data);
    }

    public function setClientId($client_id)
    {
        $this->client_id = $client_id;
        return $this;
    }

    public function setRedirectUri($redirect_uri)
    {
        $this->redirect_uri = $redirect_uri;
        return $this;
    }
}


text:
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.

package org.jetbrains.kotlin.idea.refactoring.copy;

import com.intellij.testFramework.TestDataPath;
import org.jetbrains.kotlin.idea.test.JUnit3RunnerWithInners;
import org.jetbrains.kotlin.idea.test.KotlinTestUtils;
import org.jetbrains.kotlin.test.TestMetadata;
import org.jetbrains.kotlin.idea.base.test.TestRoot;
import org.junit.runner.RunWith;

/**
 * This class is generated by {@link org.jetbrains.kotlin.testGenerator.generator.TestGenerator}.
 * DO NOT MODIFY MANUALLY.
 */
@SuppressWarnings("all")
@TestRoot("idea/tests")
@TestDataPath("$CONTENT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
@TestMetadata("testData/refactoring/copyMultiModule")
public class MultiModuleCopyTestGenerated extends AbstractMultiModuleCopyTest {
    private void runTest(String testDataFilePath) throws Exception {
        KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
    }

    @TestMetadata("fileNotUnderSourceRoot/fileNotUnderSourceRoot.test")
    public void testFileNotUnderSourceRoot_FileNotUnderSourceRoot() throws Exception {
        runTest("testData/refactoring/copyMultiModule/fileNotUnderSourceRoot/fileNotUnderSourceRoot.test");
    }

    @TestMetadata("internalReferencesToAnotherModule2/internalReferencesToAnotherModule.test")
    public void testInternalReferencesToAnotherModule2_InternalReferencesToAnotherModule() throws Exception {
        runTest("testData/refactoring/copyMultiModule/internalReferencesToAnotherModule2/internalReferencesToAnotherModule.test");
    }

    @TestMetadata("referencesToUnrelatedModule/referencesToUnrelatedModule.test")
    public void testReferencesToUnrelatedModule_ReferencesToUnrelatedModule() throws Exception {
        runTest("testData/refactoring/copyMultiModule/referencesToUnrelatedModule/referencesToUnrelatedModule.test");
    }
}


text:
package com.eagerlogic.cubee.client.components;

import com.eagerlogic.cubee.client.components.AComponent;
import com.eagerlogic.cubee.client.components.AUserControl;
import com.eagerlogic.cubee.client.components.LayoutChildren;
import com.eagerlogic.cubee.client.components.Panel;
import com.eagerlogic.cubee.client.components.VBox;
import com.eagerlogic.cubee.client.events.Event;
import com.eagerlogic.cubee.client.events.EventArgs;
import com.eagerlogic.cubee.client.events.IEventListener;
import com.eagerlogic.cubee.client.properties.BooleanProperty;
import com.eagerlogic.cubee.client.properties.IChangeListener;
import com.eagerlogic.cubee.client.properties.KeyFrame;
import com.eagerlogic.cubee.client.properties.Timeline;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author dipacs
 */
public abstract class AbstractTreeViewItem<T> extends AUserControl {

    static final class ItemClickedEventArgs extends EventArgs {

        public ItemClickedEventArgs(AbstractTreeViewItem<?> sender) {
            super(sender);
        }

        public final AbstractTreeViewItem<?> getItem() {
            return (AbstractTreeViewItem<?>) getSender();
        }

    }

    private final Event<ItemClickedEventArgs> onItemClicked = new Event<ItemClickedEventArgs>();
    private final Event<EventArgs> onChildrenChanged = new Event<EventArgs>();

    private final BooleanProperty selected = new BooleanProperty(false, false, true);
    private final BooleanProperty selectedWriter = new BooleanProperty(false, false, false);
    private final BooleanProperty expanded = new BooleanProperty(false, false, false);
    private final BooleanProperty leaf = new BooleanProperty(true, false, true);
    private final BooleanProperty leafWriter = new BooleanProperty(true, false, false);
    private final List<AbstractTreeViewItem<?>> items = new ArrayList<AbstractTreeViewItem<?>>();
    private final T value;

    private VBox root;
    private Panel rootComponentHolder;
    private Panel childrenPanel;
    private VBox childrenHolder;
    private AComponent rootComponent;

    private Timeline timeline;

    private final IEventListener<ItemClickedEventArgs> onItemClickedEventListener = new IEventListener<ItemClickedEventArgs>() {

        @Override
        public void onFired(ItemClickedEventArgs args) {
            onItemClicked.fireEvent(args);
        }
    };

    public AbstractTreeViewItem(T value) {
        this.value = value;

        selected.initReadonlyBind(selectedWriter);
        leaf.initReadonlyBind(leafWriter);

        root = new VBox();
        root.pointerTransparentProperty().set(true);
        super.getChildren().add(root);

        rootComponentHolder = new Panel();
        rootComponentHolder.pointerTransparentProperty().set(Boolean.TRUE);
        root.getChildren().add(rootComponentHolder);

        childrenPanel = new Panel();
        childrenPanel.transformCenterYProperty().set(0.0);
        childrenPanel.scaleYProperty().set(0.0);
        childrenPanel.pointerTransparentProperty().set(true);
        root.getChildren().add(childrenPanel);

        childrenHolder = new VBox();
        childrenHolder.translateXProperty().set(20);
        childrenHolder.pointerTransparentProperty().set(true);
        childrenPanel.getChildren().add(childrenHolder);

        expanded.addChangeListener(new IChangeListener() {

            @Override
            public void onChanged(Object sender) {
                startAnimation();
            }
        });
    }

    private void startAnimation() {
        if (timeline != null) {
            timeline.stop();
        }

        if (expanded.get()) {
            timeline = new Timeline(new KeyFrame(0, childrenPanel.scaleYProperty(), 0.0)
                    , new KeyFrame(200, childrenPanel.scaleYProperty(), 1.0));
        } else {
            timeline = new Timeline(new KeyFrame(0, childrenPanel.scaleYProperty(), 1.0)
                    , new KeyFrame(200, childrenPanel.scaleYProperty(), 0.0));
        }
        timeline.start();
    }

    private void refreshChildren() {
        childrenHolder.getChildren().clear();
        if (getItems() != null) {
            for (AbstractTreeViewItem<?> item : items) {
                childrenHolder.addEmptyCell(2);
                childrenHolder.getChildren().add(item);
            }
            leafWriter.set(items.size() < 1);
        }
    }

    public AComponent getRootComponent() {
        return rootComponent;
    }

    public void setRootComponent(AComponent rootComponent) {
        rootComponentHolder.getChildren().clear();
        this.rootComponent = rootComponent;
        rootComponentHolder.getChildren().add(rootComponent);
    }

    @Override
    @Deprecated
    protected LayoutChildren getChildren() {
        return super.getChildren();
    }

    public final BooleanProperty selectedProperty() {
        return selected;
    }

    final BooleanProperty selectedWriterProperty() {
        return selectedWriter;
    }

    public final BooleanProperty expandedProperty() {
        return expanded;
    }

    public final List<AbstractTreeViewItem<?>> getItems() {
        if (items == null) {
            return null;
        }
        return new ArrayList<AbstractTreeViewItem<?>>(items);
    }

//    public final void setItems(List<AbstractTreeViewItem> items) {
//        this.items = items;
//        leaf.set(items == null || items.size() < 1);
//        refreshChildren();
//    }

    public final BooleanProperty leafProperty() {
        return leaf;
    }

    final Event<ItemClickedEventArgs> onItemClickedEvent() {
        return onItemClicked;
    }

    protected final void fireItemClickedEvent(AbstractTreeViewItem item) {
        this.onItemClicked.fireEvent(new ItemClickedEventArgs(item));
    }

    public final void addChildren(AbstractTreeViewItem item) {
        if (item == null) {
            throw new NullPointerException("The item property can not be null.");
        }
        this.items.add(item);
        item.onItemClicked.addListener(onItemClickedEventListener);
        refreshChildren();
        onChildrenChanged.fireEvent(new EventArgs(this));
    }

    public final AbstractTreeViewItem<?> removeChildren(int index) {
        AbstractTreeViewItem<?> res = items.remove(index);
        res.onItemClicked.removeListener(onItemClickedEventListener);
        refreshChildren();
        onChildrenChanged.fireEvent(new EventArgs(this));
        return res;
    }

    public final void removeChildren(AbstractTreeViewItem<?> item) {
        item.onItemClicked.removeListener(onItemClickedEventListener);
        items.remove(item);
        refreshChildren();
        onChildrenChanged.fireEvent(new EventArgs(this));
    }

    public final void insertChildren(AbstractTreeViewItem<?> item, int index) {
        if (item == null) {
            throw new NullPointerException("The item property can not be null.");
        }
        this.items.add(index, item);
        item.onItemClicked.addListener(onItemClickedEventListener);
        refreshChildren();
        onChildrenChanged.fireEvent(new EventArgs(this));
    }

    public final void clearChildren() {
        for (AbstractTreeViewItem item : items) {
            item.onItemClicked.removeListener(onItemClickedEventListener);
        }
        this.items.clear();
        refreshChildren();
        onChildrenChanged.fireEvent(new EventArgs(this));
    }

    public final int getChildrenCount() {
        return items.size();
    }

    public Event<EventArgs> onChildrenChangedEvent() {
        return onChildrenChanged;
    }

    void deselect() {
        this.selectedWriter.set(false);
        for (AbstractTreeViewItem item : items) {
            item.deselect();
        }
    }

    public final T getValue() {
        return value;
    }

}


text:
import React from 'react';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';

// route components
import App from '../../ui/App.jsx';
import CreateCourse from '../../ui/routes/createCourse/CreateCourse.jsx';
import CourseOverview from '../../ui/routes/courseOverview/CourseOverview.jsx';
import NotFoundPage from '../../ui/routes/notFound/notFound.jsx';
import Course from '../../ui/routes/course/course.jsx';
import EventEmitter from 'wolfy87-eventemitter';

var eventEmitter = new EventEmitter();

export const renderRoutes = () => (
  <Router history={browserHistory}>
    <Route path="/" component={App}>
      <IndexRoute component={CourseOverview} eventEmitter={eventEmitter}/>
      <Route path="create" component={CreateCourse} eventEmitter={eventEmitter}/>
      <Route path="course" component={Course} eventEmitter={eventEmitter}/>
      <Route path="*" component={NotFoundPage}/>
    </Route>
  </Router>
);


text:
cordova.define("org.apache.cordova.file.Metadata", function(require, exports, module) {

/**
 * Information about the state of the file or directory
 *
 * {Date} modificationTime (readonly)
 */
var Metadata = function(time) {
    this.modificationTime = (typeof time != 'undefined'?new Date(time):null);
};

module.exports = Metadata;
});


text:
<template name="adminRefereeDelete">
    {{> adminNavigation}}

Schiedsrichter löschen

        {{> errors}}

            {{ >deleteRefereeForm}}

</template>

<template name="deleteRefereeForm">
    <form class="deleteRefereeForm">

            Soll der Schiedsrichter {{referee.name}} unwideruflich gelöscht werden?

                <button class="btn btn-danger" type="submit">delete Ja</button>
                <button class="btn btn-primary cancel-button" type="button">close Nein</button>

    </form>
</template>


text:
<?php
/**
 * Breadcrumb Behavior
 *
 * @package default
 * @author Armando Sosa
 */
class BreadcrumbsBehavior extends DuperrificBehavior{

	function breadcrumbs(&$blog,$options = array()){

		$options = set_merge(array(
				'drop_first_category_node' => 1,
				'search_label'=>'Search',
			),$options);

		$pageType = $blog->getCurrentPageType();
		$methodName = "_{$pageType}Breadcrumbs";
		if (method_exists($this,$methodName)) {
			echo $this->{$methodName}($options);
		}
	}

	function _list($links,$mask = "

%s\n
\n
",$itemMask = "\n
%s
"){
		$list = '';
		$last = count($links);
		$count = 0;
		foreach ($links as $link) {
			$count++;
			$class = '';
			if ($count == $last) {
				$class = " class=\"current\"";
			}
			$list .= sprintf($itemMask,$class,$link);
		}
		return sprintf($mask,$list);
	}

	function _categoryBreadcrumbs($options){
		$id = get_query_var('cat');
		$links = $this->_getCategoryParentLinks($id,$options);

		return $this->_list($links);
	}

	function _getCategoryParentLinks($id,&$options){
		$links = get_category_parents($id,1,"|");
		$links = explode('|',$links);
		array_pop($links);

		if ($options['drop_first_category_node']) {
			array_shift($links);
		}

		return $links;
	}

	function _singleBreadcrumbs($options){
		$cats = get_the_category();
		$id = $cats[0]->cat_ID;
		$links = $this->_getCategoryParentLinks($id,$options);
		$links[] = HtmlHelper::link(get_the_title(),get_permalink());
		return $this->_list($links);
	}

	function _searchBreadcrumbs($options){
		$links = array(
				"{$options['search_label']}",
				"".get_search_query()."",
			);
		return $this->_list($links);

	}
}
?>


text:
<?xml version="1.0" encoding="UTF-8"?>
<resources>

    <color name="result_view">#b0000000</color>
    <color name="viewfinder_mask">#60000000</color>
    <color name="possible_result_points">#c0ffff00</color>
    <color name="viewfinder_laser">#ffcc0000</color>
    <color name="result_points">#c099cc00</color>
    <color name="viewfinder_frame">#66FF00</color>
    <color name="transparent">#00000000</color>
    <color name="black">#000000</color>
    <color name="white">#FFFFFF</color>
    <color name="blue">#00B2EE</color>
    <color name="yellow">#EEE685</color>
    <color name="grey">#EBEBEB</color>
</resources>


text:
The official theme template from the team, for every prospective/current themer who wishes to join the Substratum game!

There are seven types of Substratum as of this date (06/05/18)
  - Substratum OMS (3/7) (Marshmallow) [Marshmallow has been deprecated since 510, but it is still available]
  - Substratum OMS (7) (Nougat)
  - Substratum Dynamic Overlays (Stock Oreo) [Will require a rooted device, or Andromeda installed]
  - Substratum Dynamic Overlays (Oreo)
  - Substratum Samsung (RRO-OMS fusion) [Will require a device with the samsung plugin]
  - Substratum Samsung Oreo (OMS-RRO fusion) [Will require a device with the andromeda plugin]
  - Substratum Legacy (RRO) [Rooted]

To get started, first of all, FORK and CLONE this project on GitHub and open it up with Android Studio (We recommend to keep yourself up to date with the latest Google has to offer)

## Step 0: PRECONFIGURATIONS!
Install the latest Android Studio Preview: https://developer.android.com/studio/preview/index.html

Disable Instant Run: http://stackoverflow.com/a/35169716

Disable activity launch on theme:
  - Click on the above dropdown menu in Android Studio that says `app` (by default there should be an icon of andy with an x on it)
  - Click on `Edit configurations...`
  - Locate "Launch Options" and instead of Default Activity, select Nothing
  - This will now push your theme APK to your device without having to worry about build errors

## Step 1: Package Naming
The FIRST thing you need to change is the package identifier (the name the app identifies as) to something more meaningful to you. Open up [build.gradle](app/build.gradle) and look for this line
```
applicationId "substratum.theme.template"
```
Change this to anything you want, for instance:
```
applicationId "com.yourname.themename"
```

Change Package Name in the project structure (optional):
  - Just follow the instructions listed brilliantly here http://stackoverflow.com/a/29092698

NOTE: If you change your project structure name, the AndroidManifest AND the build.gradle package names must match, or else encrypted assets will break.

## Step 2: Theme Properties
You can control your theme properties such as whether your theme supports OMS, RRO or both inside
the theme configuration file: [theme_configurations.xml](app/src/main/res/values/theme_configurations.xml)

For wallpapers, make sure you use DIRECT LINKS for everything you see in the pastebin template. We recommend using pastebin,
but you could use Google Drive (for the XML file). Pictures must be located in a public area so that people can download them freely.

## Step 3: Start theming!
### Audio
To install system sound effects, you will need to have an audio folder, just like it's listed [here](app/src/main/assets/audio).

You are allowed to add multiple audio files and name them differently so they show up indivually on the spinner dropdown in the app.

Example:
```
assets/audio/StarWarsLockUnlock.zip
```
Audio ZIP root structure:
```
StarWarsLockUnlock.zip/ui/Lock.ogg(or mp3)
StarWarsLockUnlock.zip/ui/Unlock.ogg(or mp3)
StarWarsLockUnlock.zip/ui/effect_tick.ogg(or mp3)
StarWarsLockUnlock.zip/alarms/alarm.ogg(or mp3)
StarWarsLockUnlock.zip/ringtones/ringtone.ogg(or mp3)
StarWarsLockUnlock.zip/notifications/notification.ogg(or mp3)
```

### Boot Animations
To install boot animations, you will need to have a bootanimations folder, just like it's listed [here](app/src/main/assets/bootanimation).

You are allowed to add multiple bootanimations and name them differently so they show up individually on the spinner dropdown in the app.

Example:
```
assets/bootanimation/Sakura.zip
```

### Shutdown Animations
To install shutdown animations, you will need to have a shutdownanimation folder, just like it's listed [here](app/src/main/assets/shutdownanimation).

Just like bootanimations, but only enabled on Oreo based devices and above!

Example:
```
assets/shutdownanimation/Sakura.zip
```

### Fonts
To install fonts, you will need to have a fonts folder, just like it's listed [here](app/src/main/assets/fonts).

You are allowed to add multiple fonts and name them differently so they show up individually on the spinner dropdown in the app.

If you are looking to load up DOWNLOADED fonts from the internet, then download the ZIP from your source, extract it and navigate INTO the folder, until you find the folder "fonts" in "/system/fonts", and ZIP the whole contents of the folder up to form your new fonts pack.

This also supports fonts.xml within the font's ZIP file, so if you have any knowledge of this, you can add it in.

Example:
```
assets/fonts/Ubuntu.zip
```
Font ZIP root structure:
```
Ubuntu.zip/font1.ttf
Ubuntu.zip/font2.ttf
Ubuntu.zip/font3.ttf
```

### Overlays
If you had any experience with overlays on CMTE, it is rather the same format, except we added our own twists for enhanced theming capabilities for Substratum users.

If you would like to theme an application, first you need their package identifier. Let's say you wanted to theme Substratum (projekt.substratum), you will create a folder within "assets/overlays" and name it the package name and start following the app's resource structure, e.g.
```
assets/overlays/projekt.substratum/res/values/colors.xml
```

### Overlay Type Options Guide

https://docs.google.com/document/d/1H8tC1hjhADPOZdjebJEeC3FYZid9gZ7F56OA-27PxfU/edit?usp=sharing

## Step 4: Finalize your theme!
To get your theme to show up on Substratum, all you need to ensure that your hero image relates to your theme. The hero image DETERMINES the color of the automatic actionbar and nav bar colors based on the (0,0)'th pixel on your image. Your theme hero image is located [here](app/src/main/res/drawable-xxhdpi/heroimage.png).

If you have a completely white image, your actionbar and nav bar will change to that color, and the text colors will determine whether the black text is more visible on that color, or a white color.

## Step 5: Include a built in changelog for your users!

If you take a look at the aforementioned theme_configurations.xml, you will see a <string-array> with name "ThemeChangelog" where you can add your own changelog line by line. Please do not include line breaks unless you really have to. Substratum does this automagically! You can have as many lines as you want, so don't worry about the default 5 lines in the template!

## Step 6: Safeguard your theme! Don't let the pirates win!

### If you want to enable the Substratum theme for other Theme Managers (e.g. Slim)
In ThemerConstants.gradle, change the [SUPPORTS_THIRD_PARTY_SYSTEMS](app/ThemerConstants.gradle#L9) on line 9.

### If you don't want to activate AntiPiracy
Then you can stop reading and get your theme published! Good luck!

### Getting started with AntiPiracy

If you are ready to get AntiPiracy set up, all you need to look at is [ThemerConstants.gradle](app/ThemerConstants.gradle)!

Compile your theme as a SIGNED release APK from Android Studio (Build -> Generate Signed APK). Then launch the signed apk on your device and your log will spit out an error log under the name "SubstratumThemeReport", and you want to copy and paste that into [APK_SIGNATURE_PRODUCTION](app/ThemerConstants.gradle#L13) on line 13.

**NOTE**: If you are planning to make use of [Google Play App Signing](https://developer.android.com/studio/publish/app-signing.html#google-play-app-signing), **DO NOT** fill the `APK_SIGNATURE_PRODUCTION` field in [ThemerConstants.gradle](app/ThemerConstants.gradle).

Then you would need to go to Play Developer Console. Then access to your app -> Services and APIs, generate a new API key for your app and then paste it into [BASE_64_LICENSE_KEY](app/ThemerConstants.gradle#L12)  on line 12.

Third, if  you would like to change where it checks for various things such as Amazon App Store Enforcement or Play Store Enforcement, you have options listed on line 16 and lines below it, simply change from `true` to `false` and vice versa to make your desired configuration.

Finally, if you would like to enable intensive mode anti-piracy (App package blacklist), add as many package names as you want under [BLACKLISTED_APPLICATIONS](app/src/main/kotlin/substratum/theme/template/AdvancedConstants.kt#L21) line 21. Then make sure to enable [ENABLE_APP_BLACKLIST_CHECK](app/ThemerConstants.gradle#L16) on line 16.

**Under no circumstances should you share your ThemerConstants.gradle file, unless specifically asked by an [official substratum developer](https://github.com/substratum/documentation#team-info-and-responsibilities)**!

### Encrypted Assets
As of template version 11.0.0, all theme assets are duplicated are encrypted within the APK by default, not your original assets!

Always use a version control tool listed below to host your private themes!

BitBucket: https://bitbucket.org/
GitLab: https://about.gitlab.com/

If you want to keep your theme assets unencrypted, just change the value [here](app/ThemerConstants.gradle#L4) to false.

### Enforcing security
As of template version 11.0.0, themes have an additional check on the build of substratum your users should be running.

What this means is that themes can ensure their themes ONLY function with our full release cycle with debug and Play Store releases.

If you would like to enable this feature (only allow your theme to be used with official substratum builds), all you have to do is to flip `true` to `false` [here](app/ThemerConstants.gradle#L22)!

### Now what?
Nothing. Now you're set to publish your theme!

## Written with ❤ from themers and developers alike!


text:
@ECHO OFF
ECHO "Dotted files in hook dirs should not be called" > dotted_hook_should_not_fire.txt


text:
package armconnectedvmware_test

import (
	"context"
	"log"

	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/connectedvmware/armconnectedvmware"
)

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/connectedvmware/resource-manager/Microsoft.ConnectedVMwarevSphere/preview/2022-01-10-preview/examples/ListOperations.json
func ExampleOperationsClient_NewListPager() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armconnectedvmware.NewOperationsClient(cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	pager := client.NewListPager(nil)
	for pager.More() {
		nextResult, err := pager.NextPage(ctx)
		if err != nil {
			log.Fatalf("failed to advance page: %v", err)
		}
		for _, v := range nextResult.Value {
			// TODO: use page item
			_ = v
		}
	}
}


text:
import pandas as pd

import pickle

from rdkit import Chem
from rdkit.Chem import AllChem
import os.path as osp

import mastic.selection as masticsel
import mastic.molecule as masticmol
import mastic.system as masticsys
import mastic.interactions as masticinx
from mastic.interactions.hydrogen_bond import HydrogenBondType

from mastic.interfaces.rdkit import RDKitMoleculeWrapper

import mastic.config.interactions as masticinxconfig

import mastic.tests.data as masticdata

from rdkit import Chem

# without Hs straight from pdb
BEN_rdkit = Chem.MolFromPDBBlock(masticdata.BEN_3ptb, removeHs=False, sanitize=True)
trypsin_rdkit = Chem.MolFromPDBBlock(masticdata.trypsin_3ptb, removeHs=False, sanitize=True)

# with hydrogens added files
BEN_Hs_rdkit = Chem.MolFromPDBBlock(masticdata.BEN_Hs_3ptb, removeHs=False, sanitize=True)
trypsin_Hs_rdkit = Chem.MolFromPDBBlock(masticdata.trypsin_Hs_3ptb, removeHs=False, sanitize=True)

BEN_rdkit_wrapper = RDKitMoleculeWrapper(BEN_rdkit, mol_name="BEN")
trypsin_rdkit_wrapper = RDKitMoleculeWrapper(trypsin_rdkit, mol_name="Trypsin")

BEN_coords = BEN_rdkit_wrapper.get_conformer_coords(0)
trypsin_coords = trypsin_rdkit_wrapper.get_conformer_coords(0)
member_coords = [BEN_coords, trypsin_coords]

BEN_Molecule = masticdata.BEN_Molecule
Trypsin_Molecule = masticdata.Trypsin_Molecule

BEN_mol = BEN_Molecule.to_molecule(BEN_coords)
trypsin_mol = Trypsin_Molecule.to_molecule(trypsin_coords)

member_types = [BEN_Molecule, Trypsin_Molecule]
system_attrs = {'name' : 'trypsin-benzamidine-complex'}

Trypsin_Benzamidine_System = masticsys.SystemType("Trypsin_Benzamidine_System",
                                                member_types=member_types,
                                                **system_attrs)

print("making an AssociationType of the receptor and ligand in the Trypsin_Benzamidine_System")
rec_lig_attrs = {'name' : 'trypsin-benzamidine-complex'}
# rec_lig_attrs['ligand_type'] = ben_type
# rec_lig_attrs['receptor_type'] = trypsin_type
selection_map = {0 : None, 1 : None}
selection_types = [None, None]
Trypsin_Benzamidine_Association = \
            masticsys.AssociationType("Trypsin_Benzamidine_Association",
                                    system_type=Trypsin_Benzamidine_System,
                                    selection_map=selection_map,
                                    selection_types=selection_types,
                                    **rec_lig_attrs)

# add it to the SystemType
Trypsin_Benzamidine_System.add_association_type(Trypsin_Benzamidine_Association)

# now when we make the system the selections are put into an
# Association that can be profiled
trypsys = Trypsin_Benzamidine_System.to_system(member_coords)

# from mastic.molecule import Molecules
print("testing Hbond interaction between molecules in the receptor ligand association")
tryp_ben_assoc = trypsys.associations[0]

intermember_key_pairs, intermember_interactions = \
tryp_ben_assoc.profile_interactions([HydrogenBondType])

intramember_key_pairs, intramember_interactions = \
tryp_ben_assoc.profile_interactions([HydrogenBondType],
                                    intramember_interactions=True)

intermember_inx_class_df = pd.DataFrame([inx.interaction_class.record for
                                 inx in intermember_interactions[HydrogenBondType]])
intramember_inx_class_df = pd.DataFrame([inx.interaction_class.record for
                                 inx in intramember_interactions[HydrogenBondType]])

intermember_inx_df = pd.DataFrame([inx.record for inx in
                           intermember_interactions[HydrogenBondType]])
intramember_inx_df = pd.DataFrame([inx.record for inx in
                           intramember_interactions[HydrogenBondType]])


text:
require 'spec_helper'

describe 'Property' do
  with_connection do
    let :database do
      DataMapper.repository(:default).adapter.send(:database)
    end
    before :all do
      ENV['TZ'] = 'UTC'

      class ::User
        include DataMapper::Mongo::Resource

        property :id, ObjectId
        property :date_time_field, DateTime
        property :date_field, Date
        property :type, Discriminator
      end

      DataMapper.finalize
    end

    describe 'Class' do
      it 'should be typecasted to a string' do
        lambda{
          user = User.create!(:type => User)
        }.should_not raise_error
      end
    end

    describe 'DateTime' do
      it 'should be typecasted from a Time object' do
        dt_now = DateTime.now
        t_now  = Time.now

        _id = database.collection('users').insert(:type => 'User', :date_time_field => t_now)

        user = User.get(_id)

        user.date_time_field.class.should be(DateTime)

        Time.parse(user.date_time_field.to_s).to_i.should == Time.parse(dt_now.to_s).to_i
      end
    end

    describe 'Date' do
      it 'should be typecasted from a Time object' do
        today = Date.today

        _id = database.collection('users').insert(:type => 'User', :date_field => Time.parse(today.to_s))

        user = User.get(_id)

        user.date_field.class.should be(Date)
        Time.parse(user.date_field.to_s).should == Time.parse(today.to_s)
      end
    end
  end
end


text:
'use strict'

class Scene {
	constructor(canvas, options) {
		if (typeof canvas == 'string') {
			canvas = document.getElementById(canvas)
		}

		this.canvas = canvas
		this.ctx    = canvas.getContext('2d')
		this.layers = {}

		if (options && options.stretch) {
			this.canvas.width  = window.innerWidth
			this.canvas.height = window.innerHeight
		}
	}

	layer(name, fn) {
		this.layers[name] = fn.bind(this)
		return this
	}

	color(color) {
		this.ctx.fillStyle = color
		return this
	}

	border(color, width) {
		this.ctx.strokeStyle = color
		this.ctx.lineWidth = width
		return this
	}

	region(x, y, width, height) {
		this.ctx.fillRect(x, y, width, height)
		return this
	}

	dot(x, y) {
		this.ctx.fillRect(x, y, 1, 1)
		return this
	}

	circle(x, y, r) {
		this.ctx.beginPath()
		this.ctx.arc(x, y, r, 0, 2 * Math.PI)
		this.ctx.fill()
		this.ctx.stroke()
		return this
	}

	shape(points) {
		this.ctx.beginPath()
		this.ctx.moveTo(points[0][0], points[0][1])
		for (var i = 1; i < points.length; i++) {
			this.ctx.lineTo(points[i][0], points[i][1])
		}
		this.ctx.fill()
		this.ctx.stroke()
		return this
	}

	animation(fn, interval) {
		var state = {}
		var bound = fn.bind(this, state)
		window.setInterval(bound, interval)
	}
}


text:
package services

import (
	"github.com/vonji/vonji-api/models"
	"github.com/vonji/vonji-api/utils"
)

type CommentService struct {
	BaseService
}

func (service CommentService) GetAll() []models.Comment {
	if Error != nil {
		return nil
	}

	comments := []models.Comment{}

	if db:= service.GetDB().Find(&comments); db.Error != nil {
		Error = utils.DatabaseError(db)
		return nil
	}

	for i, comment := range comments {
		comments[i].User = *User.GetOne(comment.UserID)
	}

	return comments
}

func (service CommentService) GetOne(id uint) *models.Comment {
	if Error != nil {
		return nil
	}

	comment := models.Comment{}

	if db := service.GetDB().First(&comment, id); db.Error != nil {
		Error = utils.DatabaseError(db)
		return nil
	}

	comment.User = *User.GetOne(comment.UserID)

	return &comment
}

func (service CommentService) GetOneWhere(comment *models.Comment) *models.Comment {
	if Error != nil {
		return nil
	}

	if db := service.GetDB().Where(&comment).First(&comment); db.Error != nil {
		if !db.RecordNotFound() {
			Error = utils.DatabaseError(db)
		}
		return nil
	}

	comment.User = *User.GetOne(comment.UserID)

	return comment
}

func (service CommentService) GetAllWhere(comment *models.Comment) []models.Comment {
	if Error != nil {
		return nil
	}

	comments := []models.Comment{}

	if db := service.GetDB().Where(comment).Find(&comments); db.Error != nil {
		if !db.RecordNotFound() {
			Error = utils.DatabaseError(db)
		}
		return nil
	}

	for i := range comments {
		comments[i].User = *User.GetOne(comments[i].UserID)
	}

	return comments
}

func (service CommentService) Create(comment *models.Comment) *models.Comment {
	if Error != nil {
		return nil
	}

	if db := service.GetDB().Create(&comment); db.Error != nil {
		Error = utils.DatabaseError(db)
		return nil
	}

	return Comment.GetOne(comment.ID)
}

func (service CommentService) Update(comment *models.Comment) {
	if Error != nil {
		return
	}

	if db := service.GetDB().Save(&comment); db.Error != nil {
		Error = utils.DatabaseError(db)
	}
}

func (service CommentService) Delete(id uint) {
	if Error != nil {
		return
	}

	comment := models.Comment{}
	comment.ID = id

	if db := service.GetDB().Delete(&comment); db.Error != nil {
		Error = utils.DatabaseError(db)
		return
	}
}


text:
class StyleConstants
{
	static get navBar()
	{
		return {
			height: '7em',
			borderBottom: 'gray',
			borderBottomStyle: 'solid',
			borderBottomWidth: 'thin'
		};
	}

	static get searchIcon()
	{
		return {
			height: '1.5em',
			width: '1.5em'
		};
	}

	static get addPersonIcon()
	{
		return {
			width: '2em',
			height: '2em'
		};
	}
}

export default StyleConstants


text:
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>ember traceur compiled app</title>

		<script src="/lib/jquery/dist/jquery.js"></script>
		<script src="/lib/handlebars/handlebars.js"></script>
		<script src="/js/loader.js"></script>

		<script type="module" src="/js/app.js"></script>
		<script src="/lib/traceur/traceur.js"></script>
		<script src="/js/main.js"></script>
	</head>
	<body>
	</body>
</html>


text:
class ProblemsController < ApplicationController

  def show
    @language_problem = LanguageProblem.find_language_problem(params[:language_id], params[:id])
    @language = @language_problem.language
    @problem = @language_problem.problem
    @users_working = UserProgress.problem_users(@language, @problem, current_user, 1)
    @users_finished = UserProgress.problem_users(@language, @problem, current_user, 2)
    @posts = Kaminari.paginate_array(@language_problem.posts.reverse).page(params[:page]).per(4)
    @post = Post.new
    @rooms = @language_problem.rooms.limit(3)
  end

  def search
    @language = Language.find(params[:language_id])
    @problem = Problem.where("title LIKE ?", "%#{params[:query]}%").limit(1).first
    if @problem
      redirect_to language_problem_path(@language.slug, @problem.slug)
    else
      flash[:alert] = "Sorry, couldn't find anything - here's your current problem"
      redirect_to language_problem_path(@language.slug, current_user.current_problem(@language))
    end
  end

end


text:
namespace manifold {
namespace caffdram {

//! This is a simpler version of Controller. It doesn't have flow control and allows to be
//! connected directly to, say, a cache.
class ControllerSimple : public manifold::kernel::Component {
public:
    enum {PORT=0};

    ControllerSimple(int nid, const Dsettings&, bool st_resp=false);
    ~ControllerSimple();

    int get_nid() { return m_nid; }

    template<typename T>
    void handle_request(int, T*);

    void print_config(std::ostream&);
    void print_stats(std::ostream&);

#ifdef CAFFDRAM_TEST
public:
#else
private:
#endif
    unsigned long int processRequest (unsigned long int reqAddr, unsigned long int currentTime);

    //Called when a request is complete.
    template<typename T>
    void request_complete(T*);

    int m_nid; //node id
    const bool m_send_st_response; //send response for stores
    Dsettings* dramSetting;
    Channel** myChannel;

    std::list<uarch::NetworkPacket*> m_completed_reqs; //this is the output buffer holding completed requests.

    //stats
    unsigned stats_ld_misses;
    unsigned stats_stores;
    unsigned stats_max_output_buffer_size;

};

//! Event handler for memory requests.
template<typename T>
void ControllerSimple :: handle_request(int, T* req)
{
    if(req->is_read()) {
#ifdef DBG_CAFFDRAM
cout << "mc received LD, addr= " <<hex<< req->get_addr() <<dec<<endl;
#endif
	//stats
	stats_ld_misses++;

	manifold::kernel::Ticks_t latency = processRequest(req->get_addr(), manifold::kernel::Manifold::NowTicks()); //????????????? using default clock here.
	//The return value of processRequest() is the actual (or absolute) time of when the request
	//is completed, but Sendtick requires time relative to now. So we must pass to SendTick
	//the return value - now.

	//SendTick(OUT, pkt, latency - manifold::kernel::Manifold::NowTicks());
	manifold::kernel::Manifold::Schedule(latency - manifold::kernel::Manifold::NowTicks(), &ControllerSimple::request_complete<T>, this, req);
    }
    else { //write request
#ifdef DBG_CAFFDRAM
cout << "mc received ST, addr= " <<hex<< req->get_addr() <<dec<<endl;
#endif
	//stats
	stats_stores++;
	manifold::kernel::Ticks_t latency = processRequest(req->get_addr(), manifold::kernel::Manifold::NowTicks()); //????????????? using default clock here.
        if(m_send_st_response) {
	    manifold::kernel::Manifold::Schedule(latency - manifold::kernel::Manifold::NowTicks(), &ControllerSimple::request_complete<T>, this, req);
	}
	else
	    delete req;
    }
}

template<typename T>
void ControllerSimple :: request_complete(T* req)
{
    Send(PORT, req);
}

} //namespace caffdram
} //namespace manifold

#endif // MANIFOLD_CAFFDRAM_CONTROLLERSIMPLE_H


text:
package com.amazonaws.services.kafkaconnect.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * The target capacity for the connector. The capacity can be auto scaled or provisioned.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CapacityUpdate implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The target auto scaling setting.
     *

     */
    private AutoScalingUpdate autoScaling;
    /**
     *

     * The target settings for provisioned capacity.
     *

     */
    private ProvisionedCapacityUpdate provisionedCapacity;

    /**
     *

     * The target auto scaling setting.
     *

     *
     * @param autoScaling
     *        The target auto scaling setting.
     */

    public void setAutoScaling(AutoScalingUpdate autoScaling) {
        this.autoScaling = autoScaling;
    }

    /**
     *

     * The target auto scaling setting.
     *

     *
     * @return The target auto scaling setting.
     */

    public AutoScalingUpdate getAutoScaling() {
        return this.autoScaling;
    }

    /**
     *

     * The target auto scaling setting.
     *

     *
     * @param autoScaling
     *        The target auto scaling setting.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CapacityUpdate withAutoScaling(AutoScalingUpdate autoScaling) {
        setAutoScaling(autoScaling);
        return this;
    }

    /**
     *

     * The target settings for provisioned capacity.
     *

     *
     * @param provisionedCapacity
     *        The target settings for provisioned capacity.
     */

    public void setProvisionedCapacity(ProvisionedCapacityUpdate provisionedCapacity) {
        this.provisionedCapacity = provisionedCapacity;
    }

    /**
     *

     * The target settings for provisioned capacity.
     *

     *
     * @return The target settings for provisioned capacity.
     */

    public ProvisionedCapacityUpdate getProvisionedCapacity() {
        return this.provisionedCapacity;
    }

    /**
     *

     * The target settings for provisioned capacity.
     *

     *
     * @param provisionedCapacity
     *        The target settings for provisioned capacity.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CapacityUpdate withProvisionedCapacity(ProvisionedCapacityUpdate provisionedCapacity) {
        setProvisionedCapacity(provisionedCapacity);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getAutoScaling() != null)
            sb.append("AutoScaling: ").append(getAutoScaling()).append(",");
        if (getProvisionedCapacity() != null)
            sb.append("ProvisionedCapacity: ").append(getProvisionedCapacity());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof CapacityUpdate == false)
            return false;
        CapacityUpdate other = (CapacityUpdate) obj;
        if (other.getAutoScaling() == null ^ this.getAutoScaling() == null)
            return false;
        if (other.getAutoScaling() != null && other.getAutoScaling().equals(this.getAutoScaling()) == false)
            return false;
        if (other.getProvisionedCapacity() == null ^ this.getProvisionedCapacity() == null)
            return false;
        if (other.getProvisionedCapacity() != null && other.getProvisionedCapacity().equals(this.getProvisionedCapacity()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getAutoScaling() == null) ? 0 : getAutoScaling().hashCode());
        hashCode = prime * hashCode + ((getProvisionedCapacity() == null) ? 0 : getProvisionedCapacity().hashCode());
        return hashCode;
    }

    @Override
    public CapacityUpdate clone() {
        try {
            return (CapacityUpdate) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.kafkaconnect.model.transform.CapacityUpdateMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
#include <codex/diag/error.hpp>

namespace codex {

  const char* error_category_impl::name( void ) const noexcept {
    return "codex";
  }

  std::string error_category_impl::message( int ev ) const {
    static std::vector< std::string > map {
      std::string( "success" ) ,
      std::string( "fail" ) ,
      std::string( "invalid_argument" ) ,
    };
    if ( ev < static_cast<int>(map.size()) )
      return map[ev];
    return std::string("error");
  }

  std::error_condition error_category_impl::default_error_condition( int ev ) const noexcept {
    if ( ev == static_cast<int>(codex::errc::invalid_argument) )
      return std::make_error_condition( std::errc::invalid_argument );
    return std::error_condition( ev , *this );
  }

  bool error_category_impl::equivalent( const std::error_code& code , int cond ) const noexcept{
    if ( *this == code.category() && code.value() == cond ) {
      return true;
    }
    if ( code == std::errc::invalid_argument) {
      return cond == static_cast<int>(codex::errc::invalid_argument);
    }
    return false;
  }

  /*
  bool error_category_impl::equivalent( int code , const std::error_condition& cond ) const noexcept {
    if ( *this == cond.category() && cond.value() == code ) {
      return true;
    }
    if ( code == static_cast<int>(codex::errc::invalid_argument) ) {
      return cond == std::errc::invalid_argument;
    }
    return false;
  }
  */
  const std::error_category& category( void ) {
    static error_category_impl impl;
    return impl;
  }

  std::error_code make_error_code( codex::errc ec ) {
    return std::error_code( static_cast<int>(ec) , codex::category());
  }

  std::error_condition make_error_condition( codex::errc ec ){
    return std::error_condition( static_cast<int>(ec) , codex::category());
  }

  std::error_code last_error( void ) {
#if defined( __codex_win32__)
    return std::error_code( GetLastError() , std::system_category());
#else
    return std::error_code( errno , std::system_category());
#endif
  }

}

namespace std {

}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>

<screensaver name="ccurve" _label="CCurve">

  <command arg="-root"/>

  <number id="delay" type="slider" arg="-delay %"
          _label="Change image every" _low-label="0 seconds" _high-label="30 seconds"
          low="0" high="30" default="3"/>

  <number id="pause" type="slider" arg="-pause %"
          _label="Animation speed" _low-label="Slow" _high-label="Fast"
          low="0.0" high="5.0" default="0.4" convert="invert"/>

  <number id="limit" type="slider" arg="-limit %"
          _label="Density" _low-label="Low" _high-label="High"
          low="3" high="300000" default="200000"/>

  <boolean id="showfps" _label="Show frame rate" arg-set="-fps"/>

  <xscreensaver-updater />

  <_description>
Generates self-similar linear fractals, including the classic "C Curve".

http://en.wikipedia.org/wiki/Levy_C_curve

Written by Rick Campbell; 1999.
  </_description>
</screensaver>


text:
<?php
namespace HtSettingsModuleDoctrineORM\Mapper;

use HtSettingsModule\Mapper\SettingsMapper as BaseSettingsMapper;
use Doctrine\ORM\EntityManager;
use HtSettingsModule\Options\DbOptionsInterface;
use HtSettingsModule\Entity\ParameterInterface;
use HtSettingsModule\Exception;

class SettingsMapper extends BaseSettingsMapper
{
    /**
     * @var EntityManager
     */
    protected $em;

    /**
     * Constructor
     *
     * @param EntityManager            $em
     * @param DbOptionsInterface $options
     *
     * @return void
     */
    public function __construct(EntityManager $em, DbOptionsInterface $options)
    {
        $this->em       = $em;
        $this->options  = $options;
    }

    /**
     * {@inheritDoc}
     */
    public function findByNamespace($namespace)
    {
        return $this->getRepository()->findBy(array('namespace' => $namespace));
    }

    /**
     * {@inheritDoc}
     */
    public function insertParameter(ParameterInterface $parameter)
    {
        $this->saveParameter($parameter);
    }

    /**
     * {@inheritDoc}
     */
    public function updateParameter(ParameterInterface $parameter)
    {
        if ($parameter->getId()) {
            $this->saveParameter($parameter);
        } else {
            $qb = $this->em->createQueryBuilder('s');
            $qb->update()->set('value = :value')
                ->where('s.namespace = :namespace AND s.name = :name')
                ->setParameter('namespace', $parameter->getNamespace())
                ->setParameter('name', $parameter->getName())
                ->setParameter('value', $parameter->getValue());
            return $qb->getQuery()->execute();
        }
    }

    /**
     * Saves a parameter
     *
     * @param ParameterInterface $parameter
     * @return void
     */
    public function saveParameter(ParameterInterface $parameter)
    {
        $this->em->persist($parameter);
        $this->em->flush();
    }

    /**
     * {@inheritDoc}
     */
    public function deleteParameter(ParameterInterface $parameter)
    {
        if ($parameter->getId()) {
            $this->em->remove($parameter);
            $this->em->flush();
        } else {
            $qb = $this->em->createQueryBuilder('s');
            $qb->delete()->where('s.namespace = :namespace AND s.name = :name')
                ->setParameter('namespace', $parameter->getNamespace())
                ->setParameter('name', $parameter->getName());
            return $qb->getQuery()->execute();
        }
    }

    /**
     * {@inheritDoc}
     */
    public function findParameter($parameter, $name = null)
    {
        if ($parameter instanceof ParameterInterface) {
            $namespace = $parameter->getNamespace();
            $name = $parameter->getName();
        } elseif (is_string($parameter)) {
            $namespace = $parameter;
        } else {
            throw new Exception\InvalidArgumentException(
                sprintf(
                    '%s expects parameter 1 to be string or an instance of HtSettingsModule\Entity\ParameterInterface, %s provided instead',
                    __METHOD__,
                    is_object($parameter) ? get_class($parameter) : gettype($parameter)
                )
            );
        }
        $qb = $this->em->createQueryBuilder('s');
        $qb->select()->where('s.namespace = :namespace AND s.name = :name')
            ->setParameter('namespace', $namespace)
            ->setParameter('name', $name);

        return $qb->getQuery()->getSingleOrNullResult();
    }

    protected function getRepository()
    {
        return $this->em->getRepository($this->options->getParameterEntityClass());
    }
}