text:
;(function() {

    var _isa = function(a) { return Object.prototype.toString.call(a) === "[object Array]"; },
        _isnum = function(n) { return Object.prototype.toString.call(n) === "[object Number]"; },
        _iss = function(s) { return typeof s === "string"; },
        _isb = function(s) { return typeof s === "boolean"; },
        _isnull = function(s) { return s == null; },
        _iso = function(o) { return o == null ? false : Object.prototype.toString.call(o) === "[object Object]"; },
        _isd = function(o) { return Object.prototype.toString.call(o) === "[object Date]"; },
        _isf = function(o) { return Object.prototype.toString.call(o) === "[object Function]"; },
        _ise = function(o) {
            for (var i in o) { if (o.hasOwnProperty(i)) return false; }
            return true;
        },
        pointHelper = function(p1, p2, fn) {
            p1 = _isa(p1) ? p1 : [p1.x, p1.y];
            p2 = _isa(p2) ? p2 : [p2.x, p2.y];
            return fn(p1, p2);
        };

    jsPlumbUtil = {
        isArray : _isa,
        isString : _iss,
        isBoolean: _isb,
        isNull : _isnull,
        isObject : _iso,
        isDate : _isd,
        isFunction: _isf,
        isEmpty:_ise,
        isNumber:_isnum,
        clone : function(a) {
            if (_iss(a)) return "" + a;
            else if (_isb(a)) return !!a;
            else if (_isd(a)) return new Date(a.getTime());
            else if (_isf(a)) return a;
            else if (_isa(a)) {
                var b = [];
                for (var i = 0; i < a.length; i++)
                    b.push(this.clone(a[i]));
                return b;
            }
            else if (_iso(a)) {
                var c = {};
                for (var j in a)
                    c[j] = this.clone(a[j]);
                return c;
            }
            else return a;
        },
        merge : function(a, b) {
            var c = this.clone(a);
            for (var i in b) {
                if (c[i] == null || _iss(b[i]) || _isb(b[i]))
                    c[i] = b[i];
                else {
                    if (_isa(b[i])/* && this.isArray(c[i])*/) {
                        var ar = [];
                        // if c's object is also an array we can keep its values.
                        if (_isa(c[i])) ar.push.apply(ar, c[i]);
                        ar.push.apply(ar, b[i]);
                        c[i] = ar;
                    }
                    else if(_iso(b[i])) {
                        // overwite c's value with an object if it is not already one.
                        if (!_iso(c[i]))
                            c[i] = {};
                        for (var j in b[i])
                            c[i][j] = b[i][j];
                    }
                }
            }
            return c;
        },
        copyValues:function(names, from, to) {
            for (var i = 0; i < names.length; i++)
                to[names[i]] = from[names[i]];
        },
        //
        // chain a list of functions, supplied by [ object, method name, args ], and return on the first
        // one that returns the failValue. if none return the failValue, return the successValue.
        //
        functionChain : function(successValue, failValue, fns) {
            for (var i = 0; i < fns.length; i++) {
                var o = fns[i][0][fns[i][1]].apply(fns[i][0], fns[i][2]);
                if (o === failValue) {
                    return o;
                }
            }
            return successValue;
        },
        // take the given model and expand out any parameters.
        populate : function(model, values) {
            // for a string, see if it has parameter matches, and if so, try to make the substitutions.
            var getValue = function(fromString) {
                    var matches = fromString.match(/(\${.*?})/g);
                    if (matches != null) {
                        for (var i = 0; i < matches.length; i++) {
                            var val = values[matches[i].substring(2, matches[i].length - 1)];
                            if (val != null) {
                                fromString = fromString.replace(matches[i], val);
                            }
                        }
                    }
                    return fromString;
                },
                // process one entry.
                _one = function(d) {
                    if (d != null) {
                        if (_iss(d)) {
                            return getValue(d);
                        }
                        else if (_isa(d)) {
                            var r = [];
                            for (var i = 0; i < d.length; i++)
                                r.push(_one(d[i]));
                            return r;
                        }
                        else if (_iso(d)) {
                            var s = {};
                            for (var j in d) {
                                s[j] = _one(d[j]);
                            }
                            return s;
                        }
                        else {
                            return d;
                        }
                    }
                };

            return _one(model);
        },
        convertStyle : function(s, ignoreAlpha) {
            // TODO: jsPlumb should support a separate 'opacity' style member.
            if ("transparent" === s) return s;
            var o = s,
                pad = function(n) { return n.length == 1 ? "0" + n : n; },
                hex = function(k) { return pad(Number(k).toString(16)); },
                pattern = /(rgb[a]?\()(.*)(\))/;
            if (s.match(pattern)) {
                var parts = s.match(pattern)[2].split(",");
                o = "#" + hex(parts[0]) + hex(parts[1]) + hex(parts[2]);
                if (!ignoreAlpha && parts.length == 4)
                    o = o + hex(parts[3]);
            }
            return o;
        },
        gradient : function(p1, p2) {
            return pointHelper(p1, p2, function(_p1, _p2) {
                if (_p2[0] == _p1[0])
                    return _p2[1] > _p1[1] ? Infinity : -Infinity;
                else if (_p2[1] == _p1[1])
                    return _p2[0] > _p1[0] ? 0 : -0;
                else
                    return (_p2[1] - _p1[1]) / (_p2[0] - _p1[0]);
            });
        },
        normal : function(p1, p2) {
            return -1 / this.gradient(p1, p2);
        },
        lineLength : function(p1, p2) {
            return pointHelper(p1, p2, function(_p1, _p2) {
                return Math.sqrt(Math.pow(_p2[1] - _p1[1], 2) + Math.pow(_p2[0] - _p1[0], 2));
            });
        },
        segment : function(p1, p2) {
            return pointHelper(p1, p2, function(_p1, _p2) {
                if (_p2[0] > _p1[0]) {
                    return (_p2[1] > _p1[1]) ? 2 : 1;
                }
                else if (_p2[0] == _p1[0]) {
                    return _p2[1] > _p1[1] ? 2 : 1;
                }
                else {
                    return (_p2[1] > _p1[1]) ? 3 : 4;
                }
            });
        },
        theta : function(p1, p2) {
            return pointHelper(p1, p2, function(_p1, _p2) {
                var m = jsPlumbUtil.gradient(_p1, _p2),
                    t = Math.atan(m),
                    s = jsPlumbUtil.segment(_p1, _p2);
                if ((s == 4 || s== 3)) t += Math.PI;
                if (t < 0) t += (2 * Math.PI);

                return t;
            });
        },
        intersects : function(r1, r2) {
            var x1 = r1.x, x2 = r1.x + r1.w, y1 = r1.y, y2 = r1.y + r1.h,
                a1 = r2.x, a2 = r2.x + r2.w, b1 = r2.y, b2 = r2.y + r2.h;

        return  ( (x1 <= a1 && a1 <= x2) && (y1 <= b1 && b1 <= y2) ) ||
                ( (x1 <= a2 && a2 <= x2) && (y1 <= b1 && b1 <= y2) ) ||
                ( (x1 <= a1 && a1 <= x2) && (y1 <= b2 && b2 <= y2) ) ||
                ( (x1 <= a2 && a1 <= x2) && (y1 <= b2 && b2 <= y2) ) ||
                ( (a1 <= x1 && x1 <= a2) && (b1 <= y1 && y1 <= b2) ) ||
                ( (a1 <= x2 && x2 <= a2) && (b1 <= y1 && y1 <= b2) ) ||
                ( (a1 <= x1 && x1 <= a2) && (b1 <= y2 && y2 <= b2) ) ||
                ( (a1 <= x2 && x1 <= a2) && (b1 <= y2 && y2 <= b2) );
        },
        segmentMultipliers : [null, [1, -1], [1, 1], [-1, 1], [-1, -1] ],
        inverseSegmentMultipliers : [null, [-1, -1], [-1, 1], [1, 1], [1, -1] ],
        pointOnLine : function(fromPoint, toPoint, distance) {
            var m = jsPlumbUtil.gradient(fromPoint, toPoint),
                s = jsPlumbUtil.segment(fromPoint, toPoint),
                segmentMultiplier = distance > 0 ? jsPlumbUtil.segmentMultipliers[s] : jsPlumbUtil.inverseSegmentMultipliers[s],
                theta = Math.atan(m),
                y = Math.abs(distance * Math.sin(theta)) * segmentMultiplier[1],
                x =  Math.abs(distance * Math.cos(theta)) * segmentMultiplier[0];
            return { x:fromPoint.x + x, y:fromPoint.y + y };
        },
        perpendicularLineTo : function(fromPoint, toPoint, length) {
            var m = jsPlumbUtil.gradient(fromPoint, toPoint),
                theta2 = Math.atan(-1 / m),
                y =  length / 2 * Math.sin(theta2),
                x =  length / 2 * Math.cos(theta2);
            return [{x:toPoint.x + x, y:toPoint.y + y}, {x:toPoint.x - x, y:toPoint.y - y}];
        },
        findWithFunction : function(a, f) {
            if (a)
                for (var i = 0; i < a.length; i++) if (f(a[i])) return i;
            return -1;
        },
        clampToGrid : function(x, y, grid, dontClampX, dontClampY) {
            var _gridClamp = function(n, g) {
                var e = n % g,
                    f = Math.floor(n / g),
                    inc = e >= (g / 2) ? 1 : 0;
                return (f + inc) * g;
            };
            return [
                dontClampX || grid == null ? x : _gridClamp(x, grid[0]),
                dontClampY || grid == null ? y : _gridClamp(y, grid[1])
            ];
        },
        indexOf : function(l, v) {
            return jsPlumbUtil.findWithFunction(l, function(_v) { return _v == v; });
        },
        removeWithFunction : function(a, f) {
            var idx = jsPlumbUtil.findWithFunction(a, f);
            if (idx > -1) a.splice(idx, 1);
            return idx != -1;
        },
        remove : function(l, v) {
            var idx = jsPlumbUtil.indexOf(l, v);
            if (idx > -1) l.splice(idx, 1);
            return idx != -1;
        },
        // TODO support insert index
        addWithFunction : function(list, item, hashFunction) {
            if (jsPlumbUtil.findWithFunction(list, hashFunction) == -1) list.push(item);
        },
        addToList : function(map, key, value, insertAtStart) {
            var l = map[key];
            if (l == null) {
                l = [];
                map[key] = l;
            }
            l[insertAtStart ? "unshift" : "push"](value);
            return l;
        },
        //
        // extends the given obj (which can be an array) with the given constructor function, prototype functions, and
        // class members, any of which may be null.
        //
        extend : function(child, parent, _protoFn, _protoAtts) {
            _protoFn = _protoFn || {};
            _protoAtts = _protoAtts || {};
            parent = _isa(parent) ? parent : [ parent ];

            for (var i = 0; i < parent.length; i++) {
                for (var j in parent[i].prototype) {
                    if(parent[i].prototype.hasOwnProperty(j)) {
                        child.prototype[j] = parent[i].prototype[j];
                    }
                }
            }

            var _makeFn = function(name) {
                return function() {
                    for (var i = 0; i < parent.length; i++) {
                        if (parent[i].prototype[name])
                            parent[i].prototype[name].apply(this, arguments);
                    }
                    return _protoFn[name].apply(this, arguments);
                };
            };

            for (var k in _protoFn) {
                child.prototype[k] = _makeFn(k);
            }

            return child;
        },
        uuid : function() {
            return ('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
                return v.toString(16);
            }));
        },
        logEnabled : true,
        log : function() {
            if (jsPlumbUtil.logEnabled && typeof console != "undefined") {
                try {
                    var msg = arguments[arguments.length - 1];
                    console.log(msg);
                }
                catch (e) {}
            }
        },
        group : function(g) { if (jsPlumbUtil.logEnabled && typeof console != "undefined") console.group(g); },
        groupEnd : function(g) { if (jsPlumbUtil.logEnabled && typeof console != "undefined") console.groupEnd(g); },
        time : function(t) { if (jsPlumbUtil.logEnabled && typeof console != "undefined") console.time(t); },
        timeEnd : function(t) { if (jsPlumbUtil.logEnabled && typeof console != "undefined") console.timeEnd(t); },

        /**
		 * helper to remove an element from the DOM.
		 */
		removeElement : function(element) {
			if (element != null && element.parentNode != null) {
				element.parentNode.removeChild(element);
			}
		},
        /**
		 * helper to remove a list of elements from the DOM.
		 */
		removeElements : function(elements) {
			for ( var i = 0; i < elements.length; i++)
				jsPlumbUtil.removeElement(elements[i]);
		},
        /*
         * Function: sizeElement
         * Helper to size and position an element. You would typically use
         * this when writing your own Connector or Endpoint implementation.
         *
         * Parameters:
         *  x - [int] x position for the element origin
         *  y - [int] y position for the element origin
         *  w - [int] width of the element
         *  h - [int] height of the element
         *
         */
        sizeElement : function(el, x, y, w, h) {
            if (el) {
                el.style.height = h + "px";
                el.height = h;
                el.style.width = w + "px";
                el.width = w;
                el.style.left = x + "px";
                el.style.top = y + "px";
            }
        },
        /**
        * @name jsPlumbUtil.wrap
        * @desc Wraps one function with another, creating a placeholder for the
        * wrapped function if it was null. this is used to wrap the various
        * drag/drop event functions - to allow jsPlumb to be notified of
        * important lifecycle events without imposing itself on the user's
        * drag/drop functionality.
        * @param {Function} wrappedFunction original function to wrap; may be null.
        * @param {Function} newFunction function to wrap the original with.
        * @param {Object} [returnOnThisValue] Optional. Indicates that the wrappedFunction should
        * not be executed if the newFunction returns a value matching 'returnOnThisValue'.
        * note that this is a simple comparison and only works for primitives right now.
        */
        wrap : function(wrappedFunction, newFunction, returnOnThisValue) {
            wrappedFunction = wrappedFunction || function() { };
            newFunction = newFunction || function() { };
            return function() {
                var r = null;
                try {
                    r = newFunction.apply(this, arguments);
                } catch (e) {
                    jsPlumbUtil.log("jsPlumb function failed : " + e);
                }
                if (returnOnThisValue == null || (r !== returnOnThisValue)) {
                    try {
                        r = wrappedFunction.apply(this, arguments);
                    } catch (e) {
                        jsPlumbUtil.log("wrapped function failed : " + e);
                    }
                }
                return r;
            };
        }
    };

    jsPlumbUtil.EventGenerator = function() {
        var _listeners = {}, eventsSuspended = false;

        // this is a list of events that should re-throw any errors that occur during their dispatch. as of 1.3.0 this is private to
        // jsPlumb, but it seems feasible that people might want to manipulate this list.  the thinking is that we don't want event
        // listeners to bring down jsPlumb - or do we.  i can't make up my mind about this, but i know i want to hear about it if the "ready"
        // event fails, because then my page has most likely not initialised.  so i have this halfway-house solution.  it will be interesting
        // to hear what other people think.
        var eventsToDieOn = [ "ready" ];

        this.bind = function(event, listener, insertAtStart) {
            jsPlumbUtil.addToList(_listeners, event, listener, true);
            return this;
        };

        this.fire = function(event, value, originalEvent) {
            if (!eventsSuspended && _listeners[event]) {
                // instead of looping through the array we get a counter and a length, because it is possible
                // that an event fired from here could cause the object to get cleaned up, which would throw
                // away the listeners. so after each cycle through the loop we check to ensure we haven't
                // been nuked.
                var l = _listeners[event].length, i = 0, _gone = false, ret = null;
                if (!this.shouldFireEvent || this.shouldFireEvent(event, value, originalEvent)) {
                    while (!_gone && i < l && ret !== false) {

                        // doing it this way rather than catching and then possibly re-throwing means that an error propagated by this
                        // method will have the whole call stack available in the debugger.
                        if (jsPlumbUtil.findWithFunction(eventsToDieOn, function(e) { return e === event; }) != -1)
                            _listeners[event][i](value, originalEvent);
                        else {
                            // for events we don't want to die on, catch and log.
                            try {
                                ret = _listeners[event][i](value, originalEvent);
                            } catch (e) {
                                jsPlumbUtil.log("jsPlumb: fire failed for event " + event + " : " + e);
                            }
                        }
                        i++;
                        if (_listeners == null || _listeners[event] == null) _gone = true;
                    }
                }
            }
            return this;
        };

        this.unbind = function(event) {
            if (event)
                delete _listeners[event];
            else {
                _listeners = {};
            }
            return this;
        };

        this.getListener = function(forEvent) {
            return _listeners[forEvent];
        };
        this.setSuspendEvents = function(val) {
            eventsSuspended = val;
        };
        this.isSuspendEvents = function() {
            return eventsSuspended;
        };
        this.cleanupListeners = function() {
            for (var i in _listeners) {
                _listeners[i].splice(0);
                delete _listeners[i];
            }
        };
    };

    jsPlumbUtil.EventGenerator.prototype = {
        cleanup:function() {
            this.cleanupListeners();
        }
    };

    // thanks MDC
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fbind
    if (!Function.prototype.bind) {
      Function.prototype.bind = function (oThis) {
        if (typeof this !== "function") {
          // closest thing possible to the ECMAScript 5 internal IsCallable function
          throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
        }

        var aArgs = Array.prototype.slice.call(arguments, 1),
            fToBind = this,
            fNOP = function () {},
            fBound = function () {
              return fToBind.apply(this instanceof fNOP && oThis ? this : oThis,
                                   aArgs.concat(Array.prototype.slice.call(arguments)));
            };

        fNOP.prototype = this.prototype;
        fBound.prototype = new fNOP();

        return fBound;
      };
    }

})();


text:
<?php

require dirname(__FILE__).'/../src/global.php';

logInfo("Starting to Check Email");

$inbox = imap_open(MAIL_SERVER,MAIL_USERNAME,MAIL_PASSWORD);
if (!$inbox) {
	logWarning('Cannot connect to email: ' . imap_last_error());
	die('Cannot connect to email: ' . imap_last_error());
}

$emails = imap_search($inbox,'ALL',SE_UID);

if($emails) {
	foreach($emails as $email_number) {
		//print "#############################################################\n";

		logInfo("Fetching email ".$email_number);
		$overview = imap_fetch_overview($inbox,$email_number,FT_UID);
		$struct = imap_fetchstructure($inbox,$email_number,FT_UID);

		$message = null;
		if (property_exists($struct,'parts') && is_array($struct->parts)) {
			foreach($struct->parts as $id=>$part) {
				if ($part->subtype == 'PLAIN') {
					$message = imap_fetchbody($inbox, $email_number, ($id+1), FT_UID);
				}
				if ($part->subtype == 'ALTERNATIVE') {
					foreach($part->parts as $id2=>$part) {
						if ($part->subtype == 'PLAIN') {
							$message = imap_fetchbody($inbox, $email_number, ($id+1).".".($id2+1), FT_UID);
						}
					}
				}
			}
		} else {
			$message = imap_body($inbox,$email_number,FT_UID);
		}

		//var_dump($overview);
		//var_dump($struct);
		//var_dump($message);

		if ($message) {
			logInfo("Parsing email ".$email_number);
			$email = new EmailIn($overview[0]->from, $overview[0]->subject, $message);
			$email->parse();
			if ($email->getReply() && $email->getRequest() && $email->getUserAccount()) {
				logInfo("Creating new reply from email ".$email_number." for Request:".$email->getRequest()->getId());
				$email->getRequest()->newResponse($email->getReply(), $email->getUserAccount());
				imap_mail_move($inbox, $email_number, "Old", CP_UID);
			}
			if ($email->getReply() && $email->getSupportGroupNewsArticle() && $email->getUserAccount()) {
				logInfo("Creating new reply from email ".$email_number." for SupportGroupNewsArticle:".$email->getSupportGroupNewsArticle()->getId());
				$email->getSupportGroupNewsArticle()->newResponse($email->getReply(), $email->getUserAccount());
				imap_mail_move($inbox, $email_number, "Old", CP_UID);
			}
		}

	}
}

imap_close($inbox,CL_EXPUNGE);

logInfo("Finished Checking Email");

redpajama_set_name: RedPajamaGithub


text:
@interface DummyAuthHandler : NSObject <RNFRequestAuthentication>

@end


text:
namespace blink {

LayoutAnalyzer::Scope::Scope(const LayoutObject& o)
    : m_layoutObject(o)
    , m_analyzer(o.frameView()->layoutAnalyzer())
{
    if (m_analyzer)
        m_analyzer->push(o);
}

LayoutAnalyzer::Scope::~Scope()
{
    if (m_analyzer)
        m_analyzer->pop(m_layoutObject);
}

LayoutAnalyzer::BlockScope::BlockScope(const LayoutBlock& block)
    : m_block(block)
    , m_width(block.frameRect().width())
    , m_height(block.frameRect().height())
{
}

LayoutAnalyzer::BlockScope::~BlockScope()
{
    LayoutAnalyzer* analyzer = m_block.frameView()->layoutAnalyzer();
    if (!analyzer)
        return;
    bool changed = false;
    if (m_width != m_block.frameRect().width()) {
        analyzer->increment(LayoutBlockWidthChanged);
        changed = true;
    }
    if (m_height != m_block.frameRect().height()) {
        analyzer->increment(LayoutBlockHeightChanged);
        changed = true;
    }
    analyzer->increment(changed ? LayoutBlockSizeChanged : LayoutBlockSizeDidNotChange);
}

void LayoutAnalyzer::reset()
{
    m_startMs = currentTimeMS();
    m_depth = 0;
    for (size_t i = 0; i < NumCounters; ++i) {
        m_counters[i] = 0;
    }
}

void LayoutAnalyzer::push(const LayoutObject& o)
{
    increment(TotalLayoutObjectsThatWereLaidOut);
    if (!o.everHadLayout())
        increment(LayoutObjectsThatHadNeverHadLayout);
    if (o.selfNeedsLayout())
        increment(LayoutObjectsThatNeedLayoutForThemselves);
    if (o.needsPositionedMovementLayout())
        increment(LayoutObjectsThatNeedPositionedMovementLayout);
    if (o.isOutOfFlowPositioned())
        increment(LayoutObjectsThatAreOutOfFlowPositioned);
    if (o.isTableCell())
        increment(LayoutObjectsThatAreTableCells);
    if (o.isFloating())
        increment(LayoutObjectsThatAreFloating);
    if (o.style()->specifiesColumns())
        increment(LayoutObjectsThatSpecifyColumns);
    if (o.hasLayer())
        increment(LayoutObjectsThatHaveALayer);
    if (o.isLayoutInline() && o.alwaysCreateLineBoxesForLayoutInline())
        increment(LayoutInlineObjectsThatAlwaysCreateLineBoxes);
    if (o.isText()) {
        const LayoutText& t = *toLayoutText(&o);
        if (t.canUseSimpleFontCodePath()) {
            increment(LayoutObjectsThatAreTextAndCanUseTheSimpleFontCodePath);
            increment(CharactersInLayoutObjectsThatAreTextAndCanUseTheSimpleFontCodePath, t.textLength());
        } else {
            increment(LayoutObjectsThatAreTextAndCanNotUseTheSimpleFontCodePath);
            increment(CharactersInLayoutObjectsThatAreTextAndCanNotUseTheSimpleFontCodePath, t.textLength());
        }
    }

    ++m_depth;

    // This refers to LayoutAnalyzer depth, which is generally closer to C++
    // stack recursion depth, not layout tree depth or DOM tree depth.
    m_counters[LayoutAnalyzerStackMaximumDepth] = max(m_counters[LayoutAnalyzerStackMaximumDepth], m_depth);
}

void LayoutAnalyzer::pop(const LayoutObject& o)
{
    ASSERT(m_depth > 0);
    --m_depth;
}

PassRefPtr<TracedValue> LayoutAnalyzer::toTracedValue()
{
    RefPtr<TracedValue> tracedValue(TracedValue::create());
    for (size_t i = 0; i < NumCounters; ++i) {
        if (m_counters[i] > 0)
            tracedValue->setInteger(nameForCounter(static_cast<Counter>(i)), m_counters[i]);
    }
    return tracedValue.release();
}

const char* LayoutAnalyzer::nameForCounter(Counter counter) const
{
    switch (counter) {
    case LayoutBlockWidthChanged: return "LayoutBlockWidthChanged";
    case LayoutBlockHeightChanged: return "LayoutBlockHeightChanged";
    case LayoutBlockSizeChanged: return "LayoutBlockSizeChanged";
    case LayoutBlockSizeDidNotChange: return "LayoutBlockSizeDidNotChange";
    case LayoutObjectsThatSpecifyColumns: return "LayoutObjectsThatSpecifyColumns";
    case LayoutAnalyzerStackMaximumDepth: return "LayoutAnalyzerStackMaximumDepth";
    case LayoutObjectsThatAreFloating: return "LayoutObjectsThatAreFloating";
    case LayoutObjectsThatHaveALayer: return "LayoutObjectsThatHaveALayer";
    case LayoutInlineObjectsThatAlwaysCreateLineBoxes: return "LayoutInlineObjectsThatAlwaysCreateLineBoxes";
    case LayoutObjectsThatHadNeverHadLayout: return "LayoutObjectsThatHadNeverHadLayout";
    case LayoutObjectsThatAreOutOfFlowPositioned: return "LayoutObjectsThatAreOutOfFlowPositioned";
    case LayoutObjectsThatNeedPositionedMovementLayout: return "LayoutObjectsThatNeedPositionedMovementLayout";
    case PerformLayoutRootLayoutObjects: return "PerformLayoutRootLayoutObjects";
    case LayoutObjectsThatNeedLayoutForThemselves: return "LayoutObjectsThatNeedLayoutForThemselves";
    case LayoutObjectsThatNeedSimplifiedLayout: return "LayoutObjectsThatNeedSimplifiedLayout";
    case LayoutObjectsThatAreTableCells: return "LayoutObjectsThatAreTableCells";
    case LayoutObjectsThatAreTextAndCanNotUseTheSimpleFontCodePath: return "LayoutObjectsThatAreTextAndCanNotUseTheSimpleFontCodePath";
    case CharactersInLayoutObjectsThatAreTextAndCanNotUseTheSimpleFontCodePath: return "CharactersInLayoutObjectsThatAreTextAndCanNotUseTheSimpleFontCodePath";
    case LayoutObjectsThatAreTextAndCanUseTheSimpleFontCodePath: return "LayoutObjectsThatAreTextAndCanUseTheSimpleFontCodePath";
    case CharactersInLayoutObjectsThatAreTextAndCanUseTheSimpleFontCodePath: return "CharactersInLayoutObjectsThatAreTextAndCanUseTheSimpleFontCodePath";
    case TotalLayoutObjectsThatWereLaidOut: return "TotalLayoutObjectsThatWereLaidOut";
    }
    ASSERT_NOT_REACHED();
    return "";
}

} // namespace blink


text:
flask_swag package
==================

Subpackages
-----------

.. toctree::

    flask_swag.extractor

Submodules
----------

flask_swag.core module
----------------------

.. automodule:: flask_swag.core
    :members:
    :undoc-members:
    :show-inheritance:

flask_swag.ext module
---------------------

.. automodule:: flask_swag.ext
    :members:
    :undoc-members:
    :show-inheritance:

flask_swag.fields module
------------------------

.. automodule:: flask_swag.fields
    :members:
    :undoc-members:
    :show-inheritance:

flask_swag.globals module
-------------------------

.. automodule:: flask_swag.globals
    :members:
    :undoc-members:
    :show-inheritance:

flask_swag.mark module
----------------------

.. automodule:: flask_swag.mark
    :members:
    :undoc-members:
    :show-inheritance:

flask_swag.schemas module
-------------------------

.. automodule:: flask_swag.schemas
    :members:
    :undoc-members:
    :show-inheritance:

flask_swag.utils module
-----------------------

.. automodule:: flask_swag.utils
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: flask_swag
    :members:
    :undoc-members:
    :show-inheritance:


text:
require 'formula'

class TigerOnly < Requirement
  def message; <<-EOS.undent
    gcc-4.2 is only provided for Tiger, as it is officially available
    from an Xcode shipped with Leopard.
    EOS
  end
  def satisfied?; MacOS.version == :tiger; end
  def fatal?; true; end
end

class AppleGcc42 < Formula
  homepage 'http://r.research.att.com/tools/'
  url 'http://r.research.att.com/gcc-42-5553-darwin8-all.tar.gz'
  version '4.2.1-5553'
  sha1 '0e529a2e4723e016e3d086d6ca3215d700931503'

  depends_on TigerOnly.new

  def install
    cd 'usr' do
      prefix.install Dir['*']
    end
  end

  def caveats
    <<-EOS.undent
      This formula contains compilers built from Apple's GCC sources, build
      5553, available from:

        http://opensource.apple.com/tarballs/gcc

      All compilers have a `-4.2` suffix. A GFortran compiler is also included.
    EOS
  end
end


text:
@interface ScrollViewControllerWithXib () <UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@end

@implementation ScrollViewControllerWithXib

- (void)viewDidLoad {
    [super viewDidLoad];
    self.scrollView.delegate = self;

    self.scrollView.scrollsToTop = YES;
}

#pragma mark - UIScrollViewDelegate
//scrollView滚动时,就调用该方法。任何offset值改变都调用该方法。即滚动过程中,调用多次
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{

    NSLog(@"scrollViewDidScroll");
    CGPoint point = scrollView.contentOffset;
    NSLog(@"%f,%f",point.x,point.y);
    // 从中可以读取contentOffset属性以确定其滚动到的位置。
    // 注意:当ContentSize属性小于Frame时,将不会出发滚动

    if (scrollView.contentOffset.y == -64){
        NSLog(@"At the top");
    }
}

// 当scrollView缩放时,调用该方法。在缩放过程中,回多次调用
- (void)scrollViewDidZoom:(UIScrollView *)scrollView{
    NSLog(@"scrollViewDidZoom");
    float value=scrollView.zoomScale;
    NSLog(@"%f",value);
}

// 当开始滚动视图时,执行该方法。一次有效滑动(开始滑动,滑动一小段距离,只要手指不松开,只算一次滑动),只执行一次。
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    NSLog(@"scrollViewWillBeginDragging");
}

// 滑动scrollView,并且手指离开时执行。一次有效滑动,只执行一次。
// 当pagingEnabled属性为YES时,不调用,该方法
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    NSLog(@"scrollViewWillEndDragging");
}

// 滑动视图,当手指离开屏幕那一霎那,调用该方法。一次有效滑动,只执行一次。
// decelerate,指代,当我们手指离开那一瞬后,视图是否还将继续向前滚动(一段距离),经过测试,decelerate=YES
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    NSLog(@"scrollViewDidEndDragging");
    if (decelerate) {
        NSLog(@"decelerate");
    }else{
        NSLog(@"no decelerate");

    }
    CGPoint point=scrollView.contentOffset;
    NSLog(@"%f,%f",point.x,point.y);
}

// 滑动减速时调用该方法。
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    NSLog(@"scrollViewWillBeginDecelerating");
    // 该方法在scrollViewDidEndDragging方法之后。
}

// 滚动视图减速完成,滚动将停止时,调用该方法。一次有效滑动,只执行一次。
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSLog(@"scrollViewDidEndDecelerating");
    //[_scrollView setContentOffset:CGPointMake(0, 500) animated:YES];
}

// 当滚动视图动画完成后,调用该方法,如果没有动画,那么该方法将不被调用
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    NSLog(@"scrollViewDidEndScrollingAnimation");
    // 有效的动画方法为:
    //    - (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated 方法
    //    - (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated 方法
}

// 返回将要缩放的UIView对象。要执行多次
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    //NSLog(@"viewForZoomingInScrollView");
    //return  self.imgView;
    return nil;
}

// 当将要开始缩放时,执行该方法。一次有效缩放,就只执行一次。
- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view{
    //NSLog(@"scrollViewWillBeginZooming");
}

// 当缩放结束后,并且缩放大小回到minimumZoomScale与maximumZoomScale之间后(我们也许会超出缩放范围),调用该方法。
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale{
    //NSLog(@"scrollViewDidEndZooming");
}

// 指示当用户点击状态栏后,滚动视图是否能够滚动到顶部。需要设置滚动视图的属性:_scrollView.scrollsToTop=YES;
- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView{
    return YES;
}

// 当滚动视图滚动到最顶端后,执行该方法
- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView{
    NSLog(@"scrollViewDidScrollToTop");
}

#pragma mark - IBAction
- (IBAction)topAction:(UIButton *)sender {
    [_scrollView scrollRectToVisible:CGRectMake(0, CGRectGetMaxY(self.view.frame), 100, 100) animated:YES];
}

- (IBAction)middleAction:(id)sender {
    //Go bottom
    [_scrollView setContentOffset:CGPointMake(0, 1000) animated:YES];

}

- (IBAction)bottomAction:(UIButton *)sender {
    //Go top
    [_scrollView setContentOffset:CGPointMake(0, -64) animated:YES];
}

@end


text:
hook.Add( "PhysgunPickup", "PhysgunKill", function( ply, ent )
	ent:TakeDamage( ent:Health() )
end )


text:
#import "SCMultiPolygon.h"
#import "SCBoundingBox.h"
#import "SCPolygon.h"

@interface SCMultiPolygon ()
@end

@implementation SCMultiPolygon

@synthesize polygons = _polygons;

- (id)initWithCoordinateArray:(NSArray *)coords crs:(NSInteger)s {
  if (self = [super initWithCoordinateArray:coords crs:s]) {
    NSMutableArray *arr =
        [[NSMutableArray alloc] initWithCapacity:coords.count];
    for (NSArray *coord in coords) {
      [arr addObject:[[SCPolygon alloc] initWithCoordinateArray:coord crs:s]];
    }
    _polygons = [[NSArray alloc] initWithArray:arr];
  }
  self.bbox = [[SCBoundingBox alloc] init];
  [_polygons
      enumerateObjectsUsingBlock:^(SCPolygon *p, NSUInteger idx, BOOL *stop) {
        [self.bbox addPoints:p.points];
      }];
  return self;
}

- (id)initWithCoordinateArray:(NSArray *)coords {
  return [self initWithCoordinateArray:coords crs:4326];
}

- (GeometryType)type {
  return MULTIPOLYGON;
}

- (NSString *)description {
  NSMutableString *str =
      [[NSMutableString alloc] initWithString:@"MultiPolygon["];
  [self.polygons enumerateObjectsUsingBlock:^(SCPolygon *polygon,
                                              NSUInteger idx, BOOL *stop) {
    [str appendString:[polygon description]];
  }];
  [str appendString:@"]"];
  return str;
}

- (BOOL)isContained:(SCBoundingBox *)bbox {
  __block BOOL response = NO;
  [self.polygons enumerateObjectsUsingBlock:^(SCPolygon *poly, NSUInteger idx,
                                              BOOL *stop) {
    if ([poly isContained:bbox]) {
      response = YES;
      *stop = YES;
    }
  }];
  return response;
}

- (SCSimplePoint *)centroid {
  __block double x = 0;
  __block double y = 0;
  [self.polygons
      enumerateObjectsUsingBlock:^(SCPolygon *p, NSUInteger idx, BOOL *stop) {
        SCSimplePoint *pt = p.centroid;
        x += pt.x;
        y += pt.y;
      }];
  return [[SCSimplePoint alloc] initWithX:(x / self.polygons.count)
                                        Y:(y / self.polygons.count)];
}

- (NSDictionary *)JSONDict {
  NSMutableDictionary *dict =
      [NSMutableDictionary dictionaryWithDictionary:[super JSONDict]];
  NSArray *coords = [self coordinateArray];
  NSDictionary *geometry =
      [NSDictionary dictionaryWithObjects:@[ @"MultiPolygon", coords ]
                                  forKeys:@[ @"type", @"coordinates" ]];
  [dict setObject:geometry forKey:@"geometry"];
  return dict;
}

- (NSArray *)coordinateArray {
  return [self coordinateArrayAsProj:self.crs];
}

- (NSArray *)coordinateArrayAsProj:(NSInteger)c {
  return [[self.polygons.rac_sequence map:^NSArray *(SCPolygon *poly) {
    return [poly coordinateArrayAsProj:c];
  }] array];
}

@end


text:
package com.ibm.opensirf.audit;

import javax.xml.bind.annotation.XmlTransient;

public class AuditLogReference {

	public AuditLogReference() {
	}

	public AuditLogReference(String type, String referenceRole, String value) {
		this.referenceType = type;
		this.referenceRole = referenceRole;
		this.referenceValue = value;
	}

	public AuditLogReference(String type, String value) {
		this(type, "AuditLog", value);
	}

	public String getReferenceType() {
		return referenceType;
	}

	public void setReferenceType(String referenceType) {
		this.referenceType = referenceType;
	}

	public String getReferenceRole() {
		return referenceRole;
	}

	public void setReferenceRole(String referenceRole) {
		this.referenceRole = referenceRole;
	}

	public String getReferenceValue() {
		return referenceValue;
	}

	public void setReferenceValue(String referenceValue) {
		this.referenceValue = referenceValue;
	}

	private String referenceType;

	private String referenceRole;

	private String referenceValue;

	@XmlTransient
	public static final String TYPE_INTERNAL = "internal";

	@XmlTransient
	public static final String TYPE_EXTERNAL = "external";
}


text:
static char THIS_FILE[] = __FILE__;
#endif

// A simple dialog class.
class CrcDlg : public ClsDialog
{
	_NO_COPY( CrcDlg );
public:
	// No-op constructor and destructor.
	CrcDlg() {;}
	virtual ~CrcDlg() {;}

protected:
	// WM_COMMAND handler.
	virtual LRESULT OnCommand( UINT nNotifyCode, UINT nCtrlID, HWND hWndCtrl )
	{
		// The checkbox?
		if ( nCtrlID == IDC_SHOWFILES )
		{
			m_Browser.ShowFiles() = m_Check.IsChecked();
			return 0;
		}
		return ClsDialog::OnCommand( nNotifyCode, nCtrlID, hWndCtrl );
	}

	// WM_INITDIALOG handler.
	virtual LRESULT OnInitDialog( PROPSHEETPAGE *psp )
	{
		// Attach FileBrowser control.
		m_Browser.Attach( GetDlgItemHandle( IDC_FILE ));
		m_Browser.LoadingTextColor() = RGB( 255, 0, 0 );
		m_Browser.ShowFiles() = FALSE;

		m_Check.Attach( GetDlgItemHandle( IDC_SHOWFILES ));
		m_Check.SetCheck( BST_UNCHECKED );

		return ClsDialog::OnInitDialog( psp );
	}
	// Data.
	ClsFileDirBrowser	m_Browser;
	ClsCheckBox		m_Check;
};

// Entry point.
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, INT nShowCmd )
{
	int		rc = 0;

	// Setup app.
	if ( ClsGetApp()->Setup( hInstance, lpCmdLine, nShowCmd ))
	{
		// Check OS version.
		if ( ClsGetApp()->GetPlatformID() != VER_PLATFORM_WIN32_WINDOWS &&
		     ClsGetApp()->GetPlatformID() != VER_PLATFORM_WIN32_NT )
		{
			MessageBox( NULL, _T( "Windows 95/98/ME/NT/2000/XP required!" ), _T( "\"ClsCrc\" Sample" ), MB_OK );
			return NULL;
		}

		// Create and open the dialog.
		CrcDlg	dlg;
		dlg.DoModal( IDD_CRC );
	}
	return rc;
}


text:
// ==++==
//
//   Copyright (c) Microsoft Corporation.  All rights reserved.
//
// ==--==
/*============================================================
**
** Interface:  ICollection
**
** <OWNER>[....]</OWNER>
**
**
** Purpose: Base interface for all collections.
**
**
===========================================================*/
namespace System.Collections {
    using System;
    using System.Diagnostics.Contracts;

    // Base interface for all collections, defining enumerators, size, and
    // synchronization methods.
#if CONTRACTS_FULL
    [ContractClass(typeof(ICollectionContract))]
#endif // CONTRACTS_FULL
    [System.Runtime.InteropServices.ComVisible(true)]
    public interface ICollection : IEnumerable
    {
        // Interfaces are not serialable
        // CopyTo copies a collection into an Array, starting at a particular
        // index into the array.
        //
        void CopyTo(Array array, int index);

        // Number of items in the collections.
        int Count
        { get; }

        // SyncRoot will return an Object to use for synchronization
        // (thread safety).  You can use this object in your code to take a
        // lock on the collection, even if this collection is a wrapper around
        // another collection.  The intent is to tunnel through to a real
        // implementation of a collection, and use one of the internal objects
        // found in that code.
        //
        // In the absense of a static Synchronized method on a collection,
        // the expected usage for SyncRoot would look like this:
        //
        // ICollection col = ...
        // lock (col.SyncRoot) {
        //     // Some operation on the collection, which is now thread safe.
        //     // This may include multiple operations.
        // }
        //
        //
        // The system-provided collections have a static method called
        // Synchronized which will create a thread-safe wrapper around the
        // collection.  All access to the collection that you want to be
        // thread-safe should go through that wrapper collection.  However, if
        // you need to do multiple calls on that collection (such as retrieving
        // two items, or checking the count then doing something), you should
        // NOT use our thread-safe wrapper since it only takes a lock for the
        // duration of a single method call.  Instead, use Monitor.Enter/Exit
        // or your language's equivalent to the C# lock keyword as mentioned
        // above.
        //
        // For collections with no publically available underlying store, the
        // expected implementation is to simply return the this pointer.  Note
        // that the this pointer may not be sufficient for collections that
        // wrap other collections;  those should return the underlying
        // collection's SyncRoot property.
        Object SyncRoot
        { get; }

        // Is this collection synchronized (i.e., thread-safe)?  If you want a
        // thread-safe collection, you can use SyncRoot as an object to
        // synchronize your collection with.  If you're using one of the
        // collections in System.Collections, you could call the static
        // Synchronized method to get a thread-safe wrapper around the
        // underlying collection.
        bool IsSynchronized
        { get; }
    }

#if CONTRACTS_FULL
    [ContractClassFor(typeof(ICollection))]
    internal abstract class ICollectionContract : ICollection
    {
        void ICollection.CopyTo(Array array, int index)
        {
        }

        int ICollection.Count {
            get {
                Contract.Ensures(Contract.Result<int>() >= 0);
                return default(int);
            }
        }

        Object ICollection.SyncRoot {
            get {
                Contract.Ensures(Contract.Result<Object>() != null);
                return default(Object);
            }
        }

        bool ICollection.IsSynchronized {
            get { return default(bool); }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return default(IEnumerator);
        }
    }
#endif // CONTRACTS_FULL
}


text:
type BylineProps = {
  author: string
}

export default function Byline({ author }: BylineProps) {
  return (
    <>

By {author}

    </>
  )
}


text:
<?php

namespace PUGX\Badge\Model\UseCase;

use PUGX\Badge\Model\Badge;
use PUGX\Badge\Model\PackageRepositoryInterface;

abstract class BaseCreatePackagistImage
{
    /** @var PackageRepositoryInterface */
    protected $packageRepository;

    /**
     * @param PackageRepositoryInterface $packageRepository
     */
    public function __construct(PackageRepositoryInterface $packageRepository)
    {
        $this->packageRepository = $packageRepository;
    }

    protected function createBadgeFromRepository($repository, $subject, $color, $format = 'svg', $context = null)
    {
        $package = $this->fetchPackage($repository);
        $text = $this->prepareText($package, $context);

        return $this->createBadge($subject, $text, $color, $format);
    }

    protected function fetchPackage($repository)
    {
       return $this->packageRepository->fetchByRepository($repository);
    }

    protected function createBadge($subject, $status, $color, $format)
    {
        return new Badge($subject, $status, $color, $format);
    }

    abstract protected function prepareText($package, $context = null);
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Pagelet.Widget (MDW 6 API JavaDocs)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.centurylink.mdw.model.asset

Class Pagelet.Widget

java.lang.Object

com.centurylink.mdw.model.asset.Pagelet.Widget

All Implemented Interfaces:

io.limberest.json.Jsonable

Enclosing class:

Pagelet

public static class Pagelet.Widget
extends java.lang.Object
implements Jsonable

Constructor Summary

Constructors

Constructor and Description

Widget(org.json.JSONObject json)

Widget(java.lang.String name,
      java.lang.String type)

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
addOption(java.lang.String option)

void
addWidget(Pagelet.Widget widget)

WidgetAdapter
getAdapter()

java.lang.String
getAttribute(java.lang.String name)

java.util.Map<java.lang.String,java.lang.String>
getAttributes()

everything but name, type and options

org.json.JSONObject
getJson()

java.lang.String
getJsonName()

May be overridden to name the JSON object returned from Jsonable.getJson().

java.lang.String
getName()

java.util.List<java.lang.String>
getOptions()

java.lang.String
getType()

java.lang.Object
getValue()

java.util.List<Pagelet.Widget>
getWidgets()

void
setAdapter(WidgetAdapter adapter)

void
setAttribute(java.lang.String name,
            java.lang.String val)

void
setAttributes(java.util.Map<java.lang.String,java.lang.String> attrs)

void
setName(java.lang.String name)

void
setOptions(java.util.List<java.lang.String> options)

void
setValue(java.lang.Object value)

void
setWidgets(java.util.List<Pagelet.Widget> widgets)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Methods inherited from interface com.centurylink.mdw.model.Jsonable

create

Methods inherited from interface io.limberest.json.Jsonable

bind, jsonName, toJson

Constructor Detail

Widget

public Widget(java.lang.String name,
              java.lang.String type)

Widget

public Widget(org.json.JSONObject json)
       throws org.json.JSONException

Throws:

org.json.JSONException

Method Detail

getType

public java.lang.String getType()

getName

public java.lang.String getName()

setName

public void setName(java.lang.String name)

getValue

public java.lang.Object getValue()

setValue

public void setValue(java.lang.Object value)

getAttributes

public java.util.Map<java.lang.String,java.lang.String> getAttributes()

everything but name, type and options

setAttributes

public void setAttributes(java.util.Map<java.lang.String,java.lang.String> attrs)

getOptions

public java.util.List<java.lang.String> getOptions()

setOptions

public void setOptions(java.util.List<java.lang.String> options)

getWidgets

public java.util.List<Pagelet.Widget> getWidgets()

setWidgets

public void setWidgets(java.util.List<Pagelet.Widget> widgets)

getAdapter

public WidgetAdapter getAdapter()

setAdapter

public void setAdapter(WidgetAdapter adapter)

addWidget

public void addWidget(Pagelet.Widget widget)

getAttribute

public java.lang.String getAttribute(java.lang.String name)

setAttribute

public void setAttribute(java.lang.String name,
                         java.lang.String val)

addOption

public void addOption(java.lang.String option)

getJson

public org.json.JSONObject getJson()
                            throws org.json.JSONException

Throws:

org.json.JSONException

getJsonName

public java.lang.String getJsonName()

Description copied from interface: Jsonable

May be overridden to name the JSON object returned from Jsonable.getJson().

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2019 CenturyLink, Inc.


text:
//
// Created by jrusnak on 7/22/16.
//

#ifndef __PYLLARS_INTERNAL__GLOBALMEMBERSEMANTICS_CPP__
#define __PYLLARS_INTERNAL__GLOBALMEMBERSEMANTICS_CPP__

#include "pyllars_globalmembersemantics.hpp"
#include "pyllars_pointer.impl.hpp"

namespace __pyllars_internal{

    template<typename T>
    PyObject *
    GlobalVariable::
    createGlobalVariable(const char *const name,
                            T *variable,
                            PyObject *module,
                            const size_t size) {
        if (!name || !module) {
            PyErr_SetString(PyExc_RuntimeError, "Null name or module on global variable creation");
            return nullptr;
        }
        static bool inited = false;
        PyTypeObject *type = &Container<T>::Type;
        if (!inited && (PyType_Ready(type) < 0)) {
            PyErr_SetString(PyExc_RuntimeError, "Unable to initialize python object for c function global variable wrapper");
            return nullptr;
        } else {
            Py_INCREF(type);
            static PyObject *emptyargs = PyTuple_New(0);
            inited = true;
            auto callable = (Container <T> *) PyObject_CallObject((PyObject *) type, emptyargs);
            if (!PyCallable_Check((PyObject *) callable)) {
                PyErr_SetString(PyExc_RuntimeError, "Python object is not callbable as expected!");
                return nullptr;
            }
            callable->member = (typename Container<T>::member_t) variable;
            callable->array_size = size;
            PyModule_AddObject(module, name, reinterpret_cast<PyObject *>(callable));
            return reinterpret_cast<PyObject *>(callable);
        }
    }

    template<typename T>
    int
    GlobalVariable::
    Container<T>::
    _init(PyObject *self, PyObject *args, PyObject *kwds) {
        //avoid compiler warnings
        (void) self;
        (void) args;
        (void) kwds;

        return 0;
    }

    template<typename T>
    PyObject *
    GlobalVariable::Container<T>::
    _new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
        (void) args;
        (void) kwds;
        return type->tp_alloc(type, 0);
    }

    template<typename T>
    PyObject *GlobalVariable::Container<T>::
    call(Container *callable, PyObject *args, PyObject *kwds) {
        if constexpr(!std::is_array<T>::value && !std::is_const<T>::value) {
            try {
                typedef typename std::remove_pointer<typename extent_as_pointer<T>::type>::type T_base;
                const ssize_t type_size = Sizeof<T_base>::value;
                const ssize_t array_size = type_size > 0 ? sizeof(*(callable->member)) / type_size : 1;
                if (((kwds ? PyDict_Size(kwds) : 0) + PyTuple_Size(args)) > 1) {
                    PyErr_SetString(PyExc_TypeError, "Invalid parameters when getting/setting global variable");
                    return nullptr;
                } else if (kwds && PyDict_Size(kwds) == 1) {
                    PyObject *const v = PyDict_GetItemString(kwds, "_CObject");
                    if (v) {
                        *(callable->member) = toCArgument<T>(*v).value();
                    } else {
                        PyErr_SetString(PyExc_TypeError, "Invalid parameters when getting/setting global variable");
                        return nullptr;
                    }

                } else if (PyTuple_Size(args) == 1) {
                    *(callable->member) = toCArgument<T>(*PyTuple_GetItem(args, 0)).value();
                }
                return toPyObject<T&>(*callable->member, array_size);
            } catch (PyllarsException &e) {
                e.raise();
                return nullptr;
            } catch(std::exception const & e) {
                PyllarsException::raise_internal_cpp(e.what());
                return nullptr;
            } catch (...) {
                PyllarsException::raise_internal_cpp();
                return nullptr;
            }
        } else if constexpr (std::is_array<T>::value && ArraySize<T>::size > 0){
            typedef typename std::remove_pointer<typename extent_as_pointer<T>::type>::type T_base;
            if (kwds && PyDict_Size(kwds) == 1 && PyDict_GetItemString(kwds, "_CObject")) {
                T_base val[ArraySize<T>::size];
                auto cval = *toCArgument<T_base, true, PythonClassWrapper<T> >(*PyDict_GetItemString(kwds, "_CObject"));
                //for(unsigned int i = 0; i < size; ++i)
                //    val[i] = cval[i];
                for (size_t i = 0; i < ArraySize<T>::size; ++i) (*callable->member)[i] = cval[i];
            } else if (kwds) {
                PyErr_SetString(PyExc_RuntimeError, "Invalid parameters when getting/setting global variable");
                return nullptr;
            }
            return toPyObject<T>(*callable->member, ArraySize<T>::size);
        } else if constexpr (std::is_array<T>::value){
            typedef typename extent_as_pointer<T>::type T_ptr;
            typedef typename std::remove_pointer<typename extent_as_pointer<T>::type>::type T_base;
            if (kwds && PyDict_Size(kwds) == 1 && PyDict_GetItemString(kwds, "_CObject")) {
                if (callable->array_size < 0) {
                    PyErr_SetString(PyExc_RuntimeError, "Attempt to set whole array of unknown size");
                    return nullptr;
                }
                T_ptr val = *toCArgument<T_ptr, true, PythonClassWrapper<T_ptr> >(*PyDict_GetItemString(kwds, "_CObject"));
                for (size_t i = 0; i < callable->array_size; ++i) (*callable->member)[i] = val[i];
            } else if (kwds && PyDict_Size(kwds) == 2 && PyDict_GetItemString(kwds, "_CObject") &&
                       PyDict_GetItemString(kwds, "index") &&
                       PyLong_Check(PyDict_GetItemString(kwds, "index"))) {
                long i = PyLong_AsLong(PyDict_GetItemString(kwds, "index"));
                T_ptr val = *toCArgument<T *, false, PythonClassWrapper<T_ptr> >(*PyDict_GetItemString(kwds, "_CObject"));
                (*callable->member)[i] = val[i];
            } else if (kwds && PyDict_Size(kwds) != 0) {
                PyErr_SetString(PyExc_RuntimeError, "Invalid parameters when getting/setting global variable");
                return nullptr;
            }
            const ssize_t type_size = Sizeof<T_base>::value;
            const ssize_t array_size = type_size > 0 ? sizeof(*(callable->member)) / type_size : 1;
            return toPyObject<T&>(*callable->member, array_size);
        } else {
            if (kwds && PyDict_GetItemString(kwds, "_CObject")) {
                PyErr_SetString(PyExc_RuntimeError, "Cannot set const global variable!");
                return nullptr;
            } else if (kwds && PyDict_Size(kwds) != 0) {
                PyErr_SetString(PyExc_RuntimeError, "Invalid parameters when getting/setting global variable");
                return nullptr;
            }
            typedef typename std::remove_pointer<typename extent_as_pointer<T>::type>::type T_base;
            const ssize_t type_size = Sizeof<T_base>::value;
            const ssize_t array_size = type_size > 0 ? sizeof(*(callable->member)) / type_size : 1;
            return toPyObject<T&>(*callable->member, array_size);
        }
    }

    //Python definition of Type for this function wrapper
    template<typename T>
    PyTypeObject GlobalVariable::Container<T>::Type = {
        #if PY_MAJOR_VERSION == 3
                PyVarObject_HEAD_INIT(nullptr, 0)
        #else
                PyObject_HEAD_INIT(nullptr)
                0,                               /*ob_size*/
        #endif
            type_name<T>(),                         /*tp_name*/
            sizeof(GlobalVariable::Container<T>),   /*tp_basicsize*/
            0,                               /*tp_itemsize*/
            nullptr,                         /*tp_dealloc*/
            nullptr,                         /*tp_print*/
            nullptr,                         /*tp_getattr*/
            nullptr,                         /*tp_setattr*/
            nullptr,                         /*tp_compare*/
            nullptr,                         /*tp_repr*/
            nullptr,                         /*tp_as_number*/
            nullptr,                         /*tp_as_sequence*/
            nullptr,                         /*tp_as_mapping*/
            nullptr,                         /*tp_hash */
            (ternaryfunc) call,                           /*tp_call*/
            nullptr,                         /*tp_str*/
            nullptr,                         /*tp_getattro*/
            nullptr,                         /*tp_setattro*/
            nullptr,                         /*tp_as_buffer*/
            Py_TPFLAGS_DEFAULT, /*tp_flags*/
            "Global variable object",  /* tp_doc */
            nullptr,                         /* tp_traverse */
            nullptr,                         /* tp_clear */
            nullptr,                         /* tp_richcompare */
            0,                                 /* tp_weaklistoffset */
            nullptr,                         /* tp_iter */
            nullptr,                         /* tp_iternext */
            nullptr,                         /* tp_methods */
            nullptr,                         /* tp_members */
            nullptr,                         /* tp_getset */
            nullptr,                         /* tp_base */
            nullptr,                         /* tp_dict */
            nullptr,                         /* tp_descr_get */
            nullptr,                         /* tp_descr_set */
            0,                               /* tp_dictoffset */
            _init,  /* tp_init */
            nullptr,                         /* tp_alloc */
            _new,     /* tp_new */
            nullptr,                         /*tp_free*/ //TODO: Implement a free??
            nullptr,                         /*tp_is_gc*/
            nullptr,                         /*tp_bass*/
            nullptr,                         /*tp_mro*/
            nullptr,                         /*tp_cache*/
            nullptr,                         /*tp_subclasses*/
            nullptr,                          /*tp_weaklist*/
            nullptr,                          /*tp_del*/
            0,                          /*tp_version_tag*/
    };

}

#endif


text:
<?php
class Task_model extends CI_Model
{
	public function get_task($task_id){
		$this->db->where('id', $task_id);

		$query = $this->db->get('tasks');

		if ($query->num_rows() >0){
			return $query->row(0);
		} else {
			return false;
		}
	}

	public function create_task($data){
		if($this->db->insert('tasks', $data)){
			return true;
		} else {
			return false;
		}
	}

	public function update_task($taskid, $data) {
		$this->db->where('id', $taskid);

		if($this->db->update('tasks', $data)){
			return true;
		} else {
			return false;
		}
	}

	public function delete_task($taskid) {
		$this->db->where('id', $taskid);
		if($this->db->delete('tasks')){
			return true;
		} else {
			return false;
		}
	}

	public function complete_task($taskid) {
		$this->db->where('id', $taskid);
		$data = [
			'status' => 0
		];
		if($this->db->update('tasks', $data)){
			return true;
		} else {
			return false;
		}
	}

	public function incomplete_task($taskid) {
		$this->db->where('id', $taskid);
		$data = [
			'status' => 1
		];
		if($this->db->update('tasks', $data)){
			return true;
		} else {
			return false;
		}
	}

	public function getTasks($userid) {
		$this->db->where('projects.user_id', $userid );
		$this->db->join('tasks', 'projects.id = tasks.project_id');
		$query = $this->db->get('projects');

		return $query->result();

	}

	public function getProjectId($task_id){
		$this->db->where('id', $task_id);

		$query = $this->db->get('tasks');
		return $query->row(0)->project_id;

	}

}


text:
import pytest, py, sys, os
from _pytest import runner
from py._code.code import ReprExceptionInfo

class TestSetupState:
    def test_setup(self, testdir):
        ss = runner.SetupState()
        item = testdir.getitem("def test_func(): pass")
        l = [1]
        ss.prepare(item)
        ss.addfinalizer(l.pop, colitem=item)
        assert l
        ss._pop_and_teardown()
        assert not l

    def test_setup_scope_None(self, testdir):
        item = testdir.getitem("def test_func(): pass")
        ss = runner.SetupState()
        l = [1]
        ss.prepare(item)
        ss.addfinalizer(l.pop, colitem=None)
        assert l
        ss._pop_and_teardown()
        assert l
        ss._pop_and_teardown()
        assert l
        ss.teardown_all()
        assert not l

    def test_teardown_exact_stack_empty(self, testdir):
        item = testdir.getitem("def test_func(): pass")
        ss = runner.SetupState()
        ss.teardown_exact(item, None)
        ss.teardown_exact(item, None)
        ss.teardown_exact(item, None)

    def test_setup_fails_and_failure_is_cached(self, testdir):
        item = testdir.getitem("""
            def setup_module(mod):
                raise ValueError(42)
            def test_func(): pass
        """)
        ss = runner.SetupState()
        pytest.raises(ValueError, "ss.prepare(item)")
        pytest.raises(ValueError, "ss.prepare(item)")

class BaseFunctionalTests:
    def test_passfunction(self, testdir):
        reports = testdir.runitem("""
            def test_func():
                pass
        """)
        rep = reports[1]
        assert rep.passed
        assert not rep.failed
        assert rep.outcome == "passed"
        assert not rep.longrepr

    def test_failfunction(self, testdir):
        reports = testdir.runitem("""
            def test_func():
                assert 0
        """)
        rep = reports[1]
        assert not rep.passed
        assert not rep.skipped
        assert rep.failed
        assert rep.when == "call"
        assert rep.outcome == "failed"
        #assert isinstance(rep.longrepr, ReprExceptionInfo)

    def test_skipfunction(self, testdir):
        reports = testdir.runitem("""
            import pytest
            def test_func():
                pytest.skip("hello")
        """)
        rep = reports[1]
        assert not rep.failed
        assert not rep.passed
        assert rep.skipped
        assert rep.outcome == "skipped"
        #assert rep.skipped.when == "call"
        #assert rep.skipped.when == "call"
        #assert rep.skipped == "%sreason == "hello"
        #assert rep.skipped.location.lineno == 3
        #assert rep.skipped.location.path
        #assert not rep.skipped.failurerepr

    def test_skip_in_setup_function(self, testdir):
        reports = testdir.runitem("""
            import pytest
            def setup_function(func):
                pytest.skip("hello")
            def test_func():
                pass
        """)
        print(reports)
        rep = reports[0]
        assert not rep.failed
        assert not rep.passed
        assert rep.skipped
        #assert rep.skipped.reason == "hello"
        #assert rep.skipped.location.lineno == 3
        #assert rep.skipped.location.lineno == 3
        assert len(reports) == 2
        assert reports[1].passed # teardown

    def test_failure_in_setup_function(self, testdir):
        reports = testdir.runitem("""
            import pytest
            def setup_function(func):
                raise ValueError(42)
            def test_func():
                pass
        """)
        rep = reports[0]
        assert not rep.skipped
        assert not rep.passed
        assert rep.failed
        assert rep.when == "setup"
        assert len(reports) == 2

    def test_failure_in_teardown_function(self, testdir):
        reports = testdir.runitem("""
            import pytest
            def teardown_function(func):
                raise ValueError(42)
            def test_func():
                pass
        """)
        print(reports)
        assert len(reports) == 3
        rep = reports[2]
        assert not rep.skipped
        assert not rep.passed
        assert rep.failed
        assert rep.when == "teardown"
        #assert rep.longrepr.reprcrash.lineno == 3
        #assert rep.longrepr.reprtraceback.reprentries

    def test_custom_failure_repr(self, testdir):
        testdir.makepyfile(conftest="""
            import pytest
            class Function(pytest.Function):
                def repr_failure(self, excinfo):
                    return "hello"
        """)
        reports = testdir.runitem("""
            import pytest
            def test_func():
                assert 0
        """)
        rep = reports[1]
        assert not rep.skipped
        assert not rep.passed
        assert rep.failed
        #assert rep.outcome.when == "call"
        #assert rep.failed.where.lineno == 3
        #assert rep.failed.where.path.basename == "test_func.py"
        #assert rep.failed.failurerepr == "hello"

    def test_teardown_final_returncode(self, testdir):
        rec = testdir.inline_runsource("""
            def test_func():
                pass
            def teardown_function(func):
                raise ValueError(42)
        """)
        assert rec.ret == 1

    def test_exact_teardown_issue90(self, testdir):
        rec = testdir.inline_runsource("""
            import pytest

            class TestClass:
                def test_method(self):
                    pass
                def teardown_class(cls):
                    raise Exception()

            def test_func():
                pass
            def teardown_function(func):
                raise ValueError(42)
        """)
        reps = rec.getreports("pytest_runtest_logreport")
        print (reps)
        for i in range(2):
            assert reps[i].nodeid.endswith("test_method")
            assert reps[i].passed
        assert reps[2].when == "teardown"
        assert reps[2].failed
        assert len(reps) == 6
        for i in range(3,5):
            assert reps[i].nodeid.endswith("test_func")
            assert reps[i].passed
        assert reps[5].when == "teardown"
        assert reps[5].nodeid.endswith("test_func")
        assert reps[5].failed

    def test_failure_in_setup_function_ignores_custom_repr(self, testdir):
        testdir.makepyfile(conftest="""
            import pytest
            class Function(pytest.Function):
                def repr_failure(self, excinfo):
                    assert 0
        """)
        reports = testdir.runitem("""
            def setup_function(func):
                raise ValueError(42)
            def test_func():
                pass
        """)
        assert len(reports) == 2
        rep = reports[0]
        print(rep)
        assert not rep.skipped
        assert not rep.passed
        assert rep.failed
        #assert rep.outcome.when == "setup"
        #assert rep.outcome.where.lineno == 3
        #assert rep.outcome.where.path.basename == "test_func.py"
        #assert instanace(rep.failed.failurerepr, PythonFailureRepr)

    def test_systemexit_does_not_bail_out(self, testdir):
        try:
            reports = testdir.runitem("""
                def test_func():
                    raise SystemExit(42)
            """)
        except SystemExit:
            py.test.fail("runner did not catch SystemExit")
        rep = reports[1]
        assert rep.failed
        assert rep.when == "call"

    def test_exit_propagates(self, testdir):
        try:
            testdir.runitem("""
                import pytest
                def test_func():
                    raise pytest.exit.Exception()
            """)
        except py.test.exit.Exception:
            pass
        else:
            py.test.fail("did not raise")

class TestExecutionNonForked(BaseFunctionalTests):
    def getrunner(self):
        def f(item):
            return runner.runtestprotocol(item, log=False)
        return f

    def test_keyboardinterrupt_propagates(self, testdir):
        try:
            testdir.runitem("""
                def test_func():
                    raise KeyboardInterrupt("fake")
            """)
        except KeyboardInterrupt:
            pass
        else:
            py.test.fail("did not raise")

class TestExecutionForked(BaseFunctionalTests):
    pytestmark = pytest.mark.skipif("not hasattr(os, 'fork')")

    def getrunner(self):
        # XXX re-arrange this test to live in pytest-xdist
        xplugin = py.test.importorskip("xdist.plugin")
        return xplugin.forked_run_report

    def test_suicide(self, testdir):
        reports = testdir.runitem("""
            def test_func():
                import os
                os.kill(os.getpid(), 15)
        """)
        rep = reports[0]
        assert rep.failed
        assert rep.when == "???"

class TestSessionReports:
    def test_collect_result(self, testdir):
        col = testdir.getmodulecol("""
            def test_func1():
                pass
            class TestClass:
                pass
        """)
        rep = runner.pytest_make_collect_report(col)
        assert not rep.failed
        assert not rep.skipped
        assert rep.passed
        locinfo = rep.location
        assert locinfo[0] == col.fspath.basename
        assert not locinfo[1]
        assert locinfo[2] == col.fspath.basename
        res = rep.result
        assert len(res) == 2
        assert res[0].name == "test_func1"
        assert res[1].name == "TestClass"

    def test_skip_at_module_scope(self, testdir):
        col = testdir.getmodulecol("""
            import pytest
            pytest.skip("hello")
            def test_func():
                pass
        """)
        rep = runner.pytest_make_collect_report(col)
        assert not rep.failed
        assert not rep.passed
        assert rep.skipped

reporttypes = [
    runner.BaseReport,
    runner.TestReport,
    runner.TeardownErrorReport,
    runner.CollectReport,
]

@pytest.mark.parametrize('reporttype', reporttypes, ids=[x.__name__ for x in reporttypes])
def test_report_extra_parameters(reporttype):
    args = py.std.inspect.getargspec(reporttype.__init__)[0][1:]
    basekw = dict.fromkeys(args, [])
    report = reporttype(newthing=1, **basekw)
    assert report.newthing == 1

def test_callinfo():
    ci = runner.CallInfo(lambda: 0, '123')
    assert ci.when == "123"
    assert ci.result == 0
    assert "result" in repr(ci)
    ci = runner.CallInfo(lambda: 0/0, '123')
    assert ci.when == "123"
    assert not hasattr(ci, 'result')
    assert ci.excinfo
    assert "exc" in repr(ci)

# design question: do we want general hooks in python files?
# then something like the following functional tests makes sense
@pytest.mark.xfail
def test_runtest_in_module_ordering(testdir):
    p1 = testdir.makepyfile("""
        def pytest_runtest_setup(item): # runs after class-level!
            item.function.mylist.append("module")
        class TestClass:
            def pytest_runtest_setup(self, item):
                assert not hasattr(item.function, 'mylist')
                item.function.mylist = ['class']
            def pytest_funcarg__mylist(self, request):
                return request.function.mylist
            def pytest_runtest_call(self, item, __multicall__):
                try:
                    __multicall__.execute()
                except ValueError:
                    pass
            def test_hello1(self, mylist):
                assert mylist == ['class', 'module'], mylist
                raise ValueError()
            def test_hello2(self, mylist):
                assert mylist == ['class', 'module'], mylist
        def pytest_runtest_teardown(item):
            del item.function.mylist
    """)
    result = testdir.runpytest(p1)
    result.stdout.fnmatch_lines([
        "*2 passed*"
    ])

def test_pytest_exit():
    try:
        py.test.exit("hello")
    except py.test.exit.Exception:
        excinfo = py.code.ExceptionInfo()
        assert excinfo.errisinstance(KeyboardInterrupt)

def test_pytest_fail():
    try:
        py.test.fail("hello")
    except py.test.fail.Exception:
        excinfo = py.code.ExceptionInfo()
        s = excinfo.exconly(tryshort=True)
        assert s.startswith("Failed")

def test_pytest_fail_notrace(testdir):
    testdir.makepyfile("""
        import pytest
        def test_hello():
            pytest.fail("hello", pytrace=False)
        def teardown_function(function):
            pytest.fail("world", pytrace=False)
    """)
    result = testdir.runpytest()
    result.stdout.fnmatch_lines([
        "world",
        "hello",
    ])
    assert 'def teardown_function' not in result.stdout.str()

def test_exception_printing_skip():
    try:
        pytest.skip("hello")
    except pytest.skip.Exception:
        excinfo = py.code.ExceptionInfo()
        s = excinfo.exconly(tryshort=True)
        assert s.startswith("Skipped")

def test_importorskip():
    importorskip = py.test.importorskip
    def f():
        importorskip("asdlkj")
    try:
        sys = importorskip("sys")
        assert sys == py.std.sys
        #path = py.test.importorskip("os.path")
        #assert path == py.std.os.path
        excinfo = pytest.raises(pytest.skip.Exception, f)
        path = py.path.local(excinfo.getrepr().reprcrash.path)
        # check that importorskip reports the actual call
        # in this test the test_runner.py file
        assert path.purebasename == "test_runner"
        pytest.raises(SyntaxError, "py.test.importorskip('x y z')")
        pytest.raises(SyntaxError, "py.test.importorskip('x=y')")
        path = importorskip("py", minversion=".".join(py.__version__))
        mod = py.std.types.ModuleType("hello123")
        mod.__version__ = "1.3"
        pytest.raises(pytest.skip.Exception, """
            py.test.importorskip("hello123", minversion="5.0")
        """)
    except pytest.skip.Exception:
        print(py.code.ExceptionInfo())
        py.test.fail("spurious skip")

def test_importorskip_imports_last_module_part():
    ospath = py.test.importorskip("os.path")
    assert os.path == ospath

def test_pytest_cmdline_main(testdir):
    p = testdir.makepyfile("""
        import py
        def test_hello():
            assert 1
        if __name__ == '__main__':
           py.test.cmdline.main([__file__])
    """)
    import subprocess
    popen = subprocess.Popen([sys.executable, str(p)], stdout=subprocess.PIPE)
    s = popen.stdout.read()
    ret = popen.wait()
    assert ret == 0


text:
namespace Umbraco.Cms.Infrastructure.Migrations.Expressions.Delete.DefaultConstraint
{
    /// <summary>
    /// Builds a Delete expression.
    /// </summary>
    public interface IDeleteDefaultConstraintOnTableBuilder : IFluentBuilder
    {
        /// <summary>
        /// Specifies the table of the constraint to delete.
        /// </summary>
        IDeleteDefaultConstraintOnColumnBuilder OnTable(string tableName);
    }
}


text:
import test from 'ava';
import semver from 'semver';
import semverRegex from 'semver-regex';
import latestVersion from './index.js';

test('latest version', async t => {
	t.regex(await latestVersion('ava'), semverRegex());
});

test('latest version with version', async t => {
	t.true(semver.satisfies(await latestVersion('package-json', {version: '0'}), '0.x'));
});

test('latest version with dist-tag', async t => {
	t.true(semver.satisfies(await latestVersion('npm', {version: 'latest-5'}), '5.x'));
});

test('latest version scoped', async t => {
	t.regex(await latestVersion('@sindresorhus/df'), semverRegex());
});


text:
/******************************************************************************
 * @section DESCRIPTION
 *
 * This routine solves the atmospheric exchange moisture balance.
 *****************************************************************************/

#include <vic_run.h>

/******************************************************************************
 * @brief    This routine solves the atmospheric exchange moisture balance.
 *****************************************************************************/
double
func_atmos_moist_bal(double  VPcanopy,
                     va_list ap)
{
    double  InLatentHeat;
    double  Lv;
    double  Ra;
    double  atmos_density;
    double  gamma;
    double  vp; // atmospheric vapor pressure

    double *LatentHeat;

    // internal routine variables
    double  Error;

    // extract variables from va_arg
    InLatentHeat = (double)  va_arg(ap, double);
    Lv = (double)  va_arg(ap, double);
    Ra = (double)  va_arg(ap, double);
    atmos_density = (double)  va_arg(ap, double);
    gamma = (double)  va_arg(ap, double);
    vp = (double)  va_arg(ap, double);

    LatentHeat = (double *) va_arg(ap, double *);

    // compute sensible heat flux between canopy and atmosphere
    (*LatentHeat) = Lv * calc_sensible_heat(atmos_density, vp, VPcanopy,
                                            gamma * Ra);

    // compute energy balance error
    Error = InLatentHeat - (*LatentHeat);

    return (Error);
}


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

/**
 * @fileoverview Demo login UI.
 */

/**
 * Handles a user clicking anywhere on the screen. This will log the demo user
 * in. Yes, this actually _is the intention.
 * @param {Event} e The click event that triggered this function.
 */
onClick = function(e) {
  document.removeEventListener('click', onClick);
  e.stopPropagation();
  chrome.send('launchDemoUser');
};

/**
 * Initializes the click handler.
 */
initialize = function() {
  $('page').style.opacity = 1;
  document.addEventListener('click', onClick);
  chrome.send('demoWebuiReady');
  // Report back sign in UI being painted.
  window.webkitRequestAnimationFrame(function() {
    chrome.send('loginVisible');
  });
};

disableTextSelectAndDrag();
document.addEventListener('DOMContentLoaded', initialize);


text:
<?php

namespace Scalr\Service\OpenStack\Client\Auth;

use Scalr\Service\OpenStack\Exception\OpenStackException;
use Scalr\Service\OpenStack\OpenStackConfig;

class RequestBuilderV3 implements RequestBuilderInterface
{

    /**
     * {@inheritdoc}
     * @see RequestInterface::makeRequest()
     */
    public function makeRequest(OpenStackConfig $config)
    {
        if ($config->getApiKey() !== null) {
            $requestBody = [
                'auth' => [
                    'identity' => [
                        'methods' => [
                            'token'
                        ],
                        'token' => [
                            'id' => $config->getApiKey()
                        ]
                    ]
                ]
            ];
        } else if ($config->getPassword() !== null) {
            $requestBody = [
                'auth' => [
                    'identity' => [
                        'methods' => [
                            'password'
                        ],
                        'password' => [
                            'user' => [
                                'password'  => $config->getPassword()
                            ]
                        ]
                    ]
                ]
            ];

            if ($config->getUserId()) {
                $requestBody['auth']['identity']['password']['user']['id'] = $config->getUserId();
            } else if ($config->getUsername()) {
                $requestBody['auth']['identity']['password']['user']['name'] = $config->getUsername();
            } else {
                throw new OpenStackException(
                    'Neither user name nor user id was provided for the OpenStack config.'
                );
            }
        } else {
            throw new OpenStackException(
                'Neither api key nor password was provided for the OpenStack config.'
            );
        }

        if ($config->getProjectId() !== null) {
            $requestBody['auth']['scope']['project']['id'] = $config->getProjectId();
        } else if ($config->getTenantName() !== null) {
            $requestBody['auth']['scope']['project']['name'] = $config->getTenantName();
        }

        return $requestBody;
    }
}


text:
#pragma once

#include "items/Item.h"
#include "layouts/SequentialLayoutStyle.h"
#include "layouts/SequentialLayout.h"
#include "shapes/BoxStyle.h"

namespace Visualization {

class BoxTest : public Super<Item>
{
	ITEM_COMMON_CUSTOM_STYLENAME(BoxTest, ItemStyle)

	public:
		BoxTest(Item* parent, int sub);

		void determineChildren();
		void updateGeometry(int availableWidth, int availableHeight);

	private:
		SequentialLayout items;
};

}


text:
@interface HomeViewController ()
@property (nonatomic, strong) UILabel *calendarLabel;
@property (nonatomic, strong) UIImageView *backgroundImageView;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) HomeComponentCoverView *coverView;        // 封面
@property (nonatomic, strong) HomeComponentAccessView *accessView;      // 便捷访问
@property (nonatomic, strong) HomeComponentActivityView *activityView;  // 特色活动
@property (nonatomic, strong) HomeComponentScheduleView *scheduleView;  // 课表
@property (nonatomic, strong) HomeComponentNewsView *newsView;          // 新闻

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = NSLocalizedString(@"HomeNavigationBarTitle", nil);
    [self initConstraints];
}

- (void)initConstraints {

    self.scrollView.frame = self.view.frame;

    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.width.equalTo(self.view);
    }];

    [self.coverView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentView.mas_top);
        make.left.and.right.equalTo(self.contentView);
    }];

    [self.accessView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.coverView.mas_bottom);
        make.left.and.right.equalTo(self.contentView);
    }];

    [self.activityView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.accessView.mas_bottom);
        make.left.and.right.equalTo(self.contentView);
    }];

    [self.scheduleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.activityView.mas_bottom);
        make.left.and.right.equalTo(self.contentView);
    }];

    [self.newsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.scheduleView.mas_bottom);
        make.left.and.right.equalTo(self.contentView);
        make.bottom.equalTo(self.contentView);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

#pragma mark - Getter

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:_scrollView];
    }

    return _scrollView;
}

- (UIView *)contentView {
    if (!_contentView) {
        _contentView = [[UIView alloc] init];
        [self.scrollView addSubview:_contentView];
    }

    return _contentView;
}

- (UIImageView *)backgroundImageView {
    if (!_backgroundImageView) {
        _backgroundImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home"]];
        [self.view addSubview:_backgroundImageView];
    }

    return _backgroundImageView;
}

- (HomeComponentAccessView *)accessView {
    if (!_accessView) {
        _accessView = [[HomeComponentAccessView alloc] init];
        [self.contentView addSubview:_accessView];
    }

    return _accessView;
}

- (HomeComponentCoverView *)coverView {
    if (!_coverView) {
        _coverView = [[HomeComponentCoverView alloc] init];
        [self.contentView addSubview:_coverView];
    }

    return _coverView;
}

- (HomeComponentScheduleView *)scheduleView {
    if (!_scheduleView) {
        _scheduleView = [[HomeComponentScheduleView alloc] init];
        [self.contentView addSubview:_scheduleView];
    }

    return _scheduleView;
}

- (HomeComponentActivityView *)activityView {
    if (!_activityView) {
        _activityView = [[HomeComponentActivityView alloc] init];
        [self.contentView addSubview:_activityView];
    }

    return _activityView;
}

- (HomeComponentNewsView *)newsView {
    if (!_newsView) {
        _newsView = [[HomeComponentNewsView alloc] init];
        [self.contentView addSubview:_newsView];
    }

    return _newsView;
}

@end


text:
from google.appengine.ext import ndb

class Event(ndb.Model):
    tag = ndb.StringProperty()
    done = ndb.BooleanProperty()
    created = ndb.DateTimeProperty(auto_now_add=True)
    updated = ndb.DateTimeProperty(auto_now=True)

    @classmethod
    def create_or_update(cls, calendar_key, _id, tag, done=False):
        if not _id:
            raise ValueError('Invalid id for Event object.')

        event = cls.get_or_insert(_id, parent=calendar_key,
                                  tag=tag,
                                  done=done)
        if event.tag != tag or event.done != done:
            event.tag = tag
            event.done = done
            event.put()

        return event

    @classmethod
    def get_all(cls, calendar_key):
        return cls.query(ancestor=calendar_key)