text:
class TInfoSink;

namespace glslang {

struct TVectorFields {
    TVectorFields() { }

    TVectorFields(int c0, int c1, int c2, int c3) : num(4)
    {
        offsets[0] = c0;
        offsets[1] = c1;
        offsets[2] = c2;
        offsets[3] = c3;
    }

    int offsets[4];
    int num;
};

//
// Some helper structures for TIntermediate.  Their contents are encapsulated
// by TIntermediate.
//

// Used for detecting recursion:  A "call" is a pair: <caller, callee>.
struct TCall {
    TCall(const TString& pCaller, const TString& pCallee) : caller(pCaller), callee(pCallee) { }
    TString caller;
    TString callee;
    bool visited;
    bool currentPath;
    bool errorGiven;
};

// A generic 1-D range.
struct TRange {
    TRange(int start, int last) : start(start), last(last) { }
    bool overlap(const TRange& rhs) const
    {
        return last >= rhs.start && start <= rhs.last;
    }
    int start;
    int last;
};

// An IO range is a 3-D rectangle; the set of (location, component, index) triples all lying
// within the same location range, component range, and index value.  Locations don't alias unless
// all other dimensions of their range overlap.
struct TIoRange {
    TIoRange(TRange location, TRange component, TBasicType basicType, int index)
        : location(location), component(component), basicType(basicType), index(index) { }
    bool overlap(const TIoRange& rhs) const
    {
        return location.overlap(rhs.location) && component.overlap(rhs.component) && index == rhs.index;
    }
    TRange location;
    TRange component;
    TBasicType basicType;
    int index;
};

// An offset range is a 2-D rectangle; the set of (binding, offset) pairs all lying
// within the same binding and offset range.
struct TOffsetRange {
    TOffsetRange(TRange binding, TRange offset)
        : binding(binding), offset(offset) { }
    bool overlap(const TOffsetRange& rhs) const
    {
        return binding.overlap(rhs.binding) && offset.overlap(rhs.offset);
    }
    TRange binding;
    TRange offset;
};

// Things that need to be tracked per xfb buffer.
struct TXfbBuffer {
    TXfbBuffer() : stride(TQualifier::layoutXfbStrideEnd), implicitStride(0), containsDouble(false) { }
    std::vector<TRange> ranges;  // byte offsets that have already been assigned
    unsigned int stride;
    unsigned int implicitStride;
    bool containsDouble;
};

class TSymbolTable;
class TSymbol;
class TVariable;

//
// Set of helper functions to help parse and build the tree.
//
class TIntermediate {
public:
    explicit TIntermediate(EShLanguage l, int v = 0, EProfile p = ENoProfile) :
        source(EShSourceNone), language(l), profile(p), version(v), treeRoot(0),
        numMains(0), numErrors(0), numPushConstants(0), recursive(false),
        invocations(TQualifier::layoutNotSet), vertices(TQualifier::layoutNotSet), inputPrimitive(ElgNone), outputPrimitive(ElgNone),
        pixelCenterInteger(false), originUpperLeft(false),
        vertexSpacing(EvsNone), vertexOrder(EvoNone), pointMode(false), earlyFragmentTests(false), depthLayout(EldNone), depthReplacing(false), blendEquations(0),
        multiStream(false), xfbMode(false)
    {
        localSize[0] = 1;
        localSize[1] = 1;
        localSize[2] = 1;
        localSizeSpecId[0] = TQualifier::layoutNotSet;
        localSizeSpecId[1] = TQualifier::layoutNotSet;
        localSizeSpecId[2] = TQualifier::layoutNotSet;
        xfbBuffers.resize(TQualifier::layoutXfbBufferEnd);
    }
    void setLimits(const TBuiltInResource& r) { resources = r; }

    bool postProcess(TIntermNode*, EShLanguage);
    void output(TInfoSink&, bool tree);
    void removeTree();

    void setSource(EShSource s) { source = s; }
    EShSource getSource() const { return source; }
    void setEntryPoint(const char* ep) { entryPoint = ep; }
    const std::string& getEntryPoint() const { return entryPoint; }
    void setVersion(int v) { version = v; }
    int getVersion() const { return version; }
    void setProfile(EProfile p) { profile = p; }
    EProfile getProfile() const { return profile; }
    void setSpv(const SpvVersion& s) { spvVersion = s; }
    const SpvVersion& getSpv() const { return spvVersion; }
    EShLanguage getStage() const { return language; }
    void addRequestedExtension(const char* extension) { requestedExtensions.insert(extension); }
    const std::set<std::string>& getRequestedExtensions() const { return requestedExtensions; }

    void setTreeRoot(TIntermNode* r) { treeRoot = r; }
    TIntermNode* getTreeRoot() const { return treeRoot; }
    void addMainCount() { ++numMains; }
    int getNumMains() const { return numMains; }
    int getNumErrors() const { return numErrors; }
    void addPushConstantCount() { ++numPushConstants; }
    bool isRecursive() const { return recursive; }

    TIntermSymbol* addSymbol(const TVariable&);
    TIntermSymbol* addSymbol(const TVariable&, const TSourceLoc&);
    TIntermSymbol* addSymbol(const TType&, const TSourceLoc&);
    TIntermTyped* addConversion(TOperator, const TType&, TIntermTyped*) const;
    TIntermTyped* addShapeConversion(TOperator, const TType&, TIntermTyped*);
    TIntermTyped* addBinaryMath(TOperator, TIntermTyped* left, TIntermTyped* right, TSourceLoc);
    TIntermTyped* addAssign(TOperator op, TIntermTyped* left, TIntermTyped* right, TSourceLoc);
    TIntermTyped* addIndex(TOperator op, TIntermTyped* base, TIntermTyped* index, TSourceLoc);
    TIntermTyped* addUnaryMath(TOperator, TIntermTyped* child, TSourceLoc);
    TIntermTyped* addBuiltInFunctionCall(const TSourceLoc& line, TOperator, bool unary, TIntermNode*, const TType& returnType);
    bool canImplicitlyPromote(TBasicType from, TBasicType to, TOperator op = EOpNull) const;
    TOperator mapTypeToConstructorOp(const TType&) const;
    TIntermAggregate* growAggregate(TIntermNode* left, TIntermNode* right);
    TIntermAggregate* growAggregate(TIntermNode* left, TIntermNode* right, const TSourceLoc&);
    TIntermAggregate* makeAggregate(TIntermNode* node);
    TIntermAggregate* makeAggregate(TIntermNode* node, const TSourceLoc&);
    TIntermTyped* setAggregateOperator(TIntermNode*, TOperator, const TType& type, TSourceLoc);
    bool areAllChildConst(TIntermAggregate* aggrNode);
    TIntermNode*  addSelection(TIntermTyped* cond, TIntermNodePair code, const TSourceLoc&);
    TIntermTyped* addSelection(TIntermTyped* cond, TIntermTyped* trueBlock, TIntermTyped* falseBlock, const TSourceLoc&);
    TIntermTyped* addComma(TIntermTyped* left, TIntermTyped* right, const TSourceLoc&);
    TIntermTyped* addMethod(TIntermTyped*, const TType&, const TString*, const TSourceLoc&);
    TIntermConstantUnion* addConstantUnion(const TConstUnionArray&, const TType&, const TSourceLoc&, bool literal = false) const;
    TIntermConstantUnion* addConstantUnion(int, const TSourceLoc&, bool literal = false) const;
    TIntermConstantUnion* addConstantUnion(unsigned int, const TSourceLoc&, bool literal = false) const;
    TIntermConstantUnion* addConstantUnion(long long, const TSourceLoc&, bool literal = false) const;
    TIntermConstantUnion* addConstantUnion(unsigned long long, const TSourceLoc&, bool literal = false) const;
    TIntermConstantUnion* addConstantUnion(bool, const TSourceLoc&, bool literal = false) const;
    TIntermConstantUnion* addConstantUnion(double, TBasicType, const TSourceLoc&, bool literal = false) const;
    TIntermTyped* promoteConstantUnion(TBasicType, TIntermConstantUnion*) const;
    bool parseConstTree(TIntermNode*, TConstUnionArray, TOperator, const TType&, bool singleConstantParam = false);
    TIntermLoop* addLoop(TIntermNode*, TIntermTyped*, TIntermTyped*, bool testFirst, const TSourceLoc&);
    TIntermAggregate* addForLoop(TIntermNode*, TIntermNode*, TIntermTyped*, TIntermTyped*, bool testFirst, const TSourceLoc&);
    TIntermBranch* addBranch(TOperator, const TSourceLoc&);
    TIntermBranch* addBranch(TOperator, TIntermTyped*, const TSourceLoc&);
    TIntermTyped* addSwizzle(TVectorFields&, const TSourceLoc&);

    // Constant folding (in Constant.cpp)
    TIntermTyped* fold(TIntermAggregate* aggrNode);
    TIntermTyped* foldConstructor(TIntermAggregate* aggrNode);
    TIntermTyped* foldDereference(TIntermTyped* node, int index, const TSourceLoc&);
    TIntermTyped* foldSwizzle(TIntermTyped* node, TVectorFields& fields, const TSourceLoc&);

    // Tree ops
    static const TIntermTyped* findLValueBase(const TIntermTyped*, bool swizzleOkay);

    // Linkage related
    void addSymbolLinkageNodes(TIntermAggregate*& linkage, EShLanguage, TSymbolTable&);
    void addSymbolLinkageNode(TIntermAggregate*& linkage, TSymbolTable&, const TString&);
    void addSymbolLinkageNode(TIntermAggregate*& linkage, const TSymbol&);

    bool setInvocations(int i)
    {
        if (invocations != TQualifier::layoutNotSet)
            return invocations == i;
        invocations = i;
        return true;
    }
    int getInvocations() const { return invocations; }
    bool setVertices(int m)
    {
        if (vertices != TQualifier::layoutNotSet)
            return vertices == m;
        vertices = m;
        return true;
    }
    int getVertices() const { return vertices; }
    bool setInputPrimitive(TLayoutGeometry p)
    {
        if (inputPrimitive != ElgNone)
            return inputPrimitive == p;
        inputPrimitive = p;
        return true;
    }
    TLayoutGeometry getInputPrimitive() const { return inputPrimitive; }
    bool setVertexSpacing(TVertexSpacing s)
    {
        if (vertexSpacing != EvsNone)
            return vertexSpacing == s;
        vertexSpacing = s;
        return true;
    }
    TVertexSpacing getVertexSpacing() const { return vertexSpacing; }
    bool setVertexOrder(TVertexOrder o)
    {
        if (vertexOrder != EvoNone)
            return vertexOrder == o;
        vertexOrder = o;
        return true;
    }
    TVertexOrder getVertexOrder() const { return vertexOrder; }
    void setPointMode() { pointMode = true; }
    bool getPointMode() const { return pointMode; }

    bool setLocalSize(int dim, int size)
    {
        if (localSize[dim] > 1)
            return size == localSize[dim];
        localSize[dim] = size;
        return true;
    }
    unsigned int getLocalSize(int dim) const { return localSize[dim]; }

    bool setLocalSizeSpecId(int dim, int id)
    {
        if (localSizeSpecId[dim] != TQualifier::layoutNotSet)
            return id == localSizeSpecId[dim];
        localSizeSpecId[dim] = id;
        return true;
    }
    int getLocalSizeSpecId(int dim) const { return localSizeSpecId[dim]; }

    void setXfbMode() { xfbMode = true; }
    bool getXfbMode() const { return xfbMode; }
    void setMultiStream() { multiStream = true; }
    bool isMultiStream() const { return multiStream; }
    bool setOutputPrimitive(TLayoutGeometry p)
    {
        if (outputPrimitive != ElgNone)
            return outputPrimitive == p;
        outputPrimitive = p;
        return true;
    }
    TLayoutGeometry getOutputPrimitive() const { return outputPrimitive; }
    void setOriginUpperLeft() { originUpperLeft = true; }
    bool getOriginUpperLeft() const { return originUpperLeft; }
    void setPixelCenterInteger() { pixelCenterInteger = true; }
    bool getPixelCenterInteger() const { return pixelCenterInteger; }
    void setEarlyFragmentTests() { earlyFragmentTests = true; }
    bool getEarlyFragmentTests() const { return earlyFragmentTests; }
    bool setDepth(TLayoutDepth d)
    {
        if (depthLayout != EldNone)
            return depthLayout == d;
        depthLayout = d;
        return true;
    }
    TLayoutDepth getDepth() const { return depthLayout; }
    void setDepthReplacing() { depthReplacing = true; }
    bool isDepthReplacing() const { return depthReplacing; }

    void addBlendEquation(TBlendEquationShift b) { blendEquations |= (1 << b); }
    unsigned int getBlendEquations() const { return blendEquations; }

    void addToCallGraph(TInfoSink&, const TString& caller, const TString& callee);
    void merge(TInfoSink&, TIntermediate&);
    void finalCheck(TInfoSink&);

    void addIoAccessed(const TString& name) { ioAccessed.insert(name); }
    bool inIoAccessed(const TString& name) const { return ioAccessed.find(name) != ioAccessed.end(); }

    int addUsedLocation(const TQualifier&, const TType&, bool& typeCollision);
    int checkLocationRange(int set, const TIoRange& range, const TType&, bool& typeCollision);
    int addUsedOffsets(int binding, int offset, int numOffsets);
    bool addUsedConstantId(int id);
    int computeTypeLocationSize(const TType&) const;

    bool setXfbBufferStride(int buffer, unsigned stride)
    {
        if (xfbBuffers[buffer].stride != TQualifier::layoutXfbStrideEnd)
            return xfbBuffers[buffer].stride == stride;
        xfbBuffers[buffer].stride = stride;
        return true;
    }
    int addXfbBufferOffset(const TType&);
    unsigned int computeTypeXfbSize(const TType&, bool& containsDouble) const;
    static int getBaseAlignment(const TType&, int& size, int& stride, bool std140, bool rowMajor);

protected:
    TIntermSymbol* addSymbol(int Id, const TString&, const TType&, const TConstUnionArray&, TIntermTyped* subtree, const TSourceLoc&);
    void error(TInfoSink& infoSink, const char*);
    void mergeBodies(TInfoSink&, TIntermSequence& globals, const TIntermSequence& unitGlobals);
    void mergeLinkerObjects(TInfoSink&, TIntermSequence& linkerObjects, const TIntermSequence& unitLinkerObjects);
    void mergeImplicitArraySizes(TType&, const TType&);
    void mergeErrorCheck(TInfoSink&, const TIntermSymbol&, const TIntermSymbol&, bool crossStage);
    void checkCallGraphCycles(TInfoSink&);
    void inOutLocationCheck(TInfoSink&);
    TIntermSequence& findLinkerObjects() const;
    bool userOutputUsed() const;
    static int getBaseAlignmentScalar(const TType&, int& size);
    bool isSpecializationOperation(const TIntermOperator&) const;

    const EShLanguage language;  // stage, known at construction time
    EShSource source;            // source language, known a bit later
    std::string entryPoint;
    EProfile profile;
    int version;
    SpvVersion spvVersion;
    TIntermNode* treeRoot;
    std::set<std::string> requestedExtensions;  // cumulation of all enabled or required extensions; not connected to what subset of the shader used them
    TBuiltInResource resources;
    int numMains;
    int numErrors;
    int numPushConstants;
    bool recursive;
    int invocations;
    int vertices;
    TLayoutGeometry inputPrimitive;
    TLayoutGeometry outputPrimitive;
    bool pixelCenterInteger;
    bool originUpperLeft;
    TVertexSpacing vertexSpacing;
    TVertexOrder vertexOrder;
    bool pointMode;
    int localSize[3];
    int localSizeSpecId[3];
    bool earlyFragmentTests;
    TLayoutDepth depthLayout;
    bool depthReplacing;
    int blendEquations;        // an 'or'ing of masks of shifts of TBlendEquationShift
    bool xfbMode;
    bool multiStream;

    typedef std::list<TCall> TGraph;
    TGraph callGraph;

    std::set<TString> ioAccessed;           // set of names of statically read/written I/O that might need extra checking
    std::vector<TIoRange> usedIo[4];        // sets of used locations, one for each of in, out, uniform, and buffers
    std::vector<TOffsetRange> usedAtomics;  // sets of bindings used by atomic counters
    std::vector<TXfbBuffer> xfbBuffers;     // all the data we need to track per xfb buffer
    std::unordered_set<int> usedConstantId; // specialization constant ids used

private:
    void operator=(TIntermediate&); // prevent assignments
};

} // end namespace glslang

#endif // _LOCAL_INTERMEDIATE_INCLUDED_


text:
import Route from 'ember-eureka/route';

export default Route.extend({

    model: function(params) {
        var modelId = params.id;
        // var populate = App.getModelMeta(_type).get('editViewPopulate');
        if (!modelId) {
            console.log('XXX no id');
            // return this.get('store').createRecord();
        }
        return this.get('store').fetch(modelId);
    },

    actions: {
        refreshModel: function() {
            this.refresh();
        }
    }

});

redpajama_set_name: RedPajamaGithub


text:
package com.defano.hypertalk.ast.expression;

import com.defano.hypertalk.ast.model.Value;
import com.defano.hypertalk.exception.HtException;
import com.defano.wyldcard.runtime.ExecutionContext;
import org.antlr.v4.runtime.ParserRuleContext;

/**
 * An expression with parenthesis around it, promoting its evaluation order. For example, '(3 + x)'.
 */
public class GroupExp extends Expression {

    public final Expression expression;

    public GroupExp(ParserRuleContext context, Expression expression) {
        super(context);
        this.expression = expression;
    }

    @Override
    protected Value onEvaluate(ExecutionContext context) throws HtException {
        return expression.evaluate(context);
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$CI=& get_instance();
$action_buttons=array();
$action_buttons[]=array(
    'label'=>$CI->lang->line("ACTION_BACK"),
    'href'=>site_url($CI->controller_url)
);
$action_buttons[]=array(
    'type'=>'button',
    'label'=>$CI->lang->line("ACTION_SAVE"),
    'id'=>'button_action_save',
    'data-form'=>'#save_form'
);
$action_buttons[]=array(
    'type'=>'button',
    'label'=>$CI->lang->line("ACTION_SAVE_NEW"),
    'id'=>'button_action_save_new',
    'data-form'=>'#save_form'
);
$action_buttons[]=array(
    'type'=>'button',
    'label'=>$CI->lang->line("ACTION_CLEAR"),
    'id'=>'button_action_clear',
    'data-form'=>'#save_form'
);
$CI->load->view('action_buttons',array('action_buttons'=>$action_buttons));
?>
<form class="form_valid" id="save_form" action="<?php echo site_url($CI->controller_url.'/index/save');?>" method="post">
    <input type="hidden" id="id" name="id" value="<?php echo $item['id']; ?>" />
    <input type="hidden" id="system_save_new_status" name="system_save_new_status" value="0" />

                <?php echo $title; ?>

                <?php echo $this->lang->line('LABEL_NAME');?>*

                <input type="text" name="item[name]" class="form-control" value="<?php echo $item['name'];?>"/>

                <?php echo $CI->lang->line('LABEL_DESCRIPTION');?>

                <textarea name="item[description]" class="form-control"><?php echo $item['description'] ?></textarea>

                <?php echo $this->lang->line('LABEL_PERCENTAGE');?>*

                <input type="text" name="item[percentage]" class="form-control float_type_positive" value="<?php echo $item['percentage'];?>"/>

                <?php echo $CI->lang->line('LABEL_ORDER');?>*

                <input type="text" name="item[ordering]" class="form-control" value="<?php echo $item['ordering'] ?>" >

</form>


text:
var should = require('should'),
    url = require('url'),
    wd = require('../common/wd-with-cov'),
    _ = require('lodash');

process.env = _(process.env).omit('SAUCE_USERNAME', 'SAUCE_ACCESS_KEY');

describe("wd", function() {
  describe("local", function() {
    describe("wd remote tests", function() {
      describe("default", function() {
        it("browser should be initialized with default parameters", function(done) {
          var browser;
          browser = wd.remote();
          browser.configUrl.hostname.should.equal('127.0.0.1');
          browser.configUrl.port.should.equal('4444');
          browser.configUrl.pathname.should.equal('/wd/hub');
          should.not.exist(browser.configUrl.auth);
          done();
        });
      });
      describe("url string", function() {
        it("browser should be initialized with: http url", function(done) {
          var browser;
          browser = wd.remote('http://localhost:8888/wd/hub');
          browser.configUrl.protocol.should.equal('http:');
          browser.configUrl.hostname.should.equal('localhost');
          browser.configUrl.port.should.equal('8888');
          browser.configUrl.pathname.should.equal('/wd/hub');
          should.not.exist(browser.configUrl.auth);
          done(null);
        });
        it("browser should be initialized with: https url", function(done) {
          var browser;
          browser = wd.remote('https://localhost:8888/wd/hub');
          browser.configUrl.protocol.should.equal('https:');
          browser.configUrl.hostname.should.equal('localhost');
          browser.configUrl.port.should.equal('8888');
          browser.configUrl.pathname.should.equal('/wd/hub');
          should.not.exist(browser.configUrl.auth);
          done(null);
        });
        it("browser should be initialized with: http url, auth", function(done) {
          var browser;
          browser = wd.remote('http://mickey:mouse@localhost:8888/wd/hub');
          browser.configUrl.hostname.should.equal('localhost');
          browser.configUrl.port.should.equal('8888');
          browser.configUrl.pathname.should.equal('/wd/hub');
          browser.configUrl.auth.should.equal('mickey:mouse');
          done(null);
        });
      });
      describe("url object", function() {
        it("browser should be initialized with: http url", function(done) {
          var browser;
          browser = wd.remote(url.parse('http://localhost:8888/wd/hub'));
          browser.configUrl.protocol.should.equal('http:');
          browser.configUrl.hostname.should.equal('localhost');
          browser.configUrl.port.should.equal('8888');
          browser.configUrl.pathname.should.equal('/wd/hub');
          should.not.exist(browser.configUrl.auth);
          done(null);
        });
        it("browser should be initialized with: https url", function(done) {
          var browser;
          browser = wd.remote(url.parse('https://localhost:8888/wd/hub'));
          browser.configUrl.protocol.should.equal('https:');
          browser.configUrl.hostname.should.equal('localhost');
          browser.configUrl.port.should.equal('8888');
          browser.configUrl.pathname.should.equal('/wd/hub');
          should.not.exist(browser.configUrl.auth);
          done(null);
        });
        it("browser should be initialized with: http url, auth", function(done) {
          var browser;
          browser = wd.remote(url.parse('http://mickey:mouse@localhost:8888/wd/hub'));
          browser.configUrl.hostname.should.equal('localhost');
          browser.configUrl.port.should.equal('8888');
          browser.configUrl.pathname.should.equal('/wd/hub');
          browser.configUrl.auth.should.equal('mickey:mouse');
          done(null);
        });
      });
      describe("params", function() {
        it("browser should be initialized with: host, port", function(done) {
          var browser;
          browser = wd.remote('localhost', 8888);
          browser.configUrl.hostname.should.equal('localhost');
          browser.configUrl.port.should.equal('8888');
          browser.configUrl.pathname.should.equal('/wd/hub');
          should.not.exist(browser.configUrl.auth);
          done(null);
        });
        it("browser should be initialized with: host, port, user, pwd", function(done) {
          var browser;
          browser = wd.remote('localhost', '8888', 'mickey', 'mouse');
          browser.configUrl.hostname.should.equal('localhost');
          browser.configUrl.port.should.equal('8888');
          browser.configUrl.pathname.should.equal('/wd/hub');
          browser.configUrl.auth.should.equal('mickey:mouse');
          done(null);
        });
      });
    });
    describe("options", function() {
      it("browser should be initialized with default", function(done) {
        var browser;
        browser = wd.remote({});
        browser.configUrl.hostname.should.equal('127.0.0.1');
        browser.configUrl.port.should.equal('4444');
        browser.configUrl.pathname.should.equal('/wd/hub');
        should.not.exist(browser.configUrl.auth);
        done(null);
      });
      it("browser should be initialized with: hostname, port", function(done) {
        var browser;
        browser = wd.remote({
          hostname: 'localhost',
          port: 8888
        });
        browser.configUrl.protocol.should.equal('http:');
        browser.configUrl.hostname.should.equal('localhost');
        browser.configUrl.port.should.equal('8888');
        browser.configUrl.pathname.should.equal('/wd/hub');
        should.not.exist(browser.configUrl.auth);
        done(null);
      });
      it("browser should be initialized with: protocol, hostname, port", function(done) {
        var browser;
        browser = wd.remote({
          protocol: 'https:',
          hostname: 'localhost',
          port: '8888'
        });
        browser.configUrl.protocol.should.equal('https:');
        browser.configUrl.hostname.should.equal('localhost');
        browser.configUrl.port.should.equal('8888');
        browser.configUrl.pathname.should.equal('/wd/hub');
        should.not.exist(browser.configUrl.auth);
        done(null);
      });
      it("browser should be initialized with: host", function(done) {
        var browser;
        browser = wd.remote({
          host: 'localhost:8888',
        });
        browser.configUrl.hostname.should.equal('localhost');
        browser.configUrl.port.should.equal('8888');
        browser.configUrl.pathname.should.equal('/wd/hub');
        should.not.exist(browser.configUrl.auth);
        done(null);
      });
      it("browser should be initialized with: hostname, port, user, pwd", function(done) {
        var browser;
        browser = wd.remote({
          hostname: 'localhost',
          port: 8888,
          user: 'mickey',
          pwd: 'mouse'
        });
        browser.configUrl.hostname.should.equal('localhost');
        browser.configUrl.port.should.equal('8888');
        browser.configUrl.pathname.should.equal('/wd/hub');
        browser.configUrl.auth.should.equal('mickey:mouse');
        done(null);
      });
      it("browser should be initialized with: hostname, port, user, pwd", function(done) {
        var browser;
        browser = wd.remote({
          hostname: 'localhost',
          port: 8888,
          auth: 'mickey:mouse',
        });
        browser.configUrl.hostname.should.equal('localhost');
        browser.configUrl.port.should.equal('8888');
        browser.configUrl.pathname.should.equal('/wd/hub');
        browser.configUrl.auth.should.equal('mickey:mouse');
        done(null);
      });
      it("browser should be initialized with: path", function(done) {
        var browser;
        browser = wd.remote({
          pathname: '/taiwan'
        });
        browser.configUrl.hostname.should.equal('127.0.0.1');
        browser.configUrl.port.should.equal('4444');
        browser.configUrl.pathname.should.equal('/taiwan');
        should.not.exist(browser.configUrl.auth);
        done(null);
      });
      it("browser should be initialized with: hostname, port, path", function(done) {
        var browser;
        browser = wd.remote({
          hostname: 'localhost',
          port: 8888,
          pathname: '/'
        });
        browser.configUrl.hostname.should.equal('localhost');
        browser.configUrl.port.should.equal('8888');
        browser.configUrl.pathname.should.equal('');
        should.not.exist(browser.configUrl.auth);
        done(null);
      });
      it("browser should be initialized with: hostname, port, username, user, pwd", function(done) {
        var browser;
        browser = wd.remote({
          hostname: 'localhost',
          port: 8888,
          user: 'mickey',
          pwd: 'mouse',
          pathname: '/asia/taiwan'
        });
        browser.configUrl.hostname.should.equal('localhost');
        browser.configUrl.port.should.equal('8888');
        browser.configUrl.pathname.should.equal('/asia/taiwan');
        browser.configUrl.auth.should.equal('mickey:mouse');
        done(null);
      });
    });
    describe("automatic Saucelabs config", function() {
      before(function() {
        process.env.SAUCE_USERNAME = 'zorro';
        process.env.SAUCE_ACCESS_KEY = '1234-5678';
      });
      after(function() {
        delete process.env.SAUCE_USERNAME;
        delete process.env.SAUCE_ACCESS_KEY;
      });
      it("browser should be initialized with indexed parameters", function(done) {
        var browser;
        browser = wd.remote('ondemand.saucelabs.com', 80);
        browser.configUrl.hostname.should.equal('ondemand.saucelabs.com');
        browser.configUrl.port.should.equal('80');
        browser.configUrl.pathname.should.equal('/wd/hub');
        browser.configUrl.auth.should.equal('zorro:1234-5678');
        done();
      });
      it("browser should be initialized with named parameters", function(done) {
        var browser;
        browser = wd.remote({
          hostname: 'ondemand.saucelabs.com',
          port:80 });
        browser.configUrl.hostname.should.equal('ondemand.saucelabs.com');
        browser.configUrl.port.should.equal('80');
        browser.configUrl.pathname.should.equal('/wd/hub');
        browser.configUrl.auth.should.equal('zorro:1234-5678');
        done();
      });
      it("browser should be initialized with url string", function(done) {
        var browser;
        browser = wd.remote('http://ondemand.saucelabs.com/wd/hub');
        browser.configUrl.hostname.should.equal('ondemand.saucelabs.com');
        (browser.configUrl.port || '80').should.equal('80');
        browser.configUrl.pathname.should.equal('/wd/hub');
        browser.configUrl.auth.should.equal('zorro:1234-5678');
        done();
      });
      it("browser should be initialized with url object", function(done) {
        var browser;
        browser = wd.remote(url.parse('http://ondemand.saucelabs.com/wd/hub'));
        browser.configUrl.hostname.should.equal('ondemand.saucelabs.com');
        (browser.configUrl.port || '80').should.equal('80');
        browser.configUrl.pathname.should.equal('/wd/hub');
        browser.configUrl.auth.should.equal('zorro:1234-5678');
        done();
      });
    });
    describe("backward compatibility", function() {
      it("browser should be initialized with: host, port", function(done) {
        var browser;
        browser = wd.remote({
          host: 'localhost',
          port: 8888
        });
        browser.configUrl.protocol.should.equal('http:');
        browser.configUrl.hostname.should.equal('localhost');
        browser.configUrl.port.should.equal('8888');
        browser.configUrl.pathname.should.equal('/wd/hub');
        should.not.exist(browser.configUrl.auth);
        done(null);
      });
      it("browser should be initialized with: https, host, port", function(done) {
        var browser;
        browser = wd.remote({
          https: true,
          host: 'localhost',
          port: 8888
        });
        browser.configUrl.protocol.should.equal('https:');
        browser.configUrl.hostname.should.equal('localhost');
        browser.configUrl.port.should.equal('8888');
        browser.configUrl.pathname.should.equal('/wd/hub');
        should.not.exist(browser.configUrl.auth);
        done(null);
      });
      it("browser should be initialized with: host, port, username, accesskey", function(done) {
        var browser;
        browser = wd.remote({
          host: 'localhost',
          port: 8888,
          username: 'mickey',
          accessKey: 'mouse'
        });
        browser.configUrl.hostname.should.equal('localhost');
        browser.configUrl.port.should.equal('8888');
        browser.configUrl.pathname.should.equal('/wd/hub');
        browser.configUrl.auth.should.equal('mickey:mouse');
        done(null);
      });
      it("browser should be initialized with: path", function(done) {
        var browser;
        browser = wd.remote({
          path: '/taiwan'
        });
        browser.configUrl.hostname.should.equal('127.0.0.1');
        browser.configUrl.port.should.equal('4444');
        browser.configUrl.pathname.should.equal('/taiwan');
        should.not.exist(browser.configUrl.auth);
        done(null);
      });
    });
  });
});


text:
package com.authy.api;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.HashMap;
import java.util.Map;

@XmlRootElement(name = "hash")
public class Hash extends Instance implements Formattable {

    private User user = null;
    private String token;
    private boolean success;

    public Hash() {
    }

    public Hash(int status, String content) {
        super(status, content);
    }

    @XmlElement(type = User.class)
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    /**
     * Map a Token instance to its Java's Map representation.
     *
     * @return a Java's Map with the description of this object.
     */
    public Map<String, String> toMap() {

        HashMap<String,String> map = new HashMap<>();

        if( user != null ) {

            Map<String,String> userMap = user.toMap();

            for(String st : userMap.keySet() ){
                map.put("user."+st,userMap.get(st));
            }

        }

        map.put("message",message);
        map.put("token",token);
        map.put("success",String.valueOf(success));
        return map;
    }
}


text:
/* File for "Drawing Text" lesson of the OpenGL tutorial on
 * www.videotutorialsrock.com
 */

/* The 3D font is stored in an external file called "charset", which is
 * basically a compact way of representing a series of OpenGL commands for
 * drawing each of the printable ASCII characters, other than the space
 * character (33 to 126).  The file has the following format:
 *
 *
 *
 * the characters "VTR\0FNT\0"
 * float space_width (the width of ' ', relative to the height the font)
 *
 * float char_33_scale
 * unsigned short char_33_width (width = value * scale / 65536)
 * unsigned short char_33_height (height = value * scale / 65536)
 * unsigned short char_33_num_verts
 * unsigned short char_33_vert_1_x (x = value * scale / 65536 + scale / 2)
 * unsigned short char_33_vert_1_y (y = value * scale / 65536 + scale / 2)
 * unsigned short char_33_vert_2_x (x = value * scale / 65536 + scale / 2)
 * unsigned short char_33_vert_2_y (y = value * scale / 65536 + scale / 2)
 * ...
 * unsigned short char_33_vert_n_x (x = value * scale / 65536 + scale / 2)
 * unsigned short char_33_vert_n_y (y = value * scale / 65536 + scale / 2)
 * unsigned short opcode_1_for_char_33_front_face
 * unsigned short opcode_2_for_char_33_front_face
 * ...
 * unsigned short opcode_n_for_char_33_front_face
 * unsigned short end_part_opcode
 * unsigned short opcode_1_for_char_33_3D_part
 * unsigned short opcode_2_for_char_33_3D_part
 * ...
 * unsigned short opcode_n_for_char_33_3D_part
 * unsigned short end_part_opcode
 *
 * float char_34_scale
 * ...
 *
 *
 *
 * The character models are centered at (0, 0[, 0]).
 *
 * unsigned shorts are represented in little-endian format.  floats are
 * represented using one signed character exp followed by one signed integer
 * mant, presented in little-endian format.  This represents the number
 * mant * 2^exp if mant is positive and -(~mant * 2^exp) if mant is negative.
 *
 * The opcodes are as follows:
 *
 * 0 to num_verts - 1:
 *     vertex with the same index as the opcode, using the vertex on the front
 *     face (the one with normal (0, 0, 1))
 * num_verts to 2 * num_verts - 1:
 *     Vertex with index opcode - num_verts, using the vertex on the back face
 *     (the one with normal (0, 0, -1)).  This opcode is only available for the
 *     3D part of each model.
 * 65532:
 *     Normal vector.  Followed by an unsigned short indicating the angle of the
 *     vector divided by (2 pi) times 65536.  The normal vector indicated is
 *     (cos theta, sin theta, 0).  This opcode is only available for the 3D part
 *     of each model.
 * 65533: GL_TRIANGLE_STRIP
 * 65534: GL_TRIANGLES
 * 65535: end_part
 *
 * Vertices must be specified in counterclockwise order, or, in the case of
 * triangle strips, they must be specified such that the first three vertices
 * indicate a triangle in counterclockwise order.  When specifying the 2D part
 * of the model, counterclockwise order is relative to the front face.
 */

#include <fstream>
#include "Utils/GDraw.hpp"
#include "Utils/GText3D.hpp"
#include <cmath>

using namespace std;

T3DLoadException::T3DLoadException(string message1) : message0(message1) {

}

string T3DLoadException::message() const {
	return message0;
}

namespace {
	//Converts a four-character array to an integer, using little-endian form
	int toInt(const char* bytes) {
		return int(((unsigned char)bytes[3] << 24) |
				   ((unsigned char)bytes[2] << 16) |
				   ((unsigned char)bytes[1] << 8) |
				   (unsigned char)bytes[0]);
	}

	//Converts a five-character array to a float, as indicated in the comment at
	//the top of this file
	float toFloat(const char* buffer) {
		char exp = buffer[0];
		int mant = toInt(buffer + 1);
		bool isNegative;
		if (mant < 0) {
			isNegative = true;
			mant = ~mant;
		}
		else
			isNegative = false;
		float a = (2147483648u + (unsigned int)mant) *
					pow(2.0f, exp) / 2147483648.0;
		return isNegative ? -a : a;
	}

	//Converts a two-character array to an unsigned short, using little-endian
	//form
	unsigned short toUShort(const char* buffer) {
		return (((unsigned short)((unsigned char)buffer[1])) << 8) +
				(unsigned short)((unsigned char)buffer[0]);
	}

	//Just like auto_ptr, but for arrays
	template<class T>
	class auto_array {
		private:
			T* array;
			mutable bool isReleased;
		public:
			explicit auto_array(T* array_ = NULL) :
				array(array_), isReleased(false) {
			}

			auto_array(const auto_array<T> &aarray) {
				array = aarray.array;
				isReleased = aarray.isReleased;
				aarray.isReleased = true;
			}

			~auto_array() {
				if (!isReleased && array != NULL) {
					delete[] array;
				}
			}

			T* get() const {
				return array;
			}

			T &operator*() const {
				return *array;
			}

			void operator=(const auto_array<T> &aarray) {
				if (!isReleased && array != NULL) {
					delete[] array;
				}
				array = aarray.array;
				isReleased = aarray.isReleased;
				aarray.isReleased = true;
			}

			T* operator->() const {
				return array;
			}

			T* release() {
				isReleased = true;
				return array;
			}

			void reset(T* array_ = NULL) {
				if (!isReleased && array != NULL) {
					delete[] array;
				}
				array = array_;
			}

			T* operator+(int i) {
				return array + i;
			}

			T &operator[](int i) {
				return array[i];
			}
	};

	enum Opcodes {OP_NORMAL = 65532,
				  OP_TRIANGLE_STRIP,
				  OP_TRIANGLES,
				  OP_END_PART};

	const float PI_TIMES_2_OVER_65536 = 2 * 3.1415926535f / 65536.0f;

	class T3DFont {
		private:
			float spaceWidth;
			float widths[94];
			GLuint displayListId2D;
			GLuint displayListId3D;
		public:
			//Loads the specified font file into a new T3DFont object
			T3DFont(ifstream &input) {
				char buffer[8];
				input.read(buffer, 8);
				if (input.fail()) {
					throw T3DLoadException("Invalid font file");
				}

				const char header[9] = "VTR\0FNT\0";
				for(int i = 0; i < 8; i++) {
					if (buffer[i] != header[i]) {
						throw T3DLoadException("Invalid font file");
					}
				}

				input.read(buffer, 5);
				spaceWidth = toFloat(buffer);

				displayListId2D = glGenLists(94);
				displayListId3D = glGenLists(94);
				for(int i = 0; i < 94; i++) {
					input.read(buffer, 5);
					float scale = toFloat(buffer) / 65536;
					input.read(buffer, 2);
					float width = scale * toUShort(buffer);
					input.read(buffer, 2);
					float height = scale * toUShort(buffer);
					scale /= height;
					widths[i] = width / height;
					input.read(buffer, 2);
					unsigned short numVerts = toUShort(buffer);
					auto_array<float> verts(new float[2 * numVerts]);
					float* verts2 = verts.get();
					for(int j = 0; j < numVerts; j++) {
						input.read(buffer, 2);
						verts2[2 * j] = scale * ((int)toUShort(buffer) - 32768);
						input.read(buffer, 2);
						verts2[2 * j + 1] =
							scale * ((int)toUShort(buffer) - 32768);
					}

					//Face part of the model
					glNewList(displayListId2D + i, GL_COMPILE);

					glNormal3f(0, 0, 1);

					input.read(buffer, 2);
					unsigned short opcode = toUShort(buffer);
					switch(opcode) {
						case OP_TRIANGLES:
							glBegin(GL_TRIANGLES);
							break;
						case OP_TRIANGLE_STRIP:
							glBegin(GL_TRIANGLE_STRIP);
							break;
						default:
							throw T3DLoadException("Invalid font file");
					}

					//Prevents excessive iteration or infinite loops on invalid
					//font files
					int limit = 10000;

					while(true) {
						input.read(buffer, 2);
						opcode = toUShort(buffer);
						switch(opcode) {
							case OP_TRIANGLES:
								glEnd();
								glBegin(GL_TRIANGLES);
								break;
							case OP_TRIANGLE_STRIP:
								glEnd();
								glBegin(GL_TRIANGLE_STRIP);
								break;
							case OP_END_PART:
								goto BreakOuter;
							default:
								glVertex3f(verts2[2 * opcode],
										   verts2[2 * opcode + 1],
										   0);
								break;
						}

						if (--limit == 0) {
							glEndList();
							throw T3DLoadException("Invalid font file");
						}
					}
BreakOuter:
					glEnd();
					glEndList();

					//3D part of the model
					glNewList(displayListId3D + i, GL_COMPILE);
					glPushMatrix();
					glTranslatef(0, 0, 0.5f);
					glFrontFace(GL_CW);
					glCallList(displayListId2D + i);
					glTranslatef(0, 0, -1);
					glScalef(1, 1, -1);
					glFrontFace(GL_CCW);
					glCallList(displayListId2D + i);
					glFrontFace(GL_CW);

					input.read(buffer, 2);
					opcode = toUShort(buffer);
					switch(opcode) {
						case OP_TRIANGLES:
							glBegin(GL_TRIANGLES);
							break;
						case OP_TRIANGLE_STRIP:
							glBegin(GL_TRIANGLE_STRIP);
							break;
						default:
							throw T3DLoadException("Invalid font file");
					}

					limit = 10000;
					while(true) {
						input.read(buffer, 2);
						opcode = toUShort(buffer);
						switch(opcode) {
							case OP_TRIANGLES:
								glEnd();
								glBegin(GL_TRIANGLES);
								break;
							case OP_TRIANGLE_STRIP:
								glEnd();
								glBegin(GL_TRIANGLE_STRIP);
								break;
							case OP_NORMAL:
								input.read(buffer, 2);
								float angle;
								angle = toUShort(buffer) *
									PI_TIMES_2_OVER_65536;
								float x, y;
								x = cos(angle);
								y = sin(angle);
								glNormal3f(x, y, 0);
								break;
							case OP_END_PART:
								goto BreakOuter2;
							default:
								if (opcode < numVerts) {
									glVertex3f(verts2[2 * opcode],
											   verts2[2 * opcode + 1],
											   0);
								}
								else {
									glVertex3f(verts2[2 * (opcode - numVerts)],
											   verts2[2 * (opcode - numVerts) +
													  1],
											   -1);
								}
								break;
						}

						if (--limit == 0) {
							glEndList();
							throw T3DLoadException("Invalid font file");
						}
					}
BreakOuter2:
					glEnd();
					glPopMatrix();
					glEndList();
				}

				if (input.fail()) {
					throw T3DLoadException("Invalid font file");
				}
				input.read(buffer, 1);
				if (!input.eof()) {
					throw T3DLoadException("Invalid font file");
				}
			}

			void draw2D(char c) {
				if (c >= 33 && c <= 126) {
					glCallList(displayListId2D + c - '!');
				}
			}

			void draw3D(char c) {
				if (c >= 33 && c <= 126) {
					glCallList(displayListId3D + c - '!');
				}
			}

			float width(char c) {
				if (c >= 33 && c <= 126) {
					return widths[c - 33];
				}
				else {
					return spaceWidth;
				}
			}
	};

	T3DFont* font = NULL; //The font used to draw 2D and 3D characters

	void draw2D(char c) {
		font->draw2D(c);
	}

	void draw3D(char c) {
		font->draw3D(c);
	}

	void drawLine(const char* str, int hAlign, void (*drawFunc)(char)) {
		glPushMatrix();
		if (hAlign >= 0) {
			float width = 0;
			for(int i = 0; str[i] != '\n' && str[i] != '\0'; i++) {
				width += font->width(str[i]);
			}
			glTranslatef(hAlign > 0 ? -width : -width / 2, 0, 0);
		}

		for(int i = 0; str[i] != '\n' && str[i] != '\0'; i++) {
			float width = font->width(str[i]);
			glTranslatef(width / 2, 0, 0);
			drawFunc(str[i]);
			glTranslatef(width / 2, 0, 0);
		}

		glPopMatrix();
	}

	void draw(const char* str,
			  int hAlign, int vAlign,
			  float lineHeight,
			  void (*drawFunc)(char)) {
		GLint shadeModel;
		glGetIntegerv(GL_SHADE_MODEL, &shadeModel);
		glShadeModel(GL_SMOOTH);
		GLboolean lightsEnabled;
		glGetBooleanv(GL_LIGHTING, &lightsEnabled);
		GLboolean normalsWereNormalized;
		glGetBooleanv(GL_NORMALIZE, &normalsWereNormalized);
		if (lightsEnabled) {
			glEnable(GL_NORMALIZE);
		}
		else {
			glDisable(GL_NORMALIZE);
		}

		glPushMatrix();
		if (vAlign >= 0) {
			int numLines = 1;
			for(int i = 0; str[i] != '\0'; i++) {
				if (str[i] == '\n') {
					numLines++;
				}
			}

			float height = lineHeight * (numLines - 1) + 1;
			glTranslatef(0, vAlign > 0 ? height : height / 2, 0);
		}

		glTranslatef(0, -0.5f, 0);
		drawLine(str, hAlign, drawFunc);
		for(int i = 0; str[i] != '\0'; i++) {
			if (str[i] == '\n') {
				glTranslatef(0, -lineHeight, 0);
				drawLine(str + i + 1, hAlign, drawFunc);
			}
		}

		glPopMatrix();

		glShadeModel(shadeModel);
		if (normalsWereNormalized) {
			glEnable(GL_NORMALIZE);
		}
		else {
			glDisable(GL_NORMALIZE);
		}
	}
}

void t3dInit() {
	if (font == NULL) {
		ifstream input;
		input.open("data/charset", istream::binary);
		font = new T3DFont(input);
		input.close();
	}
}

void t3dCleanup() {
	delete font;
}

void t3dDraw2D(string str, int hAlign, int vAlign, float lineHeight) {
	GLboolean wasCulling;
	glGetBooleanv(GL_CULL_FACE, &wasCulling);
	glDisable(GL_CULL_FACE);

	draw(str.c_str(), hAlign, vAlign, lineHeight, draw2D);

	if (wasCulling) {
		glEnable(GL_CULL_FACE);
	}
}

void t3dDraw3D(string str,
			   int hAlign, int vAlign,
			   float depth,
			   float lineHeight) {
	GLboolean wasCulling;
	glGetBooleanv(GL_CULL_FACE, &wasCulling);
	glEnable(GL_CULL_FACE);
	GLint frontFace;
	glGetIntegerv(GL_FRONT_FACE, &frontFace);

	glPushMatrix();
	glScalef(1, 1, depth);
	draw(str.c_str(), hAlign, vAlign, lineHeight, draw3D);
	glPopMatrix();

	if (!wasCulling) {
		glDisable(GL_CULL_FACE);
	}
	glFrontFace(frontFace);
}

float t3dDrawWidth(string str) {
	float bestWidth = 0;
	int i = 0;
	while (str[i] != '\0') {
		float width = 0;
		while (str[i] != '\n' && str[i] != '\0') {
			width += font->width(str[i]);
			i++;
		}
		if (width > bestWidth) {
			bestWidth = width;
		}
		if (str[i] != '\0') {
			i++;
		}
	}
	return bestWidth;
}

float t3dDrawHeight(string str, float lineHeight) {
	int numLines = 1;
	for(int i = 0; str[i] != '\0'; i++) {
		if (str[i] == '\n') {
			numLines++;
		}
	}

	return (numLines - 1) * lineHeight + 1;
}


text:
var cs = require("coffee-script");

module.exports = require("./time-series");


text:
"""
This is a script written to add the template "orphan" to pages.

These command line parameters can be used to specify which pages to work on:

&params;

-xml              Retrieve information from a local XML dump (pages-articles
                  or pages-meta-current, see https://download.wikimedia.org).
                  Argument can also be given as "-xml:filename".

-page             Only edit a specific page.
                  Argument can also be given as "-page:pagetitle". You can
                  give this parameter multiple times to edit multiple pages.

Furthermore, the following command line parameters are supported:

-enable:          Enable or disable the bot via a Wiki Page.

-disambig:        Set a page where the bot saves the name of the disambig
                  pages found (default: skip the pages)

-limit:           Set how many pages check.

-always           Always say yes, won't ask

--- Examples ---

    python pwb.py lonelypages -enable:User:Bot/CheckBot -always
"""
#
# (C) Pietrodn, it.wiki 2006-2007
# (C) Filnik, it.wiki 2007
# (C) Pywikibot team, 2008-2017
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals

import re
import sys

import pywikibot
from pywikibot import i18n, pagegenerators
from pywikibot.bot import suggest_help, SingleSiteBot

# This is required for the text that is shown when you run this script
# with the parameter -help.
docuReplacements = {
    '&params;': pagegenerators.parameterHelp,
}

class OrphanTemplate(object):

    """The orphan template configuration."""

    def __init__(self, site, name, parameters, aliases=None, subst=False):
        """Constructor."""
        self._name = name
        if not aliases:
            aliases = []
        elif not subst:
            aliases = list(aliases) + [name]
        else:
            name = 'subst:' + name
        if parameters:
            name += '|' + parameters
        self.template = '{{' + name + '}}'
        self._names = frozenset(aliases)

        template_ns = site.namespaces[10]
        # TODO: Add redirects to self.names too
        if not pywikibot.Page(site, self._name, template_ns.id).exists():
            raise ValueError('Orphan template "{0}" does not exist on '
                             '"{1}".'.format(self._name, site))
        for name in self._names:
            if not pywikibot.Page(site, name, template_ns.id).exists():
                pywikibot.warning('Orphan template alias "{0}" does not exist '
                                  'on "{1}"'.format(name, site))
        self.regex = re.compile(
            r'\{\{(?:' + ':|'.join(template_ns) + '|)(' +
            '|'.join(re.escape(name) for name in self._names) +
            r')[\|\}]', re.I)

# The orphan template names in the different languages.
_templates = {
    'ar': ('يتيمة', 'تاريخ={{نسخ:اسم_شهر}} {{نسخ:عام}}'),
    'ca': ('Orfe', 'date={{subst:CURRENTMONTHNAME}} {{subst:CURRENTYEAR}}'),
    'en': ('Orphan', 'date={{subst:CURRENTMONTHNAME}} {{subst:CURRENTYEAR}}', ['wi']),
    'it': ('O', '||mese={{subst:CURRENTMONTHNAME}} {{subst:CURRENTYEAR}}', ['a']),
    'ja': ('孤立', '{{subst:DATE}}'),
    'zh': ('Orphan/auto', '', ['orphan'], True),
}

class LonelyPagesBot(SingleSiteBot):

    """Orphan page tagging bot."""

    def __init__(self, generator, **kwargs):
        """Constructor."""
        self.availableOptions.update({
            'enablePage': None,    # Check if someone set an enablePage or not
            'disambigPage': None,  # If no disambigPage given, not use it.
        })
        super(LonelyPagesBot, self).__init__(**kwargs)
        self.generator = generator

        # Take the configurations according to our project
        if self.getOption('enablePage'):
            self.options['enablePage'] = pywikibot.Page(
                self.site, self.getOption('enablePage'))
        self.comment = i18n.twtranslate(
            self.site, 'lonelypages-comment-add-template')
        self.commentdisambig = i18n.twtranslate(
            self.site, 'lonelypages-comment-add-disambig-template')
        orphan_template = i18n.translate(self.site, _templates)
        if orphan_template is not None:
            try:
                orphan_template = OrphanTemplate(self.site, *orphan_template)
            except ValueError as e:
                orphan_template = e
        if orphan_template is None or isinstance(orphan_template, ValueError):
            err_message = 'Missing configuration for site %s' % self.site
            suggest_help(exception=orphan_template, additional_text=err_message)
            sys.exit(err_message)
        else:
            self._settings = orphan_template
        # DisambigPage part
        if self.getOption('disambigPage') is not None:
            self.disambigpage = pywikibot.Page(self.site, self.getOption('disambigPage'))
            try:
                self.disambigtext = self.disambigpage.get()
            except pywikibot.NoPage:
                pywikibot.output(u"%s doesn't esist, skip!" % self.disambigpage.title())
                self.disambigtext = ''
            except pywikibot.IsRedirectPage:
                pywikibot.output(u"%s is a redirect, don't use it!"
                                 % self.disambigpage.title())
                self.options['disambigPage'] = None

    @property
    def settings(self):
        """Return the settings for the configured site."""
        return self._settings

    def enable_page(self):
        """Enable or disable bot via wiki page."""
        enable = self.getOption('enablePage')
        if enable is not None:
            try:
                getenable = enable.get()
            except pywikibot.NoPage:
                pywikibot.output(
                    u"%s doesn't esist, I use the page as if it was blank!"
                    % enable.title())
                getenable = ''
            except pywikibot.IsRedirectPage:
                pywikibot.output(u"%s is a redirect, skip!" % enable.title())
                getenable = ''
            return getenable == 'enable'
        return True

    def run(self):
        """Run the bot."""
        # If the enable page is set to disable, turn off the bot
        # (useful when the bot is run on a server)
        if not self.enable_page():
            pywikibot.output('The bot is disabled')
            return
        super(LonelyPagesBot, self).run()

    def treat(self, page):
        """Check if page is applicable and not marked and add template then."""
        pywikibot.output(u"Checking %s..." % page.title())
        if page.isRedirectPage():  # If redirect, skip!
            pywikibot.output(u'%s is a redirect! Skip...' % page.title())
            return
        refs = list(page.getReferences(total=1))
        if len(refs) > 0:
            pywikibot.output(u"%s isn't orphan! Skip..." % page.title())
            return
        else:
            # no refs, no redirect; check if there's already the template
            try:
                oldtxt = page.get()
            except pywikibot.NoPage:
                pywikibot.output(u"%s doesn't exist! Skip..." % page.title())
                return
            except pywikibot.IsRedirectPage:
                pywikibot.output(u"%s is a redirect! Skip..." % page.title())
                return
            if self.settings.regex.search(oldtxt):
                pywikibot.output(
                    u'Your regex has found something in %s, skipping...'
                    % page.title())
                return
            if page.isDisambig() and self.getOption('disambigPage') is not None:
                pywikibot.output(u'%s is a disambig page, report..'
                                 % page.title())
                if not page.title().lower() in self.disambigtext.lower():
                    self.disambigtext = u"%s\n*[[%s]]" % (self.disambigtext, page.title())
                    self.disambigpage.text = self.disambigtext
                    self.disambigpage.save(self.commentdisambig)
                    return
            # Is the page a disambig but there's not disambigPage? Skip!
            elif page.isDisambig():
                pywikibot.output(u'%s is a disambig page, skip...'
                                 % page.title())
                return
            else:
                # Ok, the page need the template. Let's put it there!
                # Adding the template in the text
                newtxt = '%s\n%s' % (self.settings.template, oldtxt)
                self.userPut(page, oldtxt, newtxt, summary=self.comment)

def main(*args):
    """
    Process command line arguments and invoke bot.

    If args is an empty list, sys.argv is used.

    @param args: command line arguments
    @type args: list of unicode
    """
    options = {}

    local_args = pywikibot.handle_args(args)
    genFactory = pagegenerators.GeneratorFactory()
    site = pywikibot.Site()

    for arg in local_args:
        if arg.startswith('-enable'):
            if len(arg) == 7:
                options['enablePage'] = pywikibot.input(
                    u'Would you like to check if the bot should run or not?')
            else:
                options['enablePage'] = arg[8:]
        elif arg.startswith('-disambig'):
            if len(arg) == 9:
                options['disambigPage'] = pywikibot.input(
                    u'In which page should the bot save the disambig pages?')
            else:
                options['disambigPage'] = arg[10:]
        elif arg == '-always':
            options['always'] = True
        else:
            genFactory.handleArg(arg)

    generator = genFactory.getCombinedGenerator()

    # If the generator is not given, use the default one
    if not generator:
        generator = site.lonelypages(total=genFactory.limit)

    bot = LonelyPagesBot(generator, **options)
    bot.run()

if __name__ == '__main__':
    main()


text:
'use strict';

var React = require('react');
var sdk = require('matrix-react-sdk')

var MatrixChatController = require('matrix-react-sdk/lib/controllers/pages/MatrixChat')

// should be atomised
var Loader = require("react-loader");

var dis = require('matrix-react-sdk/lib/dispatcher');
var Matrix = require("matrix-js-sdk");
var ContextualMenu = require("../../../../ContextualMenu");

module.exports = React.createClass({
    displayName: 'MatrixChat',
    mixins: [MatrixChatController],

    getInitialState: function() {
        return {
            width: 10000,
        }
    },

    componentDidMount: function() {
        window.addEventListener('resize', this.handleResize);
        this.handleResize();
    },

    componentWillUnmount: function() {
        window.removeEventListener('resize', this.handleResize);
    },

    onAliasClick: function(event, alias) {
        event.preventDefault();
        dis.dispatch({action: 'view_room_alias', room_alias: alias});
    },

    onUserClick: function(event, userId) {
        event.preventDefault();
        var MemberInfo = sdk.getComponent('molecules.MemberInfo');
        var member = new Matrix.RoomMember(null, userId);
        ContextualMenu.createMenu(MemberInfo, {
            member: member,
            right: window.innerWidth - event.pageX,
            top: event.pageY
        });
    },

    handleResize: function(e) {
        var hideLhsThreshold = 1000;
        var showLhsThreshold = 1000;
        var hideRhsThreshold = 820;
        var showRhsThreshold = 820;

        if (this.state.width > hideLhsThreshold && window.innerWidth <= hideLhsThreshold) {
            dis.dispatch({ action: 'hide_left_panel' });
        }
        if (this.state.width <= showLhsThreshold && window.innerWidth > showLhsThreshold) {
            dis.dispatch({ action: 'show_left_panel' });
        }
        if (this.state.width > hideRhsThreshold && window.innerWidth <= hideRhsThreshold) {
            dis.dispatch({ action: 'hide_right_panel' });
        }
        if (this.state.width <= showRhsThreshold && window.innerWidth > showRhsThreshold) {
            dis.dispatch({ action: 'show_right_panel' });
        }

        this.setState({width: window.innerWidth});
    },

    onRoomCreated: function(room_id) {
        dis.dispatch({
            action: "view_room",
            room_id: room_id,
        });
    },

    render: function() {
        var LeftPanel = sdk.getComponent('organisms.LeftPanel');
        var RoomView = sdk.getComponent('organisms.RoomView');
        var RightPanel = sdk.getComponent('organisms.RightPanel');
        var Login = sdk.getComponent('templates.Login');
        var UserSettings = sdk.getComponent('organisms.UserSettings');
        var Register = sdk.getComponent('templates.Register');
        var CreateRoom = sdk.getComponent('organisms.CreateRoom');
        var RoomDirectory = sdk.getComponent('organisms.RoomDirectory');
        var MatrixToolbar = sdk.getComponent('molecules.MatrixToolbar');
        var Notifier = sdk.getComponent('organisms.Notifier');

        if (this.state.logged_in && this.state.ready) {
            var page_element;
            var right_panel = "";

            switch (this.state.page_type) {
                case this.PageTypes.RoomView:
                    page_element = <RoomView roomId={this.state.currentRoom} key={this.state.currentRoom} />
                    right_panel = <RightPanel roomId={this.state.currentRoom} collapsed={this.state.collapse_rhs} />
                    break;
                case this.PageTypes.UserSettings:
                    page_element = <UserSettings />
                    right_panel = <RightPanel collapsed={this.state.collapse_rhs}/>
                    break;
                case this.PageTypes.CreateRoom:
                    page_element = <CreateRoom onRoomCreated={this.onRoomCreated}/>
                    right_panel = <RightPanel collapsed={this.state.collapse_rhs}/>
                    break;
                case this.PageTypes.RoomDirectory:
                    page_element = <RoomDirectory />
                    right_panel = <RightPanel collapsed={this.state.collapse_rhs}/>
                    break;
            }

            // TODO: Fix duplication here and do conditionals like we do above
            if (Notifier.supportsDesktopNotifications() && !Notifier.isEnabled() && !Notifier.isToolbarHidden()) {
                return (

                            <MatrixToolbar />

                                <LeftPanel selectedRoom={this.state.currentRoom} collapsed={this.state.collapse_lhs} />

                                    {page_element}

                                {right_panel}

                );
            }
            else {
                return (

                            <LeftPanel selectedRoom={this.state.currentRoom} collapsed={this.state.collapse_lhs} />

                                {page_element}

                            {right_panel}

                );
            }
        } else if (this.state.logged_in) {
            return (
                <Loader />
            );
        } else if (this.state.screen == 'register') {
            return (
                <Register onLoggedIn={this.onLoggedIn} clientSecret={this.state.register_client_secret}
                    sessionId={this.state.register_session_id} idSid={this.state.register_id_sid}
                    hsUrl={this.state.register_hs_url} isUrl={this.state.register_is_url}
                    registrationUrl={this.props.registrationUrl}
                />
            );
        } else {
            return (
                <Login onLoggedIn={this.onLoggedIn} />
            );
        }
    }
});


text:
require 'rails/generators'

module Anaconda
  class MigrationGenerator < ::Rails::Generators::NamedBase
    desc "Create a migration for the given class name"
    source_root File.expand_path('../templates', __FILE__)

    argument :field_name, :type => :string, :default => "asset"

    def create_migration_file
      destination = "db/migrate/#{Time.now.utc.strftime('%Y%m%d%H%M%S')}_anaconda_migration_for_#{file_name}_#{field_name}.rb".gsub(" ", "")
      migration_name = "AnacondaMigrationFor#{file_name.titlecase}#{field_name.titlecase}".gsub(" ", "")
      count = nil
      i = 1
      while !Dir.glob("db/migrate/*_anaconda_migration_for_#{file_name}_#{field_name}#{count}.rb".gsub(" ", "")).empty?
        i += 1
        count = "_#{i}"
        destination = "db/migrate/#{Time.now.utc.strftime('%Y%m%d%H%M%S')}_anaconda_migration_for_#{file_name}_#{field_name}#{count}.rb".gsub(" ", "")
        migration_name = "AnacondaMigrationFor#{file_name.titlecase}#{field_name.titlecase}#{i}".gsub(" ", "")
      end
      create_file destination, <<-FILE
class #{migration_name} < ActiveRecord::Migration[5.0]
  def change
    add_column :#{plural_name}, :#{field_name}_filename, :string
    add_column :#{plural_name}, :#{field_name}_file_path, :text
    add_column :#{plural_name}, :#{field_name}_size, :integer
    add_column :#{plural_name}, :#{field_name}_original_filename, :text
    add_column :#{plural_name}, :#{field_name}_stored_privately, :boolean
    add_column :#{plural_name}, :#{field_name}_type, :string
  end
end
FILE
    end
  end
end


text:
#include "gcp/util/Constants.h"
#include "gcp/util/Mass.h"
#include "gcp/util/Frequency.h"

using namespace std;
using namespace gcp::util;

const double Mass::gPerKg_ = 1000;

/**.......................................................................
 * Constructor.
 */
Mass::Mass()
{
  initialize();
}

Mass::~Mass() {}

void Mass::initialize(void)
{
  setGrams(0.0);

  addConversion("g",          1.0);
  addConversion("Msolar",     Constants::solarMass_.g());
}

Mass::Mass(const Gram& units, double grams)
{
  setGrams(grams);
}

void Mass::setKg(double kg)
{
  setKiloGrams(kg);
}

void Mass::setKiloGrams(double kg)
{
  setGrams(kg / gPerKg_);
}

void Mass::setGrams(double g)
{
  val_ = g;
}

void Mass::setSolarMass(double mSolar)
{
  setGrams(mSolar * Constants::solarMass_.g());
}

double Mass::solarMass()
{
  return val_ / Constants::solarMass_.g();
}

double Mass::kg()
{
  return val_ / gPerKg_;
}

double Mass::g()
{
  return val_;
}

Energy Mass::energy()
{
  Energy energy;
  energy = *this;
  return energy;
}

void Mass::operator=(const Energy& energy)
{
  operator=((Energy&) energy);
}

void Mass::operator=(Energy& energy)
{
  double c = Constants::lightSpeed_.centimetersPerSec();
  setGrams(energy.ergs() / (c * c));
}

Mass Mass::operator*(double factor)
{
  Mass result;
  result.setGrams(g() * factor);
  return result;
}
void Mass::operator*=(double factor)
{
  val_ = val_ * factor;
}

Mass Mass::operator/(double factor)
{
  Mass result;
  result.setGrams(g() / factor);
  return result;
}
void Mass::operator/=(double factor)
{
  val_ = val_ / factor;
}

bool Mass::operator>(const Mass& mass)
{
  return operator>((Mass&) mass);
}

bool Mass::operator>(Mass& mass)
{
  return val_ > mass.val_;
}

bool Mass::operator>=(const Mass& mass)
{
  return operator>=((Mass&) mass);
}

bool Mass::operator>=(Mass& mass)
{
  return val_ >= mass.val_;
}

bool Mass::operator<(const Mass& mass)
{
  return operator<((Mass&) mass);
}

bool Mass::operator<(Mass& mass)
{
  return val_ < mass.val_;
}

bool Mass::operator<=(const Mass& mass)
{
  return operator<=((Mass&) mass);
}

bool Mass::operator<=(Mass& mass)
{
  return val_ <= mass.val_;
}

Volume Mass::operator/(Density& density)
{
  Volume vol;
  vol.setCubicCentimeters(g() / density.gPerCm3());
  return vol;
}

void Mass::operator=(const Mass& var)
{
  operator=((Mass&) var);
}

void Mass::operator=(Mass& var)
{
  val_ = var.val_;
}


text:
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIASOURCE_MEDIA_SOURCE_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIASOURCE_MEDIA_SOURCE_H_

#include <memory>
#include <tuple>
#include <utility>

#include "base/memory/scoped_refptr.h"
#include "base/synchronization/lock.h"
#include "third_party/blink/public/platform/web_media_source.h"
#include "third_party/blink/renderer/bindings/core/v8/active_script_wrappable.h"
#include "third_party/blink/renderer/core/execution_context/execution_context_lifecycle_observer.h"
#include "third_party/blink/renderer/core/html/media/media_source_tracer.h"
#include "third_party/blink/renderer/core/html/time_ranges.h"
#include "third_party/blink/renderer/modules/event_target_modules.h"
#include "third_party/blink/renderer/modules/mediasource/media_source_attachment_supplement.h"
#include "third_party/blink/renderer/modules/mediasource/media_source_handle_impl.h"
#include "third_party/blink/renderer/modules/mediasource/source_buffer.h"
#include "third_party/blink/renderer/modules/mediasource/source_buffer_list.h"
#include "third_party/blink/renderer/platform/bindings/exception_code.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"

namespace media {
class AudioDecoderConfig;
class VideoDecoderConfig;
}  // namespace media

namespace blink {

class EventQueue;
class ExceptionState;
class HTMLMediaElement;
class CrossThreadMediaSourceAttachment;
class SameThreadMediaSourceAttachment;
class SourceBufferConfig;
class TrackBase;
class WebSourceBuffer;

// Media Source Extensions (MSE) API's MediaSource object implementation (see
// also https://w3.org/TR/media-source/). Web apps can extend an
// HTMLMediaElement's instance to use the MSE API (also known as "attaching MSE
// to a media element") by using a Media Source object URL as the media
// element's src attribute or the src attribute of a <source> inside the media
// element, or by using a MediaSourceHandle for a worker-owned MediaSource as
// the srcObject of the media element. A MediaSourceAttachmentSupplement
// encapsulates the linkage of that object URL or handle to a MediaSource
// instance, and allows communication between the media element and the MSE API.
class MediaSource final : public EventTargetWithInlineData,
                          public ActiveScriptWrappable<MediaSource>,
                          public ExecutionContextLifecycleObserver {
  DEFINE_WRAPPERTYPEINFO();

 public:
  enum class ReadyState { kOpen, kClosed, kEnded };

  static MediaSource* Create(ExecutionContext*);

  explicit MediaSource(ExecutionContext*);
  ~MediaSource() override;

  static void LogAndThrowDOMException(ExceptionState&,
                                      DOMExceptionCode error,
                                      const String& message);
  static void LogAndThrowTypeError(ExceptionState&, const String&);

  // Web-exposed methods from media_source.idl
  SourceBufferList* sourceBuffers() { return source_buffers_.Get(); }
  SourceBufferList* activeSourceBuffers() {
    return active_source_buffers_.Get();
  }
  SourceBuffer* addSourceBuffer(const String& type, ExceptionState&)
      LOCKS_EXCLUDED(attachment_link_lock_);
  SourceBuffer* AddSourceBufferUsingConfig(ExecutionContext* execution_context,
                                           const SourceBufferConfig*,
                                           ExceptionState&)
      LOCKS_EXCLUDED(attachment_link_lock_);
  void removeSourceBuffer(SourceBuffer*, ExceptionState&)
      LOCKS_EXCLUDED(attachment_link_lock_);
  void setDuration(double, ExceptionState&)
      LOCKS_EXCLUDED(attachment_link_lock_);
  double duration() LOCKS_EXCLUDED(attachment_link_lock_);

  DEFINE_ATTRIBUTE_EVENT_LISTENER(sourceopen, kSourceopen)
  DEFINE_ATTRIBUTE_EVENT_LISTENER(sourceended, kSourceended)
  DEFINE_ATTRIBUTE_EVENT_LISTENER(sourceclose, kSourceclose)

  AtomicString readyState() const;
  void endOfStream(const AtomicString& error, ExceptionState&)
      LOCKS_EXCLUDED(attachment_link_lock_);
  void endOfStream(ExceptionState&) LOCKS_EXCLUDED(attachment_link_lock_);
  void setLiveSeekableRange(double start, double end, ExceptionState&)
      LOCKS_EXCLUDED(attachment_link_lock_);
  void clearLiveSeekableRange(ExceptionState&)
      LOCKS_EXCLUDED(attachment_link_lock_);

  MediaSourceHandleImpl* handle() LOCKS_EXCLUDED(attachment_link_lock_);

  static bool isTypeSupported(ExecutionContext* context, const String& type);

  // Helper for isTypeSupported, addSourceBuffer and SourceBuffer changeType.
  // Set |enforce_codec_specificity| true to require fully specified mime and
  // codecs, false otherwise.
  // TODO(https://crbug.com/535738): When |enforce_codec_specificity| is set to
  // false, then fully relax codec requirements.
  static bool IsTypeSupportedInternal(ExecutionContext* context,
                                      const String& type,
                                      bool enforce_codec_specificity);

  static bool canConstructInDedicatedWorker(ExecutionContext* context);

  // Methods needed by a MediaSourceAttachmentSupplement to service operations
  // proxied from an HTMLMediaElement.
  MediaSourceTracer* StartAttachingToMediaElement(
      scoped_refptr<SameThreadMediaSourceAttachment> attachment,
      HTMLMediaElement* element) LOCKS_EXCLUDED(attachment_link_lock_);
  // Same method as above, but for starting an attachment when we are
  // MSE-in-Workers and therefore using a CrossThreadMediaSourceAttachment.
  // Returns true iff successfully started. Even in this case, this method is
  // called on the main thread and operates synchronously throughout.
  bool StartWorkerAttachingToMainThreadMediaElement(
      scoped_refptr<CrossThreadMediaSourceAttachment> attachment)
      LOCKS_EXCLUDED(attachment_link_lock_);
  // Completing the attachment always occurs on the thread/context that owns
  // this MediaSource.
  void CompleteAttachingToMediaElement(std::unique_ptr<WebMediaSource>)
      LOCKS_EXCLUDED(attachment_link_lock_);
  void Close();
  bool IsClosed() const;
  double GetDuration_Locked(
      MediaSourceAttachmentSupplement::ExclusiveKey /* passkey */) const
      LOCKS_EXCLUDED(attachment_link_lock_);
  WebTimeRanges BufferedInternal(
      MediaSourceAttachmentSupplement::ExclusiveKey /* passkey */) const
      LOCKS_EXCLUDED(attachment_link_lock_);
  WebTimeRanges SeekableInternal(
      MediaSourceAttachmentSupplement::ExclusiveKey /* passkey */) const
      LOCKS_EXCLUDED(attachment_link_lock_);
  void OnTrackChanged(TrackBase*);

  // EventTarget interface
  const AtomicString& InterfaceName() const override;
  ExecutionContext* GetExecutionContext() const override;

  // ScriptWrappable
  bool HasPendingActivity() const final;

  // ExecutionContextLifecycleObserver interface
  void ContextDestroyed() override LOCKS_EXCLUDED(attachment_link_lock_);

  // Methods used by SourceBuffer.
  //
  // OpenIfInEndedState must not be called when IsClosed() is true. Furthermore,
  // the caller must ensure this is only called from the attachment's
  // RunExclusively() callback.
  void OpenIfInEndedState() LOCKS_EXCLUDED(attachment_link_lock_);
  bool IsOpen() const;
  void SetSourceBufferActive(SourceBuffer*, bool);
  std::pair<scoped_refptr<MediaSourceAttachmentSupplement>, MediaSourceTracer*>
  AttachmentAndTracer() const LOCKS_EXCLUDED(attachment_link_lock_);
  // EndOfStreamAlgorithm must not be called when IsClosed() is true.
  // Furthermore, the caller must ensure this is only called from the
  // attachment's RunExclusively() callback.
  void EndOfStreamAlgorithm(
      const WebMediaSource::EndOfStreamStatus,
      MediaSourceAttachmentSupplement::ExclusiveKey pass_key)
      LOCKS_EXCLUDED(attachment_link_lock_);

  // Helper to run operations while holding cross-thread attachment's exclusive
  // |attachment_state_lock_|. This is used for safe cross-thread operation when
  // MSE is in worker context, especially when accessing underlying demuxer.
  // Returns true if |cb| was run. Returns false if |cb| was not run (because
  // the element is gone or is closing us). Caller must ensure that we
  // currently have an attachment (typically by checking that our readyState is
  // not closed, or similar).
  bool RunUnlessElementGoneOrClosingUs(
      MediaSourceAttachmentSupplement::RunExclusivelyCB cb)
      LOCKS_EXCLUDED(attachment_link_lock_);

  // Helper to verify cross-thread attachment's |attachment_state_lock_| mutex
  // is acquired whenever we are accessing the underlying demuxer.
  void AssertAttachmentsMutexHeldIfCrossThreadForDebugging() const
      LOCKS_EXCLUDED(attachment_link_lock_);

  // Helper to tell the attachment to send updated buffered and seekable
  // information to the media element if cross-thread.
  void SendUpdatedInfoToMainThreadCache() LOCKS_EXCLUDED(attachment_link_lock_);

  void Trace(Visitor*) const override LOCKS_EXCLUDED(attachment_link_lock_);

 private:
  // Helpers used as bound callbacks with RunExclusively() or
  // RunUnlessElementGoneOrClosingUs() because they access underlying demuxer
  // resources owned by the main thread. Other methods without "_Locked" may
  // also require the same, since they can be called from within these methods.
  void AddSourceBuffer_Locked(
      const String& type /* in */,
      std::unique_ptr<media::AudioDecoderConfig> audio_config /* in */,
      std::unique_ptr<media::VideoDecoderConfig> video_config /* in */,
      ExceptionState* exception_state /* in/out */,
      SourceBuffer** created_buffer /* out */,
      MediaSourceAttachmentSupplement::ExclusiveKey /* passkey */)
      LOCKS_EXCLUDED(attachment_link_lock_);
  void RemoveSourceBuffer_Locked(
      SourceBuffer* buffer /* in */,
      MediaSourceAttachmentSupplement::ExclusiveKey /* passkey */)
      LOCKS_EXCLUDED(attachment_link_lock_);
  void SetLiveSeekableRange_Locked(
      double start,
      double end,
      MediaSourceAttachmentSupplement::ExclusiveKey /* passkey */)
      LOCKS_EXCLUDED(attachment_link_lock_);
  void ClearLiveSeekableRange_Locked(
      MediaSourceAttachmentSupplement::ExclusiveKey /* passkey */)
      LOCKS_EXCLUDED(attachment_link_lock_);
  void DetachWorkerOnContextDestruction_Locked(
      bool notify_close,
      MediaSourceAttachmentSupplement::ExclusiveKey /* passkey */)
      LOCKS_EXCLUDED(attachment_link_lock_);

  // Other helpers.
  void SetReadyState(const ReadyState state)
      LOCKS_EXCLUDED(attachment_link_lock_);
  void OnReadyStateChange(const ReadyState old_state,
                          const ReadyState new_state)
      LOCKS_EXCLUDED(attachment_link_lock_);

  bool IsUpdating() const;

  std::unique_ptr<WebSourceBuffer> CreateWebSourceBuffer(
      const String& type,
      const String& codecs,
      std::unique_ptr<media::AudioDecoderConfig> audio_config,
      std::unique_ptr<media::VideoDecoderConfig> video_config,
      ExceptionState&) LOCKS_EXCLUDED(attachment_link_lock_);
  void ScheduleEvent(const AtomicString& event_name);
  static void RecordIdentifiabilityMetric(ExecutionContext* context,
                                          const String& type,
                                          bool result);

  // Implements the duration change algorithm.
  // http://w3c.github.io/media-source/#duration-change-algorithm
  void DurationChangeAlgorithm(
      double new_duration,
      ExceptionState*,
      MediaSourceAttachmentSupplement::ExclusiveKey pass_key)
      LOCKS_EXCLUDED(attachment_link_lock_);

  // Usage of |*web_media_source_| must be within scope of attachment's
  // RunExclusively() callback to prevent potential UAF of underlying demuxer
  // resources when MSE is in worker thread. Setting it or resetting it do not
  // require being in that critical section though.
  // TODO(https://crbug.com/878133): Add comment to blink::WebMediaSource and
  // blink::WebSourceBuffer to indicate which methods (currently only their
  // destructors) are safe to be called from MSE-in-Worker unless measures such
  // as the CrossThreadMediaSourceAttachment's RunExclusively() callback are
  // ensuring the underlying demuxer is still alive.
  std::unique_ptr<WebMediaSource> web_media_source_;

  ReadyState ready_state_;
  Member<EventQueue> async_event_queue_;

  // Keep the attached element (via attachment_tracer_), |source_buffers_|,
  // |active_source_buffers_|, and their wrappers from being collected if we are
  // alive or traceable from a GC root. Activity by this MediaSource or on
  // references to objects returned by exercising this MediaSource (such as an
  // app manipulating a SourceBuffer retrieved via activeSourceBuffers()) may
  // cause events to be dispatched by these other objects.
  // |media_source_attachment_| and |attachment_tracer_| must be carefully set
  // and reset: the actual derived type of the attachment (same-thread vs
  // cross-thread, for instance) must be the same semantic as the actual derived
  // type of the tracer. Further, if there is no attachment, then there must be
  // no tracer that's tracking an active attachment.
  scoped_refptr<MediaSourceAttachmentSupplement> media_source_attachment_
      GUARDED_BY(attachment_link_lock_);
  Member<MediaSourceTracer> attachment_tracer_
      GUARDED_BY(attachment_link_lock_);
  bool context_already_destroyed_ GUARDED_BY(attachment_link_lock_);

  Member<MediaSourceHandleImpl> worker_media_source_handle_;

  // |attachment_link_lock_| protects read/write of |media_source_attachment_|,
  // |attachment_tracer_|, |context_already_destroyed_|, and execution of
  // handle().
  // It is only truly necessary for CrossThreadAttachment usage of worker MSE,
  // to prevent read/write collision on main thread versus worker thread. Note
  // that |attachment_link_lock_| must be released before attempting
  // CrossThreadMediaSourceAttachment RunExclusively() to avoid deadlock. Many
  // scenarios initiated by worker thread need to get the attachment to be able
  // to invoke operations on it. The attachment then takes internal
  // |attachment_state_lock_|and verifies state. Note that between releasing
  // |attachment_link_lock_| and the RunExclusively() operation on the
  // attachment taking its internal |attachment_state_lock_|, the attachment
  // state could have changed, but the attachment understands how to resolve
  // such cases.  Note that |web_media_source_| and child SourceBuffers'
  // |web_source_buffer_|s usage are protected by only being attempted in scope
  // of a RunExclusively callback (to prevent usage of them if the underlying
  // demuxer owned by the main thread is no longer available).
  // TODO(https://crbug.com/878133): Consider optimizing away (e.g., using
  // macros, conditional logic, or virtual implementations) usage of
  // |attachment_link_lock_| and
  // callbacks for RunExclusively, when using SameThreadMediaSourceAttachment,
  // on main thread).
  mutable base::Lock attachment_link_lock_;

  Member<SourceBufferList> source_buffers_;
  Member<SourceBufferList> active_source_buffers_;

  // These are kept as raw data (not an Oilpan managed GC-able TimeRange) to
  // avoid need to take lock during ::Trace, which could lead to deadlock. They
  // are updated or read only while the attachment's internal lock is held
  // (during the scope of a RunExclusively callback, for example).
  bool has_live_seekable_range_;
  double live_seekable_range_start_;
  double live_seekable_range_end_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIASOURCE_MEDIA_SOURCE_H_


text:
package org.cuacfm.members.test.model.feemember;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import java.util.List;

import org.cuacfm.members.model.account.Account;
import org.cuacfm.members.model.account.Account.roles;
import org.cuacfm.members.model.accountservice.AccountService;
import org.cuacfm.members.model.accounttype.AccountType;
import org.cuacfm.members.model.accounttypeservice.AccountTypeService;
import org.cuacfm.members.model.exceptions.UniqueException;
import org.cuacfm.members.model.exceptions.UniqueListException;
import org.cuacfm.members.model.feemember.FeeMember;
import org.cuacfm.members.model.feememberservice.FeeMemberService;
import org.cuacfm.members.model.methodpayment.MethodPayment;
import org.cuacfm.members.model.methodpaymentservice.MethodPaymentService;
import org.cuacfm.members.model.paymemberservice.PayMemberService;
import org.cuacfm.members.model.util.DateUtils;
import org.cuacfm.members.test.config.WebSecurityConfigurationAware;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

/** The Class rainingTypeServiceTest. */
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
public class FeeMemberServiceTest extends WebSecurityConfigurationAware {

	/** The training service. */
	@Autowired
	private FeeMemberService feeMemberService;

	/** The training service. */
	@Autowired
	private PayMemberService payMemberService;

	/** The account service. */
	@Autowired
	private AccountService accountService;

	/** The account type service. */
	@Autowired
	private AccountTypeService accountTypeService;

	/** The method payment service. */
	@Autowired
	private MethodPaymentService methodPaymentService;

	/**
	 * Save and find by FeeMember test.
	 *
	 * @throws UniqueListException
	 */
	@Test
	public void saveFeeMemberTest() throws UniqueException, UniqueListException {

		// Save
		FeeMember feeMember = new FeeMember("pay of 2015", 2015, Double.valueOf(20), DateUtils.format("2015-04-05", DateUtils.FORMAT_DATE),
				DateUtils.format("2015-07-05", DateUtils.FORMAT_DATE), "pay of 2015");
		feeMemberService.save(feeMember);

		// findById
		FeeMember feeMemberSearch = feeMemberService.findById(feeMember.getId());
		assertEquals(feeMember, feeMemberSearch);
	}

	/**
	 * Save and find by FeeMember test.
	 *
	 * @throws UniqueListException
	 */
	@Test
	public void saveFeeMemberWithUsersTest() throws UniqueException, UniqueListException {
		AccountType accountType = new AccountType("Adult", false, "Fee for adults", 0);
		accountTypeService.save(accountType);
		MethodPayment methodPayment = new MethodPayment("cash", false, "cash");
		methodPaymentService.save(methodPayment);

		Account user = new Account("user", "1", "55555555C", "London", "user", "email1@udc.es", "666666666", "666666666", "demo", roles.ROLE_USER);
		accountService.save(user);
		user.setAccountType(accountType);
		user.setMethodPayment(methodPayment);
		user.setInstallments(1);
		accountService.update(user, false, true);

		Account user2 = new Account("user2", "2", "11111111C", "London", "user2", "email2@udc.es", "666666666", "666666666", "demo", roles.ROLE_USER);
		accountService.save(user2);

		// Save
		FeeMember feeMember = new FeeMember("pay of 2015", 2015, Double.valueOf(20), DateUtils.format("2015-04-05", DateUtils.FORMAT_DATE),
				DateUtils.format("2015-07-05", DateUtils.FORMAT_DATE), "pay of 2015");
		feeMemberService.save(feeMember);

		// findById
		FeeMember feeMemberSearch = feeMemberService.findById(feeMember.getId());
		assertEquals(feeMember, feeMemberSearch);

		assertEquals(payMemberService.getPayMemberListByFeeMemberId(feeMember.getId()).size(), 2);
	}

	/**
	 * Save and find by FeeMember test.
	 *
	 * @throws UniqueListException
	 */
	@Test(expected = UniqueException.class)
	public void saveFeeMemberExceptionTest() throws UniqueException, UniqueListException {

		// Save
		FeeMember feeMember = new FeeMember("pay of 2015", 2015, Double.valueOf(20), DateUtils.format("2015-04-05", DateUtils.FORMAT_DATE),
				DateUtils.format("2015-07-05", DateUtils.FORMAT_DATE), "pay of 2015");
		feeMemberService.save(feeMember);
		FeeMember feeMember2 = new FeeMember("pay of 2016", 2015, Double.valueOf(20), DateUtils.format("2016-04-05", DateUtils.FORMAT_DATE),
				DateUtils.format("2016-07-05", DateUtils.FORMAT_DATE), "pay of 2016");
		feeMemberService.save(feeMember2);

		// findById
		FeeMember feeMemberSearch = feeMemberService.findById(feeMember.getId());
		assertEquals(feeMember, feeMemberSearch);
	}

	/**
	 * Save and find by FeeMember test.
	 *
	 * @throws UniqueListException
	 */
	@Test
	public void savePayMemberTest() throws UniqueException, UniqueListException {

		// Save
		FeeMember feeMember = new FeeMember("pay of 2015", 2015, Double.valueOf(20), DateUtils.format("2015-04-05", DateUtils.FORMAT_DATE),
				DateUtils.format("2015-07-05", DateUtils.FORMAT_DATE), "pay of 2015");
		feeMemberService.save(feeMember);

		AccountType accountType = new AccountType("Adult", false, "Fee for adults", 0);
		accountTypeService.save(accountType);
		MethodPayment methodPayment = new MethodPayment("cash", false, "cash");
		methodPaymentService.save(methodPayment);

		Account user = new Account("user", "1", "11111111C", "London", "user", "email1@udc.es", "666666666", "666666666", "demo", roles.ROLE_USER);
		accountService.save(user);
		user.setAccountType(accountType);
		user.setMethodPayment(methodPayment);
		user.setInstallments(1);
		accountService.update(user, false, true);
		feeMemberService.savePayMember(user, feeMember);

		Account user2 = new Account("user2", "2", "22222222C", "London", "user2", "email2@udc.es", "666666666", "666666666", "demo", roles.ROLE_USER);
		accountService.save(user2);
		user.setInstallments(2);
		accountService.update(user2, false, true);
		feeMemberService.savePayMember(user2, feeMember);

		Account user3 = new Account("user3", "3", "33333333C", "London", "user3", "email3@udc.es", "666666666", "666666666", "demo", roles.ROLE_USER);
		accountService.save(user3);
		user.setInstallments(3);
		accountService.update(user3, false, true);
		feeMemberService.savePayMember(user3, feeMember);

		Account user4 = new Account("user4", "4", "44444444C", "London", "user4", "email4@udc.es", "666666666", "666666666", "demo", roles.ROLE_USER);
		accountService.save(user4);
		user.setInstallments(4);
		accountService.update(user4, false, true);
		feeMemberService.savePayMember(user4, feeMember);

		Account user5 = new Account("user5", "5", "55555555C", "London", "user5", "email5@udc.es", "666666666", "666666666", "demo", roles.ROLE_USER);
		accountService.save(user5);
		user.setInstallments(5);
		accountService.update(user5, false, false);
		feeMemberService.savePayMember(user5, feeMember);

		Account user6 = new Account("user6", "6", "66666666C", "London", "user6", "email6@udc.es", "666666666", "666666666", "demo", roles.ROLE_USER);
		accountService.save(user6);
		user.setInstallments(6);
		accountService.update(user6, false, true);
		feeMemberService.savePayMember(user6, feeMember);

		Account user7 = new Account("user7", "7", "77777777C", "London", "user7", "email7@udc.es", "666666666", "666666666", "demo", roles.ROLE_USER);
		accountService.save(user7);
		user.setInstallments(7);
		accountService.update(user7, false, true);
		feeMemberService.savePayMember(user7, feeMember);

		Account user0 = new Account("user0", "8", "00000000C", "London", "user0", "email0@udc.es", "666666666", "666666666", "demo", roles.ROLE_USER);
		accountService.save(user0);
		user.setInstallments(0);
		accountService.update(user7, false, true);
		feeMemberService.savePayMember(user0, feeMember);

		// findById

		FeeMember feeMemberSearch = feeMemberService.findById(feeMember.getId());
		assertEquals(feeMember, feeMemberSearch);
	}

	/**
	 * Update
	 *
	 * @throws UniqueListException
	 */
	@Test
	public void UpdateFeeMemberTest() throws UniqueException, UniqueListException {

		// Save
		FeeMember feeMember = new FeeMember("pay of 2015", 2015, Double.valueOf(20), DateUtils.format("2015-04-05", DateUtils.FORMAT_DATE),
				DateUtils.format("2015-07-05", DateUtils.FORMAT_DATE), "pay of 2015");
		feeMemberService.save(feeMember);

		// Update
		feeMember.setName("pay of 1016");
		feeMember.setYear(2016);
		feeMember.setPrice(Double.valueOf(25));
		feeMember.setDescription("pay of 2016, tax for members");
		feeMemberService.update(feeMember);

		// Assert
		FeeMember feeMemberSearch = feeMemberService.findById(feeMember.getId());
		assertEquals(feeMember, feeMemberSearch);
		assertEquals(feeMember.getName(), feeMemberSearch.getName());
		assertEquals(feeMember.getYear(), feeMemberSearch.getYear());
		assertEquals(feeMember.getPrice(), feeMemberSearch.getPrice());
		assertEquals(feeMember.getDescription(), feeMemberSearch.getDescription());

		FeeMember feeMember2 = new FeeMember("pay of 2018", 2018, Double.valueOf(20), DateUtils.format("2018-04-05", DateUtils.FORMAT_DATE),
				DateUtils.format("2018-07-05", DateUtils.FORMAT_DATE), "pay of 2018");
		feeMemberService.update(feeMember2);
	}

	/**
	 * Update Inscription Exception
	 *
	 * @throws UniqueListException
	 */
	@Test(expected = UniqueException.class)
	public void UpdateFeeMemberExceptionTest() throws UniqueException, UniqueListException {

		// Save
		FeeMember feeMember = new FeeMember("pay of 2015", 2015, Double.valueOf(20), DateUtils.format("2015-04-05", DateUtils.FORMAT_DATE),
				DateUtils.format("2015-07-05", DateUtils.FORMAT_DATE), "pay of 2015");
		feeMemberService.save(feeMember);
		FeeMember feeMember2 = new FeeMember("pay of 2016", 2016, Double.valueOf(20), DateUtils.format("2016-04-05", DateUtils.FORMAT_DATE),
				DateUtils.format("2016-07-05", DateUtils.FORMAT_DATE), "pay of 2016");
		feeMemberService.save(feeMember2);

		// Update
		FeeMember feeMember3 = new FeeMember("pay of 2016", 2016, Double.valueOf(20), DateUtils.format("2016-04-05", DateUtils.FORMAT_DATE),
				DateUtils.format("2016-07-05", DateUtils.FORMAT_DATE), "pay of 2016");
		feeMemberService.update(feeMember3);
	}

	/**
	 * findByName test.
	 *
	 * @throws UniqueListException
	 */
	@Test
	public void findByNameTest() throws UniqueException, UniqueListException {

		// Save
		FeeMember feeMember = new FeeMember("pay of 2015", 2015, Double.valueOf(20), DateUtils.format("2015-04-05", DateUtils.FORMAT_DATE),
				DateUtils.format("2015-07-05", DateUtils.FORMAT_DATE), "pay of 2015");
		feeMemberService.save(feeMember);

		// findByName
		FeeMember feeMemberSearch = feeMemberService.findByName(feeMember.getName());
		assertEquals(feeMember, feeMemberSearch);

		feeMemberService.findByName(feeMember.getName());
		assertNull(feeMemberService.findByName("do not exist"));
	}

	/**
	 * findByYear test.
	 *
	 * @throws UniqueListException
	 */
	@Test
	public void findByYearTest() throws UniqueException, UniqueListException {

		// Save
		FeeMember feeMember = new FeeMember("pay of 2015", 2015, Double.valueOf(20), DateUtils.format("2015-04-05", DateUtils.FORMAT_DATE),
				DateUtils.format("2015-07-05", DateUtils.FORMAT_DATE), "pay of 2015");
		feeMemberService.save(feeMember);

		// findByName
		FeeMember feeMemberSearch = feeMemberService.findByYear(feeMember.getYear());
		assertEquals(feeMember, feeMemberSearch);
	}

	/**
	 * getFeeMemberList test.
	 *
	 * @throws UniqueListException
	 */
	@Test
	public void getFeeMemberListTest() throws UniqueException, UniqueListException {

		// getFeeMemberList, no FeeMembers
		List<FeeMember> feeMemberList = feeMemberService.getFeeMemberList();
		// Assert
		assertTrue(feeMemberList.isEmpty());

		// Save
		FeeMember feeMember = new FeeMember("pay of 2015", 2015, Double.valueOf(20), DateUtils.format("2015-04-05", DateUtils.FORMAT_DATE),
				DateUtils.format("2015-07-05", DateUtils.FORMAT_DATE), "pay of 2015");
		feeMemberService.save(feeMember);
		FeeMember feeMember2 = new FeeMember("pay of 2016", 2016, Double.valueOf(20), DateUtils.format("2016-04-05", DateUtils.FORMAT_DATE),
				DateUtils.format("2016-07-05", DateUtils.FORMAT_DATE), "pay of 2016");
		feeMemberService.save(feeMember2);

		// getFeeMemberList
		feeMemberList = feeMemberService.getFeeMemberList();
		// Assert
		assertEquals(feeMemberList.size(), 2);
	}
}


text:
namespace tensorflow {
namespace boosted_trees {
namespace testutil {

// This method calls Initialize on the given 'batch_features', which will be
// populated with randomly generated feature values when the call returns.
// 'tensors' returns a vector of all tensors used in the initialization,
// because they must outlive 'batch_features'.
//
// All float features will be either missing or uniformly randomly chosen
// from [0, 1). For sparse (float) features, a sparsity is uniformly randomly
// chosen from ['sparsity_lo', 'sparsity_hi') per feature, and each instance
// will have a probability of sparsity of missing that feature, in other words,
// sparsity = 1 - density.
void RandomlyInitializeBatchFeatures(
    tensorflow::random::SimplePhilox* rng, uint32 num_dense_float_features,
    uint32 num_sparse_float_features, double sparsity_lo, double sparsity_hi,
    boosted_trees::utils::BatchFeatures* batch_features);

}  // namespace testutil
}  // namespace boosted_trees
}  // namespace tensorflow

#endif  // TENSORFLOW_CONTRIB_BOOSTED_TREES_LIB_TESTUTIL_BATCH_FEATURES_TESTUTIL_H_


text:
import enum

APPLICATION_JSON         = 'application/json'

def non_null(obj, defValue):
    return obj if obj is not None else defValue

def type_coerce(obj, objType):
    if isinstance(obj, objType):
        ret = obj
    elif isinstance(obj, dict):
        ret = objType(obj)

        ret.type_coerce_attrs()
    else:
        ret = None

    return ret

def type_coerce_list(obj, objType):
    if isinstance(obj, list):
        ret = []
        for entry in obj:
            ret.append(type_coerce(entry, objType))
    else:
        ret = None

    return ret

def type_coerce_dict(obj, objType):
    if isinstance(obj, dict):
        ret = {}
        for k, v in obj.items():
            ret[k] = type_coerce(v, objType)
    else:
        ret = None

    return ret

def type_coerce_dict_list(obj, objType):
    if isinstance(obj, dict):
        ret = {}
        for k, v in obj.items():
            ret[k] = type_coerce_list(v, objType)
    else:
        ret = None

    return ret

class API:
    def __init__(self, path, method, expected_status, consumes=APPLICATION_JSON, produces=APPLICATION_JSON):
        self.path            = path
        self.method          = method
        self.expected_status = expected_status
        self.consumes        = consumes
        self.produces        = produces

    def format_path(self, params):
        return API(self.path.format(**params), self.method, self.expected_status, self.consumes, self.produces)

class HttpMethod(enum.Enum):
    GET    = "GET"
    PUT    = "PUT"
    POST   = "POST"
    DELETE = "DELETE"

class HTTPStatus:
    OK                  = 200
    NO_CONTENT          = 204
    SERVICE_UNAVAILABLE = 503


text:
import { Test } from '@nestjs/testing';
import { NotFoundException } from '@nestjs/common';
import { AffiliationController } from './affiliation.controller';
import { AffiliationService } from './affiliation.service';

describe('AffiliationController', () => {
  let controller: AffiliationController;
  let service: AffiliationService;

  beforeEach(async () => {
    const module = await Test.createTestingModule({
      controllers: [AffiliationController],
      components: [AffiliationService]
    }).compile();

    service = module.get<AffiliationService>(AffiliationService);
    controller = module.get<AffiliationController>(AffiliationController);
  });

  describe('getAll', () => {
    it('should return an empty array', async () => {
      const result = [];
      jest.spyOn(service, 'query').mockImplementation(() => result);

      expect(await controller.getAll()).toBe(result);
    });
  });

  describe('getById', () => {
    it('throws NotFoundException on user undefined', async () => {
      expect.assertions(1);

      jest.spyOn(service, 'getAffiliation').mockImplementation(() => undefined);

      try {
        await controller.getById(1);
      } catch (e) {
        expect(e).toEqual(new NotFoundException());
      }
    });
  });
});