text:
package com.serphacker.serposcope.db.google;

import com.google.inject.Singleton;
import com.querydsl.core.Tuple;
import com.querydsl.sql.SQLQuery;
import com.querydsl.sql.dml.SQLDeleteClause;
import com.querydsl.sql.dml.SQLMergeClause;
import com.serphacker.serposcope.db.AbstractDB;
import com.serphacker.serposcope.models.google.GoogleTargetSummary;
import com.serphacker.serposcope.querybuilder.QGoogleRank;
import com.serphacker.serposcope.querybuilder.QGoogleTargetSummary;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Singleton
public class GoogleTargetSummaryDB extends AbstractDB {

    QGoogleTargetSummary t_summary = QGoogleTargetSummary.googleTargetSummary;
    QGoogleRank t_rank = QGoogleRank.googleRank;

    public int insert(Collection<GoogleTargetSummary> summaries){
        int inserted = 0;

        try(Connection con = ds.getConnection()){

            for (GoogleTargetSummary target : summaries) {
                inserted += new SQLMergeClause(con, dbTplConf, t_summary)
                    .set(t_summary.groupId, target.getGroupId())
                    .set(t_summary.googleTargetId, target.getTargetId())
                    .set(t_summary.runId, target.getRunId())

                    .set(t_summary.totalTop3, target.getTotalTop3())
                    .set(t_summary.totalTop10, target.getTotalTop10())
                    .set(t_summary.totalTop100, target.getTotalTop100())
                    .set(t_summary.totalOut, target.getTotalOut())

                    .set(t_summary.topRanks, target.getTopRanksSerialized())
                    .set(t_summary.topImprovements, target.getTopImprovementsSerialized())
                    .set(t_summary.topLosts, target.getTopLostsSerialized())

                    .set(t_summary.scoreRaw, target.getScoreRaw())
                    .set(t_summary.scoreBasisPoint, target.getScoreBP())
                    .set(t_summary.previousScoreBasisPoint, target.getPreviousScoreBP())

                    .execute();
            }

        } catch(Exception ex){
            LOG.error("SQL error", ex);
        }

        return inserted;
    }

    public boolean deleteByTarget(int targetId){
        boolean deleted = false;
        try(Connection con = ds.getConnection()){
            deleted = new SQLDeleteClause(con, dbTplConf, t_summary)
                .where(t_summary.googleTargetId.eq(targetId))
                .execute() == 1;
        }catch(Exception ex){
            LOG.error("SQLError", ex);
        }
        return deleted;
    }

    public boolean deleteByRun(int runId){
        boolean deleted = false;
        try(Connection con = ds.getConnection()){
            deleted = new SQLDeleteClause(con, dbTplConf, t_summary)
                .where(t_summary.runId.eq(runId))
                .execute() == 1;
        }catch(Exception ex){
            LOG.error("SQLError", ex);
        }
        return deleted;
    }

    public void wipe(){
        try(Connection con = ds.getConnection()){
            new SQLDeleteClause(con, dbTplConf, t_summary).execute();
        }catch(Exception ex){
            LOG.error("SQLError", ex);
        }
    }

    public Map<Integer,Integer> getPreviousScore(int runId){
        Map<Integer,Integer> scores = new HashMap<>();

        try(Connection con = ds.getConnection()){
            List<Tuple> records = new SQLQuery<Void>(con, dbTplConf)
                .select(t_summary.googleTargetId, t_summary.scoreBasisPoint)
                .from(t_summary)
                .where(t_summary.runId.eq(runId))
                .fetch();

            for (Tuple record : records) {
                scores.put(record.get(t_summary.googleTargetId), record.get(t_summary.scoreBasisPoint));
            }

        }catch(Exception ex){
            LOG.error("SQLError", ex);
        }

        return scores;
    }

    public List<Integer> listScoreHistory(int groupId, int targetId, int history){
        List<Integer> scores = new ArrayList<>();

        try(Connection con = ds.getConnection()){
            scores = new SQLQuery<Void>(con, dbTplConf)
                .select(t_summary.scoreBasisPoint)
                .from(t_summary)
                .where(t_summary.groupId.eq(groupId))
                .where(t_summary.googleTargetId.eq(targetId))
                .orderBy(t_summary.runId.desc())
                .limit(history)
                .fetch();

        }catch(Exception ex){
            LOG.error("SQLError", ex);
        }

        if(scores != null){
            Collections.reverse(scores);
        } else {
            scores = new ArrayList<>();
        }

        return scores;
    }

    public List<GoogleTargetSummary> list(int runId){
        return list(runId, false);
    }

    public List<GoogleTargetSummary> list(int runId, boolean skipTop){
        List<GoogleTargetSummary> summaries = new ArrayList<>();
        try(Connection con = ds.getConnection()){

            List<Tuple> summaryTuples = new SQLQuery<Void>(con, dbTplConf)
                .select(t_summary.all())
                .from(t_summary)
                .where(t_summary.runId.eq(runId))
                .fetch();

            for (Tuple tuple : summaryTuples) {

                GoogleTargetSummary summary = new GoogleTargetSummary(
                    tuple.get(t_summary.groupId),
                    tuple.get(t_summary.googleTargetId),
                    runId,
                    tuple.get(t_summary.previousScoreBasisPoint)
                );

                summary.setTotalTop3(tuple.get(t_summary.totalTop3));
                summary.setTotalTop10(tuple.get(t_summary.totalTop10));
                summary.setTotalTop100(tuple.get(t_summary.totalTop100));
                summary.setTotalOut(tuple.get(t_summary.totalOut));

                summary.setScoreRaw(tuple.get(t_summary.scoreRaw));
                summary.setScoreBP(tuple.get(t_summary.scoreBasisPoint));

                if(!skipTop){
                    List<Integer> topRanksIds = unserializeIds(tuple.get(t_summary.topRanks));
                    List<Integer> topImprovementsIds = unserializeIds(tuple.get(t_summary.topImprovements));
                    List<Integer> topLostsIds = unserializeIds(tuple.get(t_summary.topLosts));

                    Set<Integer> searchIds = new HashSet<>();
                    searchIds.addAll(topRanksIds);
                    searchIds.addAll(topImprovementsIds);
                    searchIds.addAll(topLostsIds);

                    List<Tuple> rankTuples = new SQLQuery<Void>(con, dbTplConf)
                        .select(t_rank.all())
                        .from(t_rank)
                        .where(t_rank.runId.eq(runId))
                        .where(t_rank.groupId.eq(summary.getGroupId()))
                        .where(t_rank.googleTargetId.eq(summary.getTargetId()))
                        .where(t_rank.googleSearchId.in(searchIds))
                        .fetch();

                    for (Tuple rankTuple : rankTuples) {
                        summary.addRankToTop(GoogleRankDB.fromTuple(rankTuple));
                    }
                }

                summaries.add(summary);
            }

        } catch(Exception ex){
            LOG.error("SQLError", ex);
        }
        return summaries;
    }

    protected List<Integer> unserializeIds(String str){
        if(str == null || str.isEmpty()){
            return Collections.EMPTY_LIST;
        }

        List<Integer> ids = new ArrayList<>();

        String[] splits = str.split(",");
        for (String split : splits) {
            if(split.length() > 0){
                try {ids.add(Integer.parseInt(split));}catch(NumberFormatException ex){}
            }
        }

        return ids;
    }

    /*
    public List<GoogleTarget> list(Collection<Integer> groups){
        List<GoogleTarget> targets = new ArrayList<>();

        try(Connection con = ds.getConnection()){

            SQLQuery<Tuple> query = new SQLQuery<Void>(con, dbTplConf)
                .select(t_target.all())
                .from(t_target);

            if(groups != null){
                query.where(t_target.groupId.in(groups));
            }

            List<Tuple> tuples = query.fetch();

            if(tuples != null){
                for (Tuple tuple : tuples) {
                    targets.add(fromTuple(tuple));
                }
            }

        } catch(Exception ex){
            LOG.error("SQL error", ex);
        }

        return targets;
    }

    public GoogleTarget get(int targetId){
        GoogleTarget target = null;

        try(Connection con = ds.getConnection()){

            Tuple tuple = new SQLQuery<Void>(con, dbTplConf)
                .select(t_target.all())
                .from(t_target)
                .where(t_target.id.eq(targetId))
                .fetchOne();

            target = fromTuple(tuple);

        } catch(Exception ex){
            LOG.error("SQL error", ex);
        }

        return target;
    }

    GoogleTarget fromTuple(Tuple tuple) throws Exception{
        return new GoogleTarget(
            tuple.get(t_target.id),
            tuple.get(t_target.groupId),
            tuple.get(t_target.name),
            tuple.get(t_target.patternType) == null ? PatternType.REGEX : GoogleTarget.PatternType.values()[tuple.get(t_target.patternType)],
            tuple.get(t_target.pattern)
        );
    }
    */
}


text:
<Record>
<Term>Juvenile Xanthogranuloma</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<ParentTerm>Skin Diseases</ParentTerm>
<ParentTerm>Histiocytosis, Non-Langerhans-Cell</ParentTerm>
<ParentTerm>Xanthogranuloma</ParentTerm>
<ClassificationPath>Hemic and Lymphatic Diseases/Lymphatic Diseases/Histiocytosis/Histiocytosis, Non-Langerhans-Cell/Xanthogranuloma, Juvenile</ClassificationPath>
<ClassificationPath>Findings_and_Disorders_Kind/Disease, Disorder or Finding/Disease or Disorder/Disorder by Site/Connective and Soft Tissue Disorder/Soft Tissue Disorder/Non-Neoplastic Soft Tissue Disorder/Xanthogranuloma/Juvenile Xanthogranuloma</ClassificationPath>
<ClassificationPath>Skin and Connective Tissue Diseases/Skin Diseases/Xanthogranuloma, Juvenile</ClassificationPath>
<BroaderTerm>Xanthogranuloma, Juvenile</BroaderTerm>
<BroaderTerm>Hemic and Lymphatic Diseases</BroaderTerm>
<BroaderTerm>Skin Diseases</BroaderTerm>
<BroaderTerm>Disorder by Site</BroaderTerm>
<BroaderTerm>Juvenile Xanthogranuloma</BroaderTerm>
<BroaderTerm>Non-Neoplastic Soft Tissue Disorder</BroaderTerm>
<BroaderTerm>Findings_and_Disorders_Kind</BroaderTerm>
<BroaderTerm>Disease, Disorder or Finding</BroaderTerm>
<BroaderTerm>Disease or Disorder</BroaderTerm>
<BroaderTerm>Lymphatic Diseases</BroaderTerm>
<BroaderTerm>Histiocytosis, Non-Langerhans-Cell</BroaderTerm>
<BroaderTerm>Connective and Soft Tissue Disorder</BroaderTerm>
<BroaderTerm>Histiocytosis</BroaderTerm>
<BroaderTerm>Skin and Connective Tissue Diseases</BroaderTerm>
<BroaderTerm>Soft Tissue Disorder</BroaderTerm>
<BroaderTerm>Xanthogranuloma</BroaderTerm>
<Synonym>Nevoxanthoendotheliomas</Synonym>
<Synonym>Juvenile Xanthogranulomas</Synonym>
<Synonym>Juvenile Xanthoma</Synonym>
<Synonym>Nevoxanthoendothelioma</Synonym>
<Synonym>Juvenile Xanthogranuloma</Synonym>
<Synonym>Juvenile Xanthomas</Synonym>
<Description>Benign disorder of infants and children caused by proliferation of HISTIOCYTES, macrophages found in tissues. These histiocytes, usually lipid-laden non-Langerhans cells, form multiple yellow-red nodules most often in the skin, the eye, and sometimes in the viscera. Patients appear to have normal lipid metabolism and are classified as a normolipemic non-Langerhans cell histiocytosis.</Description>
<Description>A benign fibrohistiocytic lesion that occurs during childhood; it is distinct from Langerhans cell histiocytosis.  The lesions usually develop during infancy, and are characterized by regressing cutaneous nodules (most often in the head and neck) sometimes associated with deep soft tissues nodules.  The prognosis is excellent. -- 2003</Description>
<Source>NCI Thesaurus</Source>
<Source>MeSH</Source>
</Record>

redpajama_set_name: RedPajamaGithub


text:
package com.javaasc.shell;

import com.javaasc.entity.api.JascValues;

import java.util.LinkedList;
import java.util.List;

public class ValuesStub implements JascValues {
    @Override
    public List<String> getValues() {
        LinkedList<String> values = new LinkedList<>();
        values.add("value1111");
        values.add("value1122");
        return values;
    }
}


text:
<?php

/* You can edit some stuff starting here */

// Change this value to define whether this is a production server; this will affect error reporting
define('PRODSERV', false);

// Directory definitions
define('ROOT_DIR', getcwd() . '/');
define('LIB_DIR', ROOT_DIR . 'lib/');
define('MODEL_DIR', ROOT_DIR . 'models/');
define('THEME_DIR', ROOT_DIR . 'themes/');

/* Stop editing here */

include(ROOT_DIR . 'vendor/autoload.php');

// Set error level
if(PRODSERV)
        error_reporting(0);
else
        error_reporting(E_ALL);

// Include database settings
include('cms-settings.php');

// Make sure we can autoload files
function yap_autoloader($class) {
        $directories = array(LIB_DIR, MODEL_DIR);

        foreach($directories as $directory) {
                if(!@include("$directory/$class.php"))
                        @include($directory.strtolower($class).".php");
        }
}

spl_autoload_register('yap_autoloader');

$dbtype = DB_TYPE;
$database = new $dbtype;
if(strlen(DB_HOST) && strlen(DB_USER) && strlen(DB_PASS) && strlen(DB_NAME))
        $database->initialize(DB_HOST, DB_USER, DB_PASS, DB_NAME);


text:
package org.lwjgl.vulkan;

import javax.annotation.*;

import java.nio.*;

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

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

/**
 * Structure specifying image format properties.
 *
 *
Description

 *
 *
The bits reported in {@code linearTilingFeatures}, {@code optimalTilingFeatures} and {@code bufferFeatures} must include the bits reported in the corresponding fields of {@link VkFormatProperties2}{@code ::formatProperties}.

 *
 *
Valid Usage (Implicit)

 *
 *

 *
{@code sType} must be {@link VK13#VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3 STRUCTURE_TYPE_FORMAT_PROPERTIES_3}

 *

 *
 *
Layout

 *
 *

 * struct VkFormatProperties3 {
 *     VkStructureType sType;
 *     void * pNext;
 *     VkFormatFeatureFlags2 {@link #linearTilingFeatures};
 *     VkFormatFeatureFlags2 {@link #optimalTilingFeatures};
 *     VkFormatFeatureFlags2 {@link #bufferFeatures};
 * }

 */
public class VkFormatProperties3 extends Struct implements NativeResource {

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

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

    /** The struct member offsets. */
    public static final int
        STYPE,
        PNEXT,
        LINEARTILINGFEATURES,
        OPTIMALTILINGFEATURES,
        BUFFERFEATURES;

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

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

        STYPE = layout.offsetof(0);
        PNEXT = layout.offsetof(1);
        LINEARTILINGFEATURES = layout.offsetof(2);
        OPTIMALTILINGFEATURES = layout.offsetof(3);
        BUFFERFEATURES = layout.offsetof(4);
    }

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

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

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

    /** @return the value of the {@code sType} field. */
    @NativeType("VkStructureType")
    public int sType() { return nsType(address()); }
    /** @return the value of the {@code pNext} field. */
    @NativeType("void *")
    public long pNext() { return npNext(address()); }
    /** a bitmask of {@code VkFormatFeatureFlagBits2} specifying features supported by images created with a {@code tiling} parameter of {@link VK10#VK_IMAGE_TILING_LINEAR IMAGE_TILING_LINEAR}. */
    @NativeType("VkFormatFeatureFlags2")
    public long linearTilingFeatures() { return nlinearTilingFeatures(address()); }
    /** a bitmask of {@code VkFormatFeatureFlagBits2} specifying features supported by images created with a {@code tiling} parameter of {@link VK10#VK_IMAGE_TILING_OPTIMAL IMAGE_TILING_OPTIMAL}. */
    @NativeType("VkFormatFeatureFlags2")
    public long optimalTilingFeatures() { return noptimalTilingFeatures(address()); }
    /** a bitmask of {@code VkFormatFeatureFlagBits2} specifying features supported by buffers. */
    @NativeType("VkFormatFeatureFlags2")
    public long bufferFeatures() { return nbufferFeatures(address()); }

    /** Sets the specified value to the {@code sType} field. */
    public VkFormatProperties3 sType(@NativeType("VkStructureType") int value) { nsType(address(), value); return this; }
    /** Sets the {@link VK13#VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3 STRUCTURE_TYPE_FORMAT_PROPERTIES_3} value to the {@code sType} field. */
    public VkFormatProperties3 sType$Default() { return sType(VK13.VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3); }
    /** Sets the specified value to the {@code pNext} field. */
    public VkFormatProperties3 pNext(@NativeType("void *") long value) { npNext(address(), value); return this; }

    /** Initializes this struct with the specified values. */
    public VkFormatProperties3 set(
        int sType,
        long pNext
    ) {
        sType(sType);
        pNext(pNext);

        return this;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    /** Unsafe version of {@link #sType}. */
    public static int nsType(long struct) { return UNSAFE.getInt(null, struct + VkFormatProperties3.STYPE); }
    /** Unsafe version of {@link #pNext}. */
    public static long npNext(long struct) { return memGetAddress(struct + VkFormatProperties3.PNEXT); }
    /** Unsafe version of {@link #linearTilingFeatures}. */
    public static long nlinearTilingFeatures(long struct) { return UNSAFE.getLong(null, struct + VkFormatProperties3.LINEARTILINGFEATURES); }
    /** Unsafe version of {@link #optimalTilingFeatures}. */
    public static long noptimalTilingFeatures(long struct) { return UNSAFE.getLong(null, struct + VkFormatProperties3.OPTIMALTILINGFEATURES); }
    /** Unsafe version of {@link #bufferFeatures}. */
    public static long nbufferFeatures(long struct) { return UNSAFE.getLong(null, struct + VkFormatProperties3.BUFFERFEATURES); }

    /** Unsafe version of {@link #sType(int) sType}. */
    public static void nsType(long struct, int value) { UNSAFE.putInt(null, struct + VkFormatProperties3.STYPE, value); }
    /** Unsafe version of {@link #pNext(long) pNext}. */
    public static void npNext(long struct, long value) { memPutAddress(struct + VkFormatProperties3.PNEXT, value); }

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

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

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

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

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

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

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

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

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

        /** @return the value of the {@code sType} field. */
        @NativeType("VkStructureType")
        public int sType() { return VkFormatProperties3.nsType(address()); }
        /** @return the value of the {@code pNext} field. */
        @NativeType("void *")
        public long pNext() { return VkFormatProperties3.npNext(address()); }
        /** @return the value of the {@link VkFormatProperties3#linearTilingFeatures} field. */
        @NativeType("VkFormatFeatureFlags2")
        public long linearTilingFeatures() { return VkFormatProperties3.nlinearTilingFeatures(address()); }
        /** @return the value of the {@link VkFormatProperties3#optimalTilingFeatures} field. */
        @NativeType("VkFormatFeatureFlags2")
        public long optimalTilingFeatures() { return VkFormatProperties3.noptimalTilingFeatures(address()); }
        /** @return the value of the {@link VkFormatProperties3#bufferFeatures} field. */
        @NativeType("VkFormatFeatureFlags2")
        public long bufferFeatures() { return VkFormatProperties3.nbufferFeatures(address()); }

        /** Sets the specified value to the {@code sType} field. */
        public VkFormatProperties3.Buffer sType(@NativeType("VkStructureType") int value) { VkFormatProperties3.nsType(address(), value); return this; }
        /** Sets the {@link VK13#VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3 STRUCTURE_TYPE_FORMAT_PROPERTIES_3} value to the {@code sType} field. */
        public VkFormatProperties3.Buffer sType$Default() { return sType(VK13.VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3); }
        /** Sets the specified value to the {@code pNext} field. */
        public VkFormatProperties3.Buffer pNext(@NativeType("void *") long value) { VkFormatProperties3.npNext(address(), value); return this; }

    }

}


text:
import {
    ClientInitOptions,
    mapFeaturesForClient,
    mapSegmentsForClient,
    offlineUnleashClient,
} from './offline-unleash-client';
import {
    Unleash as UnleashClientNode,
    InMemStorageProvider as InMemStorageProviderNode,
} from 'unleash-client';
import { once } from 'events';
import { playgroundStrategyEvaluation } from '../openapi/spec/playground-strategy-schema';

export const offlineUnleashClientNode = async ({
    features,
    context,
    logError,
    segments,
}: ClientInitOptions): Promise<UnleashClientNode> => {
    const client = new UnleashClientNode({
        ...context,
        appName: context.appName,
        disableMetrics: true,
        refreshInterval: 0,
        url: 'not-needed',
        storageProvider: new InMemStorageProviderNode(),
        bootstrap: {
            data: mapFeaturesForClient(features),
            segments: mapSegmentsForClient(segments),
        },
    });

    client.on('error', logError);
    client.start();

    await once(client, 'ready');

    return client;
};

describe('offline client', () => {
    it('considers enabled variants with a default strategy to be on', async () => {
        const name = 'toggle-name';
        const client = await offlineUnleashClient({
            features: [
                {
                    name,
                    project: 'default',
                    enabled: true,
                    strategies: [{ name: 'default' }],
                    variants: [],
                    type: '',
                    stale: false,
                },
            ],
            context: { appName: 'other-app', environment: 'default' },
            logError: console.log,
        });

        expect(client.isEnabled(name).result).toBeTruthy();
    });

    it('constrains on appName', async () => {
        const enabledFeature = 'toggle-name';
        const disabledFeature = 'other-toggle';
        const appName = 'app-name';
        const client = await offlineUnleashClient({
            features: [
                {
                    name: enabledFeature,
                    enabled: true,
                    project: 'default',
                    strategies: [
                        {
                            name: 'default',
                            constraints: [
                                {
                                    contextName: 'appName',
                                    operator: 'IN',
                                    values: [appName],
                                },
                            ],
                        },
                    ],
                    variants: [],
                    type: '',
                    stale: false,
                },
                {
                    name: disabledFeature,
                    enabled: true,
                    project: 'default',
                    strategies: [
                        {
                            name: 'default',
                            constraints: [
                                {
                                    contextName: 'appName',
                                    operator: 'IN',
                                    values: ['otherApp'],
                                },
                            ],
                        },
                    ],
                    variants: [],
                    type: '',
                    stale: false,
                },
            ],
            context: { appName, environment: 'default' },
            logError: console.log,
        });

        expect(client.isEnabled(enabledFeature).result).toBeTruthy();
        expect(client.isEnabled(disabledFeature).result).toBeFalsy();
    });

    it('considers disabled features with a default strategy to be enabled', async () => {
        const name = 'toggle-name';
        const context = { appName: 'client-test' };
        const client = await offlineUnleashClient({
            features: [
                {
                    strategies: [
                        {
                            name: 'default',
                        },
                    ],
                    project: 'default',
                    stale: false,
                    enabled: false,
                    name,
                    type: 'experiment',
                    variants: [],
                },
            ],
            context,
            logError: console.log,
        });

        const result = client.isEnabled(name, context);

        expect(result.result).toBe(true);
    });

    it('considers disabled variants with a default strategy and variants to be on', async () => {
        const name = 'toggle-name';
        const client = await offlineUnleashClient({
            features: [
                {
                    strategies: [
                        {
                            name: 'default',
                        },
                    ],
                    project: 'default',
                    stale: false,
                    enabled: false,
                    name,
                    type: 'experiment',
                    variants: [
                        {
                            name: 'a',
                            weight: 500,
                            weightType: 'variable',
                            stickiness: 'default',
                            overrides: [],
                        },
                        {
                            name: 'b',
                            weight: 500,
                            weightType: 'variable',
                            stickiness: 'default',
                            overrides: [],
                        },
                    ],
                },
            ],
            context: { appName: 'client-test' },
            logError: console.log,
        });

        expect(client.isEnabled(name).result).toBe(true);
    });

    it("returns variant {name: 'disabled', enabled: false } if the toggle isn't enabled", async () => {
        const name = 'toggle-name';
        const client = await offlineUnleashClient({
            features: [
                {
                    strategies: [],
                    stale: false,
                    enabled: false,
                    name,
                    project: 'default',
                    type: 'experiment',
                    variants: [
                        {
                            name: 'a',
                            weight: 500,
                            weightType: 'variable',
                            stickiness: 'default',
                            overrides: [],
                        },
                        {
                            name: 'b',
                            weight: 500,
                            weightType: 'variable',
                            stickiness: 'default',
                            overrides: [],
                        },
                    ],
                },
            ],
            context: { appName: 'client-test' },
            logError: console.log,
        });

        expect(client.isEnabled(name).result).toBeFalsy();
        expect(client.getVariant(name).name).toEqual('disabled');
        expect(client.getVariant(name).enabled).toBeFalsy();
    });

    it('returns the disabled variant if there are no variants', async () => {
        const name = 'toggle-name';
        const client = await offlineUnleashClient({
            features: [
                {
                    strategies: [
                        {
                            name: 'default',
                            constraints: [],
                        },
                    ],
                    project: 'default',
                    stale: false,
                    enabled: true,
                    name,
                    type: 'experiment',
                    variants: [],
                },
            ],
            context: { appName: 'client-test' },
            logError: console.log,
        });

        expect(client.getVariant(name, {}).name).toEqual('disabled');
        expect(client.getVariant(name, {}).enabled).toBeFalsy();
        expect(client.isEnabled(name, {}).result).toBeTruthy();
    });

    it(`returns '${playgroundStrategyEvaluation.unknownResult}' if it can't evaluate a feature`, async () => {
        const name = 'toggle-name';
        const context = { appName: 'client-test' };

        const client = await offlineUnleashClient({
            features: [
                {
                    strategies: [
                        {
                            name: 'unimplemented-custom-strategy',
                            constraints: [],
                        },
                    ],
                    project: 'default',
                    stale: false,
                    enabled: true,
                    name,
                    type: 'experiment',
                    variants: [],
                },
            ],
            context,
            logError: console.log,
        });

        const result = client.isEnabled(name, context);

        result.strategies.forEach((strategy) =>
            expect(strategy.result.enabled).toEqual(
                playgroundStrategyEvaluation.unknownResult,
            ),
        );
        expect(result.result).toEqual(
            playgroundStrategyEvaluation.unknownResult,
        );
    });

    it(`returns '${playgroundStrategyEvaluation.unknownResult}' for the application hostname strategy`, async () => {
        const name = 'toggle-name';
        const context = { appName: 'client-test' };

        const client = await offlineUnleashClient({
            features: [
                {
                    strategies: [
                        {
                            name: 'applicationHostname',
                            constraints: [],
                        },
                    ],
                    project: 'default',
                    stale: false,
                    enabled: true,
                    name,
                    type: 'experiment',
                    variants: [],
                },
            ],
            context,
            logError: console.log,
        });

        const result = client.isEnabled(name, context);

        result.strategies.forEach((strategy) =>
            expect(strategy.result.enabled).toEqual(
                playgroundStrategyEvaluation.unknownResult,
            ),
        );
        expect(result.result).toEqual(
            playgroundStrategyEvaluation.unknownResult,
        );
    });

    it('returns strategies in the order they are provided', async () => {
        const featureName = 'featureName';
        const strategies = [
            {
                name: 'default',
                constraints: [],
                parameters: {},
            },
            {
                name: 'default',
                constraints: [
                    {
                        values: ['my-app-name'],
                        inverted: false,
                        operator: 'IN' as 'IN',
                        contextName: 'appName',
                        caseInsensitive: false,
                    },
                ],
                parameters: {},
            },
            {
                name: 'applicationHostname',
                constraints: [],
                parameters: {
                    hostNames: 'myhostname.com',
                },
            },
            {
                name: 'flexibleRollout',
                constraints: [],
                parameters: {
                    groupId: 'killer',
                    rollout: '34',
                    stickiness: 'userId',
                },
            },
            {
                name: 'userWithId',
                constraints: [],
                parameters: {
                    userIds: 'uoea,ueoa',
                },
            },
            {
                name: 'remoteAddress',
                constraints: [],
                parameters: {
                    IPs: '196.6.6.05',
                },
            },
        ];

        const context = { appName: 'client-test' };

        const client = await offlineUnleashClient({
            features: [
                {
                    strategies,
                    // impressionData: false,
                    enabled: true,
                    name: featureName,
                    project: 'default',
                    // description: '',
                    // project: 'heartman-for-test',
                    stale: false,
                    type: 'kill-switch',
                    variants: [
                        {
                            name: 'a',
                            weight: 334,
                            weightType: 'variable',
                            stickiness: 'default',
                            overrides: [],
                            payload: {
                                type: 'json',
                                value: '{"hello": "world"}',
                            },
                        },
                        {
                            name: 'b',
                            weight: 333,
                            weightType: 'variable',
                            stickiness: 'default',
                            overrides: [],
                            payload: {
                                type: 'string',
                                value: 'ueoau',
                            },
                        },
                        {
                            name: 'c',
                            weight: 333,
                            weightType: 'variable',
                            stickiness: 'default',
                            payload: {
                                type: 'csv',
                                value: '1,2,3',
                            },
                            overrides: [],
                        },
                    ],
                },
            ],
            context,
            logError: console.log,
        });

        const evaluatedStrategies = client
            .isEnabled(featureName, context)
            .strategies.map((strategy) => strategy.name);

        expect(evaluatedStrategies).toEqual(
            strategies.map((strategy) => strategy.name),
        );
    });
});


text:
require 'eol/activity_log_item'

class CollectionActivityLog < LoggingModel
  establish_connection("#{Rails.env}_logging")

  include EOL::ActivityLogItem

  belongs_to :collection, :touch => true
  belongs_to :collection_item # ONLY if it affected one
  belongs_to :user # Who took the action
  belongs_to :activity # What happened

  after_create :log_activity_in_solr
  after_create :queue_notifications

  alias :link_to :collection # Needed for rendering links; we need to know which association to make the link to

  def log_activity_in_solr
    return nil if self.collection_item.blank? || self.collection_item.collection.blank?
    return if self.collection_item.collection.watch_collection?
    keyword = self.collection_item.collected_item_type rescue nil
    base_index_hash = {
      'activity_log_unique_key' => "CollectionActivityLog_#{id}",
      'activity_log_type' => 'CollectionActivityLog',
      'activity_log_id' => self.id,
      'action_keyword' => keyword,
      'user_id' => self.user_id,
      'date_created' => self.created_at.solr_timestamp }
    EOL::Solr::ActivityLog.index_notifications(base_index_hash, notification_recipient_objects)
  end

  def queue_notifications
    Notification.queue_notifications(notification_recipient_objects, self)
  end

  def notification_recipient_objects
    return @notification_recipients if @notification_recipients
    @notification_recipients = []
    add_recipient_collection(@notification_recipients)
    add_recipient_communities(@notification_recipients)
    add_recipient_containing_collections(@notification_recipients)
    add_recipient_collector(@notification_recipients)
    add_recipient_users_watchlists(@notification_recipients)
    add_recipient_users_getting_watched(@notification_recipients)
    @notification_recipients
  end

private

  def add_recipient_collection(recipients)
    recipients << self.collection  # for collection newsfeed
  end

  def add_recipient_collector(recipients)
    # TODO: this is a new notification type - probably for ACTIVITY only
    recipients << { :user => user, :notification_type => :i_collected_something,
                    :frequency => NotificationFrequency.never }
  end

  def add_recipient_communities(recipients)
    if self.collection && ! self.collection.communities.blank?
      recipients += self.collection.communities  # communities associated this collection
    end
  end

  def add_recipient_containing_collections(recipients)
    # news feed of collections which contain the thing commented on
    Collection.which_contain(self.collection).each do |c|
      recipients << c
    end
  end

  def add_recipient_users_watchlists(recipients)
    recipients.select{ |c| c.class == Collection && c.watch_collection? }.each do |collection|
      collection.users.each do |user|
        user.add_as_recipient_if_listening_to(:changes_to_my_watched_collection, recipients)
      end
    end
  end

  def add_recipient_users_getting_watched(recipients)
    if someone_is_being_watched?
      collection_item.collected_item.add_as_recipient_if_listening_to(:i_am_being_watched, recipients)
    end
  end

  def someone_is_being_watched?
    activity.id == Activity.collect.id && collection_item.collected_item_type == 'User'
  end

end


text:
package com.google.errorprone.bugpatterns;

import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** @author scottjohnson@google.com (Scott Johnson) */
@RunWith(JUnit4.class)
public class ModifyingCollectionWithItselfTest {

  private final CompilationTestHelper compilationHelper =
      CompilationTestHelper.newInstance(ModifyingCollectionWithItself.class, getClass());

  @Test
  public void testPositiveCases1() {
    compilationHelper.addSourceFile("ModifyingCollectionWithItselfPositiveCases.java").doTest();
  }

  @Test
  public void testNegativeCase() {
    compilationHelper.addSourceFile("ModifyingCollectionWithItselfNegativeCases.java").doTest();
  }
}


text:
[![deps][deps]][deps-url]
[![devs][devs]][devs-url]
[![tests][tests]][tests-url]
[![code style][style]][style-url]

Website

Install

```bash
npm i
```

Develop

```bash
npm start
```

```bash
npm run build
```

[deps]: https://david-dm.org/michael-ciniawsky/website.svg
[deps-url]: https://david-dm.org/michael-ciniawsky/website

[devs]: https://david-dm.org/michael-ciniawsky/website.svg?info=devDependencies
[devs-url]: https://david-dm.org/michael-ciniawsky/website?info=devDependencies

[tests]: http://img.shields.io/travis/michael-ciniawsky/website.svg
[tests-url]: https://travis-ci.org/michael-ciniawsky/website

[cover]: https://coveralls.io/repos/github/michael-ciniawsky/website/badge.svg
[cover-url]: https://coveralls.io/github/michael-ciniawsky/website

[style]: https://img.shields.io/badge/code%20style-standard-yellow.svg
[style-url]: http://standardjs.com/


text:
<!DOCTYPE HTML>

Hello
Kitty


text:
using System;
using System.Collections.Generic;

using System.Text;
using System.Web;
using System.Collections.Specialized;

namespace Crypton.AvChat.Client.Events {
    /// <summary>
    /// Information about a user who left the channel
    /// </summary>
    public class UserLeaveEventArgs : PacketEventArgs {
        /// <summary>
        /// Gets the information about the user
        /// </summary>
        public class UserLeaveData {
            /// <summary>
            /// Get the user who left
            /// </summary>
            public string Name {
                get;
                private set;
            }
            /// <summary>
            /// Gets user's quit message (if available)
            /// </summary>
            public string Message {
                get;
                private set;
            }

            internal UserLeaveData(string data) {
                string[] fields = data.Split('#');

                this.Name = Uri.UnescapeDataString(fields[0]);
                this.Message = Uri.UnescapeDataString(fields[1]);
            }
        }

/*
userleave channel="#general" data="Bob%20Smith#I%20be%20gone!"
Same as userquit above, except this time he's just leaving the channel, not the whole server.  The message is usually blank.
*/
        /// <summary>
        /// Gets the name of the channel
        /// </summary>
        public string Name {
            get;
            private set;
        }
        /// <summary>
        /// Gets the information about the user who left
        /// </summary>
        public UserLeaveData UserInfo {
            get;
            private set;
        }

        internal UserLeaveEventArgs(NameValueCollection packet)
            : base(packet) {

                this.Name = packet["channel"];
                this.UserInfo = new UserLeaveData(packet["data"]);
        }
    }
}


text:
import sys
import cobra

if (len(sys.argv) is not 3):
    print "Usage: python convert_sbml_model_to_json.py <sbml_model> <json_model>"
    quit()

sbml_model = sys.argv[1]
json_model = sys.argv[2]

model = cobra.io.read_sbml_model(sbml_model)
cobra.io.save_json_model(model, json_model)

print "SBML at " + sbml_model + " --> " + "JSON at " + json_model


text:
package org.eurekaclinical.scribeupext.provider;

import com.fasterxml.jackson.databind.JsonNode;
import org.eurekaclinical.scribeupext.profile.EurekaAttributesDefinition;
import org.eurekaclinical.scribeupext.profile.TwitterProfile;
import org.scribe.up.profile.JsonHelper;
import org.scribe.up.profile.UserProfile;
import org.scribe.up.profile.twitter.TwitterAttributesDefinition;

/**
 * Extracts the user's Twitter profile. This subclass of the original Google
 * OAuth2 provider overrides the URL for getting the user's profile with the
 * current URL, and it populates the profile attributes that Eureka! Clinical
 * expects.
 *
 * @author Andrew Post
 */
public class SSLTwitterProvider extends org.scribe.up.provider.impl.TwitterProvider {

    /**
     * Returns the current URL for requesting the user's profile.
     *
     * @return the URL for requesting the user's profile.
     */
    @Override
    protected String getProfileUrl() {
        return "https://api.twitter.com/1.1/account/verify_credentials.json";
    }

    /**
     * Returns the user's profile using the attributes that Eureka! Clinical
     * expects.
     *
     * @param body the JSON response from the user profile request.
     *
     * @return the user's profile.
     */
    @Override
    protected UserProfile extractUserProfile(final String body) {
        final TwitterProfile profile = new TwitterProfile();
        final JsonNode json = JsonHelper.getFirstNode(body);
        if (json != null) {
            profile.setId(JsonHelper.get(json, "id"));
            profile.addAttribute(EurekaAttributesDefinition.USERNAME, JsonHelper.get(json, TwitterAttributesDefinition.SCREEN_NAME));
            profile.addAttribute(EurekaAttributesDefinition.FULLNAME, JsonHelper.get(json, TwitterAttributesDefinition.NAME));
        }
        return profile;
    }

}


text:
import webob

from nova.compute import vm_states
import nova.context
from nova import exception
from nova.openstack.common import jsonutils
from nova.openstack.common import timeutils
from nova.openstack.common import uuidutils
from nova import test
from nova.tests import fake_instance

class CommonMixin(object):
    def setUp(self):
        super(CommonMixin, self).setUp()
        self.compute_api = None
        self.context = nova.context.RequestContext('fake', 'fake')

    def _make_request(self, url, body):
        req = webob.Request.blank('/v3' + url)
        req.method = 'POST'
        req.body = jsonutils.dumps(body)
        req.content_type = 'application/json'
        return req.get_response(self.app)

    def _stub_instance_get(self, uuid=None):
        if uuid is None:
            uuid = uuidutils.generate_uuid()
        instance = fake_instance.fake_instance_obj(self.context,
                id=1, uuid=uuid, vm_state=vm_states.ACTIVE,
                task_state=None, launched_at=timeutils.utcnow())
        self.compute_api.get(self.context, uuid, expected_attrs=None,
                             want_objects=True).AndReturn(instance)
        return instance

    def _stub_instance_get_failure(self, exc_info, uuid=None):
        if uuid is None:
            uuid = uuidutils.generate_uuid()
        self.compute_api.get(self.context, uuid, expected_attrs=None,
                             want_objects=True).AndRaise(exc_info)
        return uuid

    def _test_non_existing_instance(self, action, body_map=None):
        uuid = uuidutils.generate_uuid()
        self._stub_instance_get_failure(
                exception.InstanceNotFound(instance_id=uuid), uuid=uuid)

        self.mox.ReplayAll()

        res = self._make_request('/servers/%s/action' % uuid,
                                 {action: body_map.get(action)})
        self.assertEqual(404, res.status_int)
        # Do these here instead of tearDown because this method is called
        # more than once for the same test case
        self.mox.VerifyAll()
        self.mox.UnsetStubs()

    def _test_action(self, action, body=None, method=None,
                     compute_api_args_map={}):
        if method is None:
            method = action

        instance = self._stub_instance_get()

        args, kwargs = compute_api_args_map.get(action, ((), {}))
        getattr(self.compute_api, method)(self.context, instance, *args,
                                          **kwargs)

        self.mox.ReplayAll()

        res = self._make_request('/servers/%s/action' % instance.uuid,
                                 {action: body})
        self.assertEqual(202, res.status_int)
        # Do these here instead of tearDown because this method is called
        # more than once for the same test case
        self.mox.VerifyAll()
        self.mox.UnsetStubs()

    def _test_invalid_state(self, action, method=None, body_map=None,
                            compute_api_args_map=None):
        if method is None:
            method = action
        if body_map is None:
            body_map = {}
        if compute_api_args_map is None:
            compute_api_args_map = {}

        instance = self._stub_instance_get()

        args, kwargs = compute_api_args_map.get(action, ((), {}))

        getattr(self.compute_api, method)(self.context, instance,
                                          *args, **kwargs).AndRaise(
                exception.InstanceInvalidState(
                    attr='vm_state', instance_uuid=instance.uuid,
                    state='foo', method=method))

        self.mox.ReplayAll()

        res = self._make_request('/servers/%s/action' % instance.uuid,
                                 {action: body_map.get(action)})
        self.assertEqual(409, res.status_int)
        self.assertIn("Cannot \'%s\' while instance" % action, res.body)
        # Do these here instead of tearDown because this method is called
        # more than once for the same test case
        self.mox.VerifyAll()
        self.mox.UnsetStubs()

    def _test_locked_instance(self, action, method=None, body=None,
                              compute_api_args_map={}):
        if method is None:
            method = action

        instance = self._stub_instance_get()

        args, kwargs = compute_api_args_map.get(action, ((), {}))
        getattr(self.compute_api, method)(self.context, instance, *args,
                                          **kwargs).AndRaise(
                exception.InstanceIsLocked(instance_uuid=instance.uuid))

        self.mox.ReplayAll()

        res = self._make_request('/servers/%s/action' % instance.uuid,
                                 {action: body})
        self.assertEqual(409, res.status_int)
        # Do these here instead of tearDown because this method is called
        # more than once for the same test case
        self.mox.VerifyAll()
        self.mox.UnsetStubs()

class CommonTests(CommonMixin, test.NoDBTestCase):
    def _test_actions(self, actions, method_translations={}, body_map={},
                      args_map={}):
        for action in actions:
            method = method_translations.get(action)
            body = body_map.get(action)
            self.mox.StubOutWithMock(self.compute_api, method or action)
            self._test_action(action, method=method, body=body,
                              compute_api_args_map=args_map)
            # Re-mock this.
            self.mox.StubOutWithMock(self.compute_api, 'get')

    def _test_actions_with_non_existed_instance(self, actions, body_map={}):
        for action in actions:
            self._test_non_existing_instance(action,
                                             body_map=body_map)
            # Re-mock this.
            self.mox.StubOutWithMock(self.compute_api, 'get')

    def _test_actions_raise_conflict_on_invalid_state(
            self, actions, method_translations={}, body_map={}, args_map={}):
        for action in actions:
            method = method_translations.get(action)
            self.mox.StubOutWithMock(self.compute_api, method or action)
            self._test_invalid_state(action, method=method,
                                     body_map=body_map,
                                     compute_api_args_map=args_map)
            # Re-mock this.
            self.mox.StubOutWithMock(self.compute_api, 'get')

    def _test_actions_with_locked_instance(self, actions,
                                           method_translations={},
                                           body_map={}, args_map={}):
        for action in actions:
            method = method_translations.get(action)
            body = body_map.get(action)
            self.mox.StubOutWithMock(self.compute_api, method or action)
            self._test_locked_instance(action, method=method, body=body,
                                       compute_api_args_map=args_map)
            # Re-mock this.
            self.mox.StubOutWithMock(self.compute_api, 'get')


text:
<!DOCTYPE html>

  <title>caffeine-test.coffee</title>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, target-densitydpi=160dpi, initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
  <link rel="stylesheet" media="all" href="docco.css" />

          Jump To …
          +

                caffeine-test.coffee

                caffeine.coffee

caffeine-test.coffee

                ¶

Copyright © 2013 Ambrus Csaszar

Tests for caffeine.coffee

caff = require "./caffeine.coffee"

Exception = caff.Exception
Assume = caff.Assume
Num = caff.Num

                ¶

Validate the basic functions of the TestSuite

class TestTests extends caff.TestSuite
    TestOK: () ->
    TestError: () -> throw new Exception "Flog"
    TestFailure: () -> @Assert false, "Something weird happened"
    TestFoo: "bar"
    Testtoo: []
    teStcar: {}

class CaffeineTests extends caff.TestSuite

                ¶

Validate Exception inheritance

    TestExceptions: () ->
        @Assert Exception, "Must have Exception class"
        class TestEx extends Exception
        class TestEx2 extends TestEx
        e = new TestEx2
        @Assert e instanceof Error
        @Assert e instanceof Exception
        @Assert e instanceof TestEx
        @Assert e instanceof TestEx2

    TestNumber: () ->
        for n in [-1234,-2,0,2,4,24,123458482]
            @Assert Num.IsInt n
            @Assert Num.IsEven n
            @Assert not Num.IsOdd n
        for n in [-123,-1,1,3,5,7,19,23493281]
            @Assert Num.IsInt n
            @Assert not Num.IsEven n
            @Assert Num.IsOdd n
        for n in [-1232543543.999,-1.00000000001,-1.1,1.1,1.0000001,1234939429.999]
            @Assert not Num.IsInt n

                ¶

Export the tests publicly

module.exports = { CaffeineTests }

                ¶

And run them if we're in Node

if not window?
    new CaffeineTests().Run()


text:
namespace media {

// FrameStatistics struct deals with frames of one stream, i.e. either
// audio or video.
struct FrameStatistics {
  // Audio: total number of frames that have been rendered.
  // Video: total number of frames that were supposed to be rendered. Late video
  //        frames might be skipped, but are counted here.
  uint32_t total = 0;

  // A number of late frames. Late frames are a subset of the total frames.
  // Audio: The frame is late if it might cause an underrun, i.e. comes from
  //        decoder when audio buffer is already depleted.
  // Video: The frame is late if it missed its presentation time as determined
  //        by PTS when it comes from decoder.  The rendering policy (i.e.
  //        render or skip) does not affect this number.
  uint32_t late = 0;

  void Clear() { total = late = 0; }

  // Increments |total| frame count.
  void IncrementFrameCount() { ++total; }

  // Increments |late| frame count except it is the first frame after start.
  // For each IncrementLateFrameCount() call there should be preceding
  // IncrementFrameCount() call.
  void IncrementLateFrameCount();
};

// MediaStatistics class gathers and reports playback quality statistics to UMA.
//
// This class is not thread safe. The caller should guarantee that operations
// on FrameStatistics objects does not happen during Start() and
// StopAndReport(). The Start() and StopAndReport() methods need to be called
// sequentially.

class MediaStatistics {
 public:
  MediaStatistics();
  ~MediaStatistics();

  // Returns the frame statistics for audio frames.
  FrameStatistics& audio_frame_stats() { return audio_frame_stats_; }

  // Returns the frame statistics for video frames.
  FrameStatistics& video_frame_stats() { return video_frame_stats_; }

  // Starts gathering statistics. When called in a row only the first call will
  // take effect.
  void Start(base::TimeDelta current_playback_time);

  // Stops gathering statistics, calculate and report results. When called
  // in a row only the first call will take effect.
  void StopAndReport(base::TimeDelta current_playback_time);

  // Adds starvation event. Starvation happens when the player interrupts
  // the regular playback and asks for more data.
  void AddStarvation() { ++num_starvations_; }

 private:
  // Resets the data to the initial state.
  void Clear();

  // Calculates relative data based on total frame numbers and reports it and
  // the duration to UMA.
  void Report(base::TimeDelta duration);

  base::TimeDelta start_time_ = kNoTimestamp();
  FrameStatistics audio_frame_stats_;
  FrameStatistics video_frame_stats_;
  uint32_t num_starvations_ = 0;
};

}  // namespace media

#endif  // MEDIA_BASE_ANDROID_MEDIA_STATISTICS_H_


text:
bearbeeswidget
==============

Android widget which updates every 30 minutes with a new message.  Clickable widget displays a popup message.


text:
import {normalize} from 'normalizr';
import {camelizeKeys} from 'humps';

export const NORMALIZE = Symbol('NORMALIZE');
export default store => next => action => {
    const {[NORMALIZE]: options, ...tail} = action;

    // copy symbols that aren't copied with rest operator
    const symbols = Object.getOwnPropertySymbols(action)
        .filter(symbol => symbol !== NORMALIZE);
    symbols.forEach(symbol => tail[symbol] = action[symbol]);

    if (typeof options !== 'object' || options === null) {
        return next(tail);
    }

    let {
        schema,
        attribute = 'payload'
    } = options;

    if (typeof attribute !== 'string') {
        throw new Error('[NORMALIZE].attribute must be a string');
    }
    if (!schema) {
        throw new Error('[NORMALIZE].schema must be a normalizr schema');
    }

    if (!tail[attribute]) {
        return next(tail);
    }
    const camelizedJson = camelizeKeys(tail[attribute]);
    tail[attribute] = normalize(camelizedJson, schema);
    return next(tail);
};


text:
module BrInvoicesPdf
  module Cfe
    module Renderer
      module Totals
        extend Util::BaseRenderer
        extend BaseRenderer

        module_function

        def execute(pdf, data)
          insert_box_info(pdf, data)

          pdf.move_down(5)
        end

        def box_info(data_payment)
          [
            ['Total bruto dos itens', format_currency(data_payment[:total_price])],
            ['Desconto', format_currency(data_payment[:discount])],
            ['Total', format_currency(data_payment[:total])]
          ]
        end
        private_class_method :box_info
      end
    end
  end
end


text:
/*
 * ComparisonOperatorsJUnitTest.java
 * JUnit based test
 *
 * Created on March 10, 2005, 3:14 PM
 */
package com.gemstone.gemfire.cache.query.functional;

import static org.junit.Assert.fail;

import java.util.Collection;
import java.util.Iterator;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.query.CacheUtils;
//import com.gemstone.gemfire.cache.query.IndexType;
import com.gemstone.gemfire.cache.query.Query;
import com.gemstone.gemfire.cache.query.QueryService;
import com.gemstone.gemfire.cache.query.data.Portfolio;
import com.gemstone.gemfire.test.junit.categories.IntegrationTest;

/**
 *
 * @author vaibhav
 */
@Category(IntegrationTest.class)
public class ComparisonOperatorsJUnitTest  {

  public ComparisonOperatorsJUnitTest() {
  }

  public String getName() {
    return this.getClass().getSimpleName();
  }

  @Before
  public void setUp() throws java.lang.Exception {
    CacheUtils.startCache();
    Region region = CacheUtils.createRegion("Portfolios", Portfolio.class);
    region.put("0",new Portfolio(0));
    region.put("1",new Portfolio(1));
    region.put("2",new Portfolio(2));
    region.put("3",new Portfolio(3));
  }

  @After
  public void tearDown() throws java.lang.Exception {
    CacheUtils.closeCache();
  }

  String operators[] ={"=","<>","!=","<","<=",">",">="};

  @Test
  public void testCompareWithInt() throws Exception{
    String var = "ID";
    int value = 2;
    QueryService qs = CacheUtils.getQueryService();
    for(int i=0;i<operators.length;i++){
      Query query = qs.newQuery("SELECT DISTINCT * FROM /Portfolios where "+var+operators[i]+value);
      Object result = query.execute();
      if(result instanceof Collection){
        Iterator iter = ((Collection)result).iterator();
        while(iter.hasNext()){
          boolean isPassed = false;
          Portfolio p = (Portfolio)iter.next();
          switch(i){
            case 0 : isPassed = (p.getID() == value); break;
            case 1 : isPassed = (p.getID() != value); break;
            case 2 : isPassed = (p.getID() != value); break;
            case 3 : isPassed = (p.getID() < value); break;
            case 4 : isPassed = (p.getID() <= value); break;
            case 5 : isPassed = (p.getID() > value); break;
            case 6 : isPassed = (p.getID() >= value); break;
          }
          if(!isPassed)
            fail(this.getName()+" failed for operator "+operators[i]);
        }
      }else{
        fail(this.getName()+" failed for operator "+operators[i]);
      }
    }
  }

  @Test
  public void testCompareWithString() throws Exception{
    String var = "P1.secId";
    String value = "DELL";
    QueryService qs = CacheUtils.getQueryService();
    for(int i=0;i<operators.length;i++){
      Query query = qs.newQuery("SELECT DISTINCT * FROM /Portfolios where "+var+operators[i]+"'"+value+"'");
      Object result = query.execute();
      if(result instanceof Collection){
        Iterator iter = ((Collection)result).iterator();
        while(iter.hasNext()){
          boolean isPassed = false;
          Portfolio p = (Portfolio)iter.next();
          switch(i){
            case 0 : isPassed = (p.getP1().getSecId().compareTo(value) == 0); break;
            case 1 : isPassed = (p.getP1().getSecId().compareTo(value) != 0); break;
            case 2 : isPassed = (p.getP1().getSecId().compareTo(value) != 0); break;
            case 3 : isPassed = (p.getP1().getSecId().compareTo(value) < 0); break;
            case 4 : isPassed = (p.getP1().getSecId().compareTo(value) <= 0); break;
            case 5 : isPassed = (p.getP1().getSecId().compareTo(value) > 0); break;
            case 6 : isPassed = (p.getP1().getSecId().compareTo(value) >= 0); break;
          }
          if(!isPassed)
            fail(this.getName()+" failed for operator "+operators[i]);
        }
      }else{
        fail(this.getName()+" failed for operator "+operators[i]);
      }
    }
  }

  @Test
  public void testCompareWithNULL() throws Exception{
    String var ="P2";
    Object value = null;
    QueryService qs = CacheUtils.getQueryService();
    for(int i=0;i<operators.length;i++){
      Query query = qs.newQuery("SELECT DISTINCT * FROM /Portfolios where "+var+operators[i]+value);
      Object result = query.execute();
      if(result instanceof Collection){
        Iterator iter = ((Collection)result).iterator();
        while(iter.hasNext()){
          boolean isPassed = false;
          Portfolio p = (Portfolio)iter.next();
          switch(i){
            case 0 : isPassed = (p.getP2() == value); break;
            default : isPassed = (p.getP2() != value); break;
          }
          if(!isPassed)
            fail(this.getName()+" failed for operator "+operators[i]);
        }
      }else{
        fail(this.getName()+" failed for operator "+operators[i]);
      }
    }
  }

  @Test
  public void testCompareWithUNDEFINED() throws Exception{
    String var = "P2.secId";
    QueryService qs = CacheUtils.getQueryService();
    for(int i=0;i<operators.length;i++){
      // According to docs:
      // To perform equality or inequality comparisons with UNDEFINED, use the
      // IS_DEFINED and IS_UNDEFINED preset query functions instead of these
      // comparison operators.
      if(!operators[i].equals("=") && !operators[i].equals("!=") && !operators[i].equals("<>")) {
        Query query = qs.newQuery("SELECT DISTINCT * FROM /Portfolios where "+var+operators[i]+" UNDEFINED");
        Object result = query.execute();
        if(result instanceof Collection){
          if(((Collection)result).size() != 0)
            fail(this.getName()+" failed for operator "+operators[i]);
        }else{
          fail(this.getName()+" failed for operator "+operators[i]);
        }
      }
    }
  }
}


text:
@interface ImageCache : NSObject
{
@private
    NSMutableArray *keyArray;
    NSMutableDictionary *memoryCache;
    NSFileManager *fileManager;
}

+ (ImageCache *)sharedImageCache;

- (UIImage *)imageForKey:(NSString *)key;

- (BOOL)hasImageWithKey:(NSString *)key;

- (void)storeImage:(UIImage *)image withKey:(NSString *)key;

- (BOOL)imageExistsInMemory:(NSString *)key;

- (BOOL)imageExistsInDisk:(NSString *)key;

- (NSUInteger)countImagesInMemory;

- (NSUInteger)countImagesInDisk;

- (void)removeImageWithKey:(NSString *)key;

- (void)removeAllImages;

- (void)removeAllImagesInMemory;

- (void)removeOldImages;

@end


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.android_webview.test;

import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.chromium.android_webview.AwContents;

/**
 * Base class for WebView find-in-page API tests.
 */
public class WebViewFindApisTestBase extends AndroidWebViewTestBase {

    private static final String WOODCHUCK =
            "How much WOOD would a woodchuck chuck if a woodchuck could chuck wOoD?";

    private FindResultListener mFindResultListener;
    private AwContents mContents;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        try {
            mContents = loadContentsFromStringSync(WOODCHUCK);
        } catch (Throwable t) {
            throw new Exception(t);
        }
    }

    @Override
    protected void tearDown() throws Exception {
        destroyAwContentsOnMainSync(mContents);
        super.tearDown();
    }

    protected AwContents contents() {
        return mContents;
    }

    // Internal interface to intercept find results from AwContentsClient.
    private interface FindResultListener {
        public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches,
                boolean isDoneCounting);
    };

    private AwContents loadContentsFromStringSync(final String html) throws Throwable {
        final TestAwContentsClient contentsClient = new TestAwContentsClient() {
            @Override
            public void onFindResultReceived(int activeMatchOrdinal,
                    int numberOfMatches, boolean isDoneCounting) {
                if (mFindResultListener == null) return;
                mFindResultListener.onFindResultReceived(activeMatchOrdinal, numberOfMatches,
                        isDoneCounting);
            }
        };

        final AwContents contents =
                createAwTestContainerViewOnMainSync(contentsClient).getAwContents();
        final String data = "" + html + "";
        loadDataSync(contents, contentsClient.getOnPageFinishedHelper(),
                data, "text/html", false);
        return contents;
    }

    /**
     * Invokes findAllSync on the UI thread and returns the number of matches.
     *
     * @param searchString A string to search for.
     * @return The number of instances of the string that were found.
     * @throws Throwable
     */
    protected int findAllSyncOnUiThread(final String searchString)
            throws Throwable {
        return runTestOnUiThreadAndGetResult(new Callable<Integer>() {
            @Override
            public Integer call() {
                return mContents.findAllSync(searchString);
            }
        });
    }

    /**
     * Invokes findAllAsync on the UI thread, blocks until find results are
     * received, and returns the number of matches.
     *
     * @param searchString A string to search for.
     * @return The number of instances of the string that were found.
     * @throws Throwable
     */
    protected int findAllAsyncOnUiThread(final String searchString)
            throws Throwable {
        final IntegerFuture future = new IntegerFuture() {
            @Override
            public void run() {
                mFindResultListener = new FindResultListener() {
                    @Override
                    public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches,
                            boolean isDoneCounting) {
                        if (isDoneCounting) set(numberOfMatches);
                    }
                };
                mContents.findAllAsync(searchString);
            }
        };
        runTestOnUiThread(future);
        return future.get(10, TimeUnit.SECONDS);
    }

    /**
     * Invokes findNext on the UI thread, blocks until find results are
     * received, and returns the ordinal of the highlighted match.
     *
     * @param forwards The direction to search as a boolean, with forwards
     *                 represented as true and backwards as false.
     * @return The ordinal of the highlighted match.
     * @throws Throwable
     */
    protected int findNextOnUiThread(final boolean forwards)
            throws Throwable {
        final IntegerFuture future = new IntegerFuture() {
            @Override
            public void run() {
                mFindResultListener = new FindResultListener() {
                    @Override
                    public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches,
                            boolean isDoneCounting) {
                        if (isDoneCounting) set(activeMatchOrdinal);
                    }
                };
                mContents.findNext(forwards);
            }
        };
        runTestOnUiThread(future);
        return future.get(10, TimeUnit.SECONDS);
    }

    /**
     * Invokes clearMatches on the UI thread.
     *
     * @throws Throwable
     */
    protected void clearMatchesOnUiThread() throws Throwable {
        runTestOnUiThread(new Runnable() {
            @Override
            public void run() {
                mContents.clearMatches();
            }
        });
    }

    // Similar to java.util.concurrent.Future, but without the ability to cancel.
    private static abstract class IntegerFuture implements Runnable {
        private CountDownLatch mLatch = new CountDownLatch(1);
        private int mValue;

        @Override
        public abstract void run();

        /**
         * Gets the value of this Future, blocking for up to the specified
         * timeout for it become available. Throws a TimeoutException if the
         * timeout expires.
         */
        public int get(long timeout, TimeUnit unit) throws Throwable {
            if (!mLatch.await(timeout, unit)) {
                throw new TimeoutException();
            }
            return mValue;
        }

        /**
         * Sets the value of this Future.
         */
        protected void set(int value) {
            mValue = value;
            mLatch.countDown();
        }
    }
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/dataproc/v1/clusters.proto

namespace Google\Cloud\Dataproc\V1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * The GKE config for this cluster.
 *
 * Generated from protobuf message google.cloud.dataproc.v1.GkeClusterConfig
 */
class GkeClusterConfig extends \Google\Protobuf\Internal\Message
{
    /**
     * Optional. A target for the deployment.
     *
     * Generated from protobuf field .google.cloud.dataproc.v1.GkeClusterConfig.NamespacedGkeDeploymentTarget namespaced_gke_deployment_target = 1 [(.google.api.field_behavior) = OPTIONAL];
     */
    private $namespaced_gke_deployment_target = null;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type \Google\Cloud\Dataproc\V1\GkeClusterConfig\NamespacedGkeDeploymentTarget $namespaced_gke_deployment_target
     *           Optional. A target for the deployment.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Dataproc\V1\Clusters::initOnce();
        parent::__construct($data);
    }

    /**
     * Optional. A target for the deployment.
     *
     * Generated from protobuf field .google.cloud.dataproc.v1.GkeClusterConfig.NamespacedGkeDeploymentTarget namespaced_gke_deployment_target = 1 [(.google.api.field_behavior) = OPTIONAL];
     * @return \Google\Cloud\Dataproc\V1\GkeClusterConfig\NamespacedGkeDeploymentTarget|null
     */
    public function getNamespacedGkeDeploymentTarget()
    {
        return $this->namespaced_gke_deployment_target;
    }

    public function hasNamespacedGkeDeploymentTarget()
    {
        return isset($this->namespaced_gke_deployment_target);
    }

    public function clearNamespacedGkeDeploymentTarget()
    {
        unset($this->namespaced_gke_deployment_target);
    }

    /**
     * Optional. A target for the deployment.
     *
     * Generated from protobuf field .google.cloud.dataproc.v1.GkeClusterConfig.NamespacedGkeDeploymentTarget namespaced_gke_deployment_target = 1 [(.google.api.field_behavior) = OPTIONAL];
     * @param \Google\Cloud\Dataproc\V1\GkeClusterConfig\NamespacedGkeDeploymentTarget $var
     * @return $this
     */
    public function setNamespacedGkeDeploymentTarget($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Dataproc\V1\GkeClusterConfig\NamespacedGkeDeploymentTarget::class);
        $this->namespaced_gke_deployment_target = $var;

        return $this;
    }

}


text:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';

// Import shared component
import { WarningPanelComponent } from './warning-panel';

@NgModule({
	imports: [
		BrowserModule,
		FormsModule
	],
	declarations: [
		WarningPanelComponent
	],
	exports: [
		WarningPanelComponent
	]
})
export class WarningPanelModule {};


text:
// Project.cpp : Initialization functions
#include "StdAfx.h"
#include "StdArx.h"
#include "resource.h"

HINSTANCE _hdllInstance =NULL ;

// This command registers an ARX command.
void AddCommand(const char* cmdGroup, const char* cmdInt, const char* cmdLoc,
				const int cmdFlags, const AcRxFunctionPtr cmdProc, const int idLocal = -1);

// NOTE: DO NOT edit the following lines.
//{{AFX_ARX_MSG
void InitApplication();
void UnloadApplication();
//}}AFX_ARX_MSG

// NOTE: DO NOT edit the following lines.
//{{AFX_ARX_ADDIN_FUNCS
//}}AFX_ARX_ADDIN_FUNCS

/////////////////////////////////////////////////////////////////////////////
// DLL Entry Point
extern "C"
BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/)
{
	if (dwReason == DLL_PROCESS_ATTACH)
	{
        _hdllInstance = hInstance;
	} else if (dwReason == DLL_PROCESS_DETACH) {
	}
	return TRUE;    // ok
}

/////////////////////////////////////////////////////////////////////////////
// ObjectARX EntryPoint
extern "C" AcRx::AppRetCode
acrxEntryPoint(AcRx::AppMsgCode msg, void* pkt)
{
	switch (msg) {
	case AcRx::kInitAppMsg:
		// Comment out the following line if your
		// application should be locked into memory
		acrxDynamicLinker->unlockApplication(pkt);
		acrxDynamicLinker->registerAppMDIAware(pkt);
		InitApplication();
		break;
	case AcRx::kUnloadAppMsg:
		UnloadApplication();
		break;
	}
	return AcRx::kRetOK;
}

// Init this application. Register your
// commands, reactors...
void InitApplication()
{
	// NOTE: DO NOT edit the following lines.
	//{{AFX_ARX_INIT
	AddCommand("ASDK", "MYINPUT", "MYINPUT", ACRX_CMD_TRANSPARENT | ACRX_CMD_USEPICKSET, asdkmyinput);
	AddCommand("ASDK", "MYSELECT", "MYSELECT", ACRX_CMD_TRANSPARENT | ACRX_CMD_USEPICKSET, asdkmyselect);
	//}}AFX_ARX_INIT

	// TODO: add your initialization functions

}

// Unload this application. Unregister all objects
// registered in InitApplication.
void UnloadApplication()
{
	// NOTE: DO NOT edit the following lines.
	//{{AFX_ARX_EXIT
	acedRegCmds->removeGroup("ASDK");
	//}}AFX_ARX_EXIT

	// TODO: clean up your application
}

// This functions registers an ARX command.
// It can be used to read the localized command name
// from a string table stored in the resources.
void AddCommand(const char* cmdGroup, const char* cmdInt, const char* cmdLoc,
				const int cmdFlags, const AcRxFunctionPtr cmdProc, const int idLocal)
{
	char cmdLocRes[65];

	// If idLocal is not -1, it's treated as an ID for
	// a string stored in the resources.
	if (idLocal != -1) {

		// Load strings from the string table and register the command.
		::LoadString(_hdllInstance, idLocal, cmdLocRes, 64);
		acedRegCmds->addCommand(cmdGroup, cmdInt, cmdLocRes, cmdFlags, cmdProc);

	} else
		// idLocal is -1, so the 'hard coded'
		// localized function name is used.
		acedRegCmds->addCommand(cmdGroup, cmdInt, cmdLoc, cmdFlags, cmdProc);
}


text:
package org.apache.beam.runners.dataflow.worker;

import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkArgument;

import com.google.api.services.dataflow.model.ApproximateReportedProgress;
import com.google.api.services.dataflow.model.ApproximateSplitRequest;
import com.google.api.services.dataflow.model.ReportedParallelism;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.NoSuchElementException;
import java.util.Optional;
import org.apache.avro.Schema;
import org.apache.beam.runners.dataflow.worker.util.common.worker.NativeReader;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.io.AvroSource;
import org.apache.beam.sdk.io.AvroSource.AvroReader;
import org.apache.beam.sdk.io.BoundedSource;
import org.apache.beam.sdk.io.FileSystems;
import org.apache.beam.sdk.io.OffsetBasedSource;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.util.CoderUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A source that reads PCollections that have been materialized as Avro files. Records are read from
 * the Avro file as a series of byte arrays. The coder provided is used to deserialize each record
 * from a byte array.
 *
 * @param <T> the type of the elements read from the source
 */
@SuppressWarnings({
  "nullness" // TODO(https://issues.apache.org/jira/browse/BEAM-10402)
})
public class AvroByteReader<T> extends NativeReader<T> {
  private static final Logger LOG = LoggerFactory.getLogger(AvroByteReader.class);

  final long startPosition;
  final long endPosition;
  final String filename;
  final AvroSource<ByteBuffer> avroSource;
  final PipelineOptions options;

  final Coder<T> coder;
  private final Schema schema = Schema.create(Schema.Type.BYTES);

  AvroByteReader(
      String filename,
      long startPosition,
      long endPosition,
      Coder<T> coder,
      PipelineOptions options) {
    checkArgument(filename != null, "filename must not be null");
    checkArgument(coder != null, "coder must not be null");
    checkArgument(options != null, "options must not be null");
    this.filename = filename;
    this.startPosition = startPosition;
    this.endPosition = endPosition;
    this.coder = coder;
    this.options = options;
    this.avroSource =
        (AvroSource<ByteBuffer>) ((AvroSource) AvroSource.from(filename).withSchema(schema));
  }

  @Override
  public AvroByteFileIterator iterator() throws IOException {
    BoundedSource.BoundedReader<ByteBuffer> reader;
    if (startPosition == 0 && endPosition == Long.MAX_VALUE) {
      // Read entire file (or collection of files).
      reader = avroSource.createReader(options);
    } else {
      // Read a subrange of file.
      reader =
          avroSource
              .createForSubrangeOfFile(
                  FileSystems.matchSingleFileSpec(filename), startPosition, endPosition)
              .createReader(options);
    }
    return new AvroByteFileIterator((AvroReader<ByteBuffer>) reader);
  }

  class AvroByteFileIterator extends NativeReaderIterator<T> {
    private final AvroReader<ByteBuffer> reader;
    private Optional<T> current;

    public AvroByteFileIterator(AvroReader<ByteBuffer> reader) {
      this.reader = reader;
    }

    @Override
    public boolean start() throws IOException {
      if (!reader.start()) {
        current = Optional.empty();
        return false;
      }
      updateCurrent();
      return true;
    }

    @Override
    public boolean advance() throws IOException {
      if (!reader.advance()) {
        current = Optional.empty();
        return false;
      }
      updateCurrent();
      return true;
    }

    private void updateCurrent() throws IOException {
      ByteBuffer inBuffer = reader.getCurrent();
      notifyElementRead(inBuffer.remaining());
      byte[] encodedElem = new byte[inBuffer.remaining()];
      inBuffer.get(encodedElem);
      current = Optional.of(CoderUtils.decodeFromByteArray(coder, encodedElem));
    }

    @Override
    public T getCurrent() throws NoSuchElementException {
      return current.get();
    }

    @Override
    public Progress getProgress() {
      Double readerProgress = reader.getFractionConsumed();
      if (readerProgress == null) {
        return null;
      }
      ApproximateReportedProgress progress = new ApproximateReportedProgress();
      progress.setFractionConsumed(readerProgress);
      double consumedParallelism = reader.getSplitPointsConsumed();
      double remainingParallelism = reader.getSplitPointsRemaining();
      progress.setConsumedParallelism(new ReportedParallelism().setValue(consumedParallelism));
      if (remainingParallelism >= 0) {
        progress.setRemainingParallelism(new ReportedParallelism().setValue(remainingParallelism));
      }
      return SourceTranslationUtils.cloudProgressToReaderProgress(progress);
    }

    @Override
    public void close() throws IOException {
      reader.close();
    }

    @Override
    public DynamicSplitResult requestDynamicSplit(DynamicSplitRequest splitRequest) {
      ApproximateSplitRequest splitProgress =
          SourceTranslationUtils.splitRequestToApproximateSplitRequest(splitRequest);
      double splitAtFraction = splitProgress.getFractionConsumed();
      LOG.info("Received request for dynamic split at {}", splitAtFraction);
      OffsetBasedSource<ByteBuffer> residual = reader.splitAtFraction(splitAtFraction);
      if (residual == null) {
        LOG.info("Rejected split request for split at {}", splitAtFraction);
        return null;
      }
      com.google.api.services.dataflow.model.Position acceptedPosition =
          new com.google.api.services.dataflow.model.Position();
      acceptedPosition.setByteOffset(residual.getStartOffset());
      LOG.info(
          "Accepted split for position {} which resulted in a new source with byte offset {}",
          splitAtFraction,
          residual.getStartOffset());
      return new DynamicSplitResultWithPosition(
          SourceTranslationUtils.cloudPositionToReaderPosition(acceptedPosition));
    }
  }
}


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>googleapiclient.errors.UnexpectedMethodError</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

        Package googleapiclient ::
        Module errors ::
        Class UnexpectedMethodError

[hide private]

[frames] | no frames]

Class UnexpectedMethodError

source code

              object --+
                       |
exceptions.BaseException --+
                           |
        exceptions.Exception --+
                               |
                           Error --+
                                   |
                                  UnexpectedMethodError

Exception raised by RequestMockBuilder on unexpected calls.

        Instance Methods
        [hide private]

          __init__(*args,
        **kwargs)

      Constructor for an UnexpectedMethodError.

            source code

Inherited from exceptions.Exception:
      __new__

Inherited from exceptions.BaseException:
      __delattr__,
      __getattribute__,
      __getitem__,
      __getslice__,
      __reduce__,
      __repr__,
      __setattr__,
      __setstate__,
      __str__,
      __unicode__

Inherited from object:
      __format__,
      __hash__,
      __reduce_ex__,
      __sizeof__,
      __subclasshook__

        Properties
        [hide private]

Inherited from exceptions.BaseException:
      args,
      message

Inherited from object:
      __class__

        Method Details
        [hide private]

__init__(*args,
        **kwargs)

(Constructor)

  	source code

Constructor for an UnexpectedMethodError.

Decorators:

@util.positional(1)

Overrides:
        object.__init__

         Home

         Trees

         Indices

         Help

    Generated by Epydoc 3.0.1 on Fri Oct  2 20:46:22 2020

      http://epydoc.sourceforge.net


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <artifactId>SimpleOSGi</artifactId>
  <version>2.0.0-SNAPSHOT</version>
   <parent>
      <artifactId>ParentMaven</artifactId>
      <version>1.0.0-SNAPSHOT</version>
      <groupId>kura.driver</groupId>
      <relativePath>../kura.driver.ParentMaven</relativePath>
   </parent>
   <packaging>maven-plugin</packaging>
</project>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DAL;
/// Summary description for HOSO_QT_DAOTAO
/// </summary>
public class HOSO_QT_DAOTAOController : LinqProvider
{
    public HOSO_QT_DAOTAOController()
	{
		//
		// TODO: Add constructor logic here
		//
	}
    public List<HOSO_QT_DAOTAO> GetHOSODTFr_key(decimal fr_key)
    {
            var hsdt = (from t in dataContext.HOSO_QT_DAOTAOs
                        where t.FR_KEY == fr_key
                  select t);
            return hsdt.ToList();

    }
}


text:
const benefitOrder = [
  `section8`,
  `snap`,
];

export { benefitOrder };


text:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <padding android:left="5dp" android:top="5dp" android:right="5dp"
        android:bottom="5dp" />
    <corners android:radius="4dp" />
    <gradient
        android:angle="90"
        android:startColor="#80f7f7f7"
        android:centerColor="#80f7f7f7"
        android:endColor="#80CCCCCC"
        android:type="linear" />
</shape>


text:
@implementation MiYiArrowItem
+ (instancetype)itemWithIcon:(NSString *)icon title:(NSString *)title destVcClass:(Class)destVcClass
{
    MiYiArrowItem *item = [self itemWithIcon:icon title:title];
    item.destVcClass = destVcClass;
    return item;
}

+ (instancetype)itemWithTitle:(NSString *)title destVcClass:(Class)destVcClass
{
    return [self itemWithIcon:nil title:title destVcClass:destVcClass];
}

+ (instancetype)itemWithIcon:(NSString *)icon title:(NSString *)title color:(UIColor *)color destVcClass:(Class)destVcClass
{
    MiYiArrowItem *item = [self itemWithIcon:icon title:title color:color];

    return item;
}

@end


text:
package tsdb

import (
	"encoding/binary"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"

	"github.com/pkg/errors"
)

const tombstoneFilename = "tombstones"

const (
	// MagicTombstone is 4 bytes at the head of a tombstone file.
	MagicTombstone = 0x130BA30

	tombstoneFormatV1 = 1
)

// TombstoneReader gives access to tombstone intervals by series reference.
type TombstoneReader interface {
	Get(ref uint64) Intervals

	Close() error
}

func writeTombstoneFile(dir string, tr tombstoneReader) error {
	path := filepath.Join(dir, tombstoneFilename)
	tmp := path + ".tmp"
	hash := newCRC32()

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

	buf := encbuf{b: make([]byte, 3*binary.MaxVarintLen64)}
	buf.reset()
	// Write the meta.
	buf.putBE32(MagicTombstone)
	buf.putByte(tombstoneFormatV1)
	_, err = f.Write(buf.get())
	if err != nil {
		return err
	}

	mw := io.MultiWriter(f, hash)

	for k, v := range tr {
		for _, itv := range v {
			buf.reset()
			buf.putUvarint64(k)
			buf.putVarint64(itv.Mint)
			buf.putVarint64(itv.Maxt)

			_, err = mw.Write(buf.get())
			if err != nil {
				return err
			}
		}
	}

	_, err = f.Write(hash.Sum(nil))
	if err != nil {
		return err
	}

	return renameFile(tmp, path)
}

// Stone holds the information on the posting and time-range
// that is deleted.
type Stone struct {
	ref       uint64
	intervals Intervals
}

func readTombstones(dir string) (tombstoneReader, error) {
	b, err := ioutil.ReadFile(filepath.Join(dir, tombstoneFilename))
	if err != nil {
		return nil, err
	}

	if len(b) < 5 {
		return nil, errors.Wrap(errInvalidSize, "tombstones header")
	}

	d := &decbuf{b: b[:len(b)-4]} // 4 for the checksum.
	if mg := d.be32(); mg != MagicTombstone {
		return nil, fmt.Errorf("invalid magic number %x", mg)
	}
	if flag := d.byte(); flag != tombstoneFormatV1 {
		return nil, fmt.Errorf("invalid tombstone format %x", flag)
	}

	if d.err() != nil {
		return nil, d.err()
	}

	// Verify checksum
	hash := newCRC32()
	if _, err := hash.Write(d.get()); err != nil {
		return nil, errors.Wrap(err, "write to hash")
	}
	if binary.BigEndian.Uint32(b[len(b)-4:]) != hash.Sum32() {
		return nil, errors.New("checksum did not match")
	}

	stonesMap := newEmptyTombstoneReader()
	for d.len() > 0 {
		k := d.uvarint64()
		mint := d.varint64()
		maxt := d.varint64()
		if d.err() != nil {
			return nil, d.err()
		}

		stonesMap.add(k, Interval{mint, maxt})
	}

	return newTombstoneReader(stonesMap), nil
}

type tombstoneReader map[uint64]Intervals

func newTombstoneReader(ts map[uint64]Intervals) tombstoneReader {
	return tombstoneReader(ts)
}

func newEmptyTombstoneReader() tombstoneReader {
	return tombstoneReader(make(map[uint64]Intervals))
}

func (t tombstoneReader) Get(ref uint64) Intervals {
	return t[ref]
}

func (t tombstoneReader) add(ref uint64, itv Interval) {
	t[ref] = t[ref].add(itv)
}

func (tombstoneReader) Close() error {
	return nil
}

// Interval represents a single time-interval.
type Interval struct {
	Mint, Maxt int64
}

func (tr Interval) inBounds(t int64) bool {
	return t >= tr.Mint && t <= tr.Maxt
}

func (tr Interval) isSubrange(dranges Intervals) bool {
	for _, r := range dranges {
		if r.inBounds(tr.Mint) && r.inBounds(tr.Maxt) {
			return true
		}
	}

	return false
}

// Intervals represents	a set of increasing and non-overlapping time-intervals.
type Intervals []Interval

// This adds the new time-range to the existing ones.
// The existing ones must be sorted.
func (itvs Intervals) add(n Interval) Intervals {
	for i, r := range itvs {
		// TODO(gouthamve): Make this codepath easier to digest.
		if r.inBounds(n.Mint-1) || r.inBounds(n.Mint) {
			if n.Maxt > r.Maxt {
				itvs[i].Maxt = n.Maxt
			}

			j := 0
			for _, r2 := range itvs[i+1:] {
				if n.Maxt < r2.Mint {
					break
				}
				j++
			}
			if j != 0 {
				if itvs[i+j].Maxt > n.Maxt {
					itvs[i].Maxt = itvs[i+j].Maxt
				}
				itvs = append(itvs[:i+1], itvs[i+j+1:]...)
			}
			return itvs
		}

		if r.inBounds(n.Maxt+1) || r.inBounds(n.Maxt) {
			if n.Mint < r.Maxt {
				itvs[i].Mint = n.Mint
			}
			return itvs
		}

		if n.Mint < r.Mint {
			newRange := make(Intervals, i, len(itvs[:i])+1)
			copy(newRange, itvs[:i])
			newRange = append(newRange, n)
			newRange = append(newRange, itvs[i:]...)

			return newRange
		}
	}

	itvs = append(itvs, n)
	return itvs
}


text:
using System.Runtime.Serialization;

namespace AdfToArm.Core.Models.LinkedServices
{
    public enum LinkedServiceType
    {
        [EnumMember(Value = "AzureSqlDatabase")]
        AzureSqlDatabase,
        [EnumMember(Value = "AzureSqlDW")]
        AzureSqlDW,
        [EnumMember(Value = "AzureStorage")]
        AzureStorage,
        [EnumMember(Value = "AzureStorageSas")]
        AzureStorageSas,
        [EnumMember(Value = "HDInsight")]
        HDInsight,
        [EnumMember(Value = "HDInsightOnDemand")]
        HDInsightOnDemand,
        [EnumMember(Value = "AzureDataLakeAnalytics")]
        AzureDataLakeAnalytics,
        [EnumMember(Value = "AzureDataLakeStore")]
        AzureDataLakeStore,
        [EnumMember(Value = "AzureBatch")]
        AzureBatch,
        [EnumMember(Value = "DocumentDb")]
        AzureCosmosDb,
        [EnumMember(Value = "AzureSearch")]
        AzureSearch,
        [EnumMember(Value = "AzureML")]
        AzureML
    }
}