text
stringlengths 2
100k
| meta
dict |
---|---|
// Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2007-2008 Steven Watanabe
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_UNITS_IMPERIAL_THOU_BASE_UNIT_HPP
#define BOOST_UNITS_IMPERIAL_THOU_BASE_UNIT_HPP
#include <boost/units/scaled_base_unit.hpp>
#include <boost/units/static_rational.hpp>
#include <boost/units/scale.hpp>
#include <boost/units/base_units/imperial/yard.hpp>
namespace boost {
namespace units {
namespace imperial {
typedef scaled_base_unit<yard_base_unit, scale<36000, static_rational<-1> > > thou_base_unit;
} // namespace imperial
template<>
struct base_unit_info<imperial::thou_base_unit> {
static const char* name() { return("thou"); }
static const char* symbol() { return("thou"); }
};
} // namespace units
} // namespace boost
#endif // BOOST_UNITS_IMPERIAL_THOU_BASE_UNIT_HPP
| {
"pile_set_name": "Github"
} |
package com.evanlennick.retry4j.exception;
/**
* This exception represents when a call throws an exception that was not specified as one to retry on in the
* RetryConfig.
*/
public class UnexpectedException extends Retry4jException {
public UnexpectedException(String message, Throwable cause) {
super(message, cause);
}
}
| {
"pile_set_name": "Github"
} |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sts=4 et sw=4 tw=99:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "builtin/RegExp.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/TypeTraits.h"
#include "frontend/TokenStream.h"
#include "irregexp/RegExpParser.h"
#include "jit/InlinableNatives.h"
#include "util/StringBuffer.h"
#include "util/Unicode.h"
#include "vm/JSContext.h"
#include "vm/RegExpStatics.h"
#include "vm/SelfHosting.h"
#include "vm/JSObject-inl.h"
#include "vm/NativeObject-inl.h"
#include "vm/UnboxedObject-inl.h"
using namespace js;
using namespace js::unicode;
using mozilla::CheckedInt;
/*
* ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2
* steps 3, 16-25.
*/
bool
js::CreateRegExpMatchResult(JSContext* cx, HandleString input, const MatchPairs& matches,
MutableHandleValue rval)
{
MOZ_ASSERT(input);
/*
* Create the (slow) result array for a match.
*
* Array contents:
* 0: matched string
* 1..pairCount-1: paren matches
* input: input string
* index: start index for the match
*/
/* Get the templateObject that defines the shape and type of the output object */
JSObject* templateObject = cx->compartment()->regExps.getOrCreateMatchResultTemplateObject(cx);
if (!templateObject)
return false;
size_t numPairs = matches.length();
MOZ_ASSERT(numPairs > 0);
/* Step 17. */
RootedArrayObject arr(cx, NewDenseFullyAllocatedArrayWithTemplate(cx, numPairs, templateObject));
if (!arr)
return false;
/* Steps 22-24.
* Store a Value for each pair. */
for (size_t i = 0; i < numPairs; i++) {
const MatchPair& pair = matches[i];
if (pair.isUndefined()) {
MOZ_ASSERT(i != 0); /* Since we had a match, first pair must be present. */
arr->setDenseInitializedLength(i + 1);
arr->initDenseElement(i, UndefinedValue());
} else {
JSLinearString* str = NewDependentString(cx, input, pair.start, pair.length());
if (!str)
return false;
arr->setDenseInitializedLength(i + 1);
arr->initDenseElement(i, StringValue(str));
}
}
/* Step 20 (reordered).
* Set the |index| property. (TemplateObject positions it in slot 0) */
arr->setSlot(0, Int32Value(matches[0].start));
/* Step 21 (reordered).
* Set the |input| property. (TemplateObject positions it in slot 1) */
arr->setSlot(1, StringValue(input));
#ifdef DEBUG
RootedValue test(cx);
RootedId id(cx, NameToId(cx->names().index));
if (!NativeGetProperty(cx, arr, id, &test))
return false;
MOZ_ASSERT(test == arr->getSlot(0));
id = NameToId(cx->names().input);
if (!NativeGetProperty(cx, arr, id, &test))
return false;
MOZ_ASSERT(test == arr->getSlot(1));
#endif
/* Step 25. */
rval.setObject(*arr);
return true;
}
static int32_t
CreateRegExpSearchResult(const MatchPairs& matches)
{
/* Fit the start and limit of match into a int32_t. */
uint32_t position = matches[0].start;
uint32_t lastIndex = matches[0].limit;
MOZ_ASSERT(position < 0x8000);
MOZ_ASSERT(lastIndex < 0x8000);
return position | (lastIndex << 15);
}
/*
* ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2
* steps 3, 9-14, except 12.a.i, 12.c.i.1.
*/
static RegExpRunStatus
ExecuteRegExpImpl(JSContext* cx, RegExpStatics* res, MutableHandleRegExpShared re,
HandleLinearString input, size_t searchIndex, VectorMatchPairs* matches,
size_t* endIndex)
{
RegExpRunStatus status = RegExpShared::execute(cx, re, input, searchIndex, matches, endIndex);
/* Out of spec: Update RegExpStatics. */
if (status == RegExpRunStatus_Success && res) {
if (matches) {
if (!res->updateFromMatchPairs(cx, input, *matches))
return RegExpRunStatus_Error;
} else {
res->updateLazily(cx, input, re, searchIndex);
}
}
return status;
}
/* Legacy ExecuteRegExp behavior is baked into the JSAPI. */
bool
js::ExecuteRegExpLegacy(JSContext* cx, RegExpStatics* res, Handle<RegExpObject*> reobj,
HandleLinearString input, size_t* lastIndex, bool test,
MutableHandleValue rval)
{
RootedRegExpShared shared(cx, RegExpObject::getShared(cx, reobj));
if (!shared)
return false;
VectorMatchPairs matches;
RegExpRunStatus status = ExecuteRegExpImpl(cx, res, &shared, input, *lastIndex,
&matches, nullptr);
if (status == RegExpRunStatus_Error)
return false;
if (status == RegExpRunStatus_Success_NotFound) {
/* ExecuteRegExp() previously returned an array or null. */
rval.setNull();
return true;
}
*lastIndex = matches[0].limit;
if (test) {
/* Forbid an array, as an optimization. */
rval.setBoolean(true);
return true;
}
return CreateRegExpMatchResult(cx, input, matches, rval);
}
static bool
CheckPatternSyntaxSlow(JSContext* cx, HandleAtom pattern, RegExpFlag flags)
{
CompileOptions options(cx);
frontend::TokenStream dummyTokenStream(cx, options, nullptr, 0, nullptr);
return irregexp::ParsePatternSyntax(dummyTokenStream, cx->tempLifoAlloc(), pattern,
flags & UnicodeFlag);
}
static RegExpShared*
CheckPatternSyntax(JSContext* cx, HandleAtom pattern, RegExpFlag flags)
{
// If we already have a RegExpShared for this pattern/flags, we can
// avoid the much slower CheckPatternSyntaxSlow call.
if (RegExpShared* shared = cx->zone()->regExps.maybeGet(pattern, flags)) {
#ifdef DEBUG
// Assert the pattern is valid.
if (!CheckPatternSyntaxSlow(cx, pattern, flags)) {
MOZ_ASSERT(cx->isThrowingOutOfMemory() || cx->isThrowingOverRecursed());
return nullptr;
}
#endif
return shared;
}
if (!CheckPatternSyntaxSlow(cx, pattern, flags))
return nullptr;
// Allocate and return a new RegExpShared so we will hit the fast path
// next time.
return cx->zone()->regExps.get(cx, pattern, flags);
}
/*
* ES 2016 draft Mar 25, 2016 21.2.3.2.2.
*
* Steps 14-15 set |obj|'s "lastIndex" property to zero. Some of
* RegExpInitialize's callers have a fresh RegExp not yet exposed to script:
* in these cases zeroing "lastIndex" is infallible. But others have a RegExp
* whose "lastIndex" property might have been made non-writable: here, zeroing
* "lastIndex" can fail. We efficiently solve this problem by completely
* removing "lastIndex" zeroing from the provided function.
*
* CALLERS MUST HANDLE "lastIndex" ZEROING THEMSELVES!
*
* Because this function only ever returns a user-provided |obj| in the spec,
* we omit it and just return the usual success/failure.
*/
static bool
RegExpInitializeIgnoringLastIndex(JSContext* cx, Handle<RegExpObject*> obj,
HandleValue patternValue, HandleValue flagsValue)
{
RootedAtom pattern(cx);
if (patternValue.isUndefined()) {
/* Step 1. */
pattern = cx->names().empty;
} else {
/* Step 2. */
pattern = ToAtom<CanGC>(cx, patternValue);
if (!pattern)
return false;
}
/* Step 3. */
RegExpFlag flags = RegExpFlag(0);
if (!flagsValue.isUndefined()) {
/* Step 4. */
RootedString flagStr(cx, ToString<CanGC>(cx, flagsValue));
if (!flagStr)
return false;
/* Step 5. */
if (!ParseRegExpFlags(cx, flagStr, &flags))
return false;
}
/* Steps 7-8. */
RegExpShared* shared = CheckPatternSyntax(cx, pattern, flags);
if (!shared)
return false;
/* Steps 9-12. */
obj->initIgnoringLastIndex(pattern, flags);
obj->setShared(*shared);
return true;
}
/* ES 2016 draft Mar 25, 2016 21.2.3.2.3. */
bool
js::RegExpCreate(JSContext* cx, HandleValue patternValue, HandleValue flagsValue,
MutableHandleValue rval)
{
/* Step 1. */
Rooted<RegExpObject*> regexp(cx, RegExpAlloc(cx, GenericObject));
if (!regexp)
return false;
/* Step 2. */
if (!RegExpInitializeIgnoringLastIndex(cx, regexp, patternValue, flagsValue))
return false;
regexp->zeroLastIndex(cx);
rval.setObject(*regexp);
return true;
}
MOZ_ALWAYS_INLINE bool
IsRegExpObject(HandleValue v)
{
return v.isObject() && v.toObject().is<RegExpObject>();
}
/* ES6 draft rc3 7.2.8. */
bool
js::IsRegExp(JSContext* cx, HandleValue value, bool* result)
{
/* Step 1. */
if (!value.isObject()) {
*result = false;
return true;
}
RootedObject obj(cx, &value.toObject());
/* Steps 2-3. */
RootedValue isRegExp(cx);
RootedId matchId(cx, SYMBOL_TO_JSID(cx->wellKnownSymbols().match));
if (!GetProperty(cx, obj, obj, matchId, &isRegExp))
return false;
/* Step 4. */
if (!isRegExp.isUndefined()) {
*result = ToBoolean(isRegExp);
return true;
}
/* Steps 5-6. */
ESClass cls;
if (!GetClassOfValue(cx, value, &cls))
return false;
*result = cls == ESClass::RegExp;
return true;
}
/* ES6 B.2.5.1. */
MOZ_ALWAYS_INLINE bool
regexp_compile_impl(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(IsRegExpObject(args.thisv()));
Rooted<RegExpObject*> regexp(cx, &args.thisv().toObject().as<RegExpObject>());
// Step 3.
RootedValue patternValue(cx, args.get(0));
ESClass cls;
if (!GetClassOfValue(cx, patternValue, &cls))
return false;
if (cls == ESClass::RegExp) {
// Step 3a.
if (args.hasDefined(1)) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_NEWREGEXP_FLAGGED);
return false;
}
// Beware! |patternObj| might be a proxy into another compartment, so
// don't assume |patternObj.is<RegExpObject>()|. For the same reason,
// don't reuse the RegExpShared below.
RootedObject patternObj(cx, &patternValue.toObject());
RootedAtom sourceAtom(cx);
RegExpFlag flags;
{
// Step 3b.
RegExpShared* shared = RegExpToShared(cx, patternObj);
if (!shared)
return false;
sourceAtom = shared->getSource();
flags = shared->getFlags();
}
// Step 5, minus lastIndex zeroing.
regexp->initIgnoringLastIndex(sourceAtom, flags);
} else {
// Step 4.
RootedValue P(cx, patternValue);
RootedValue F(cx, args.get(1));
// Step 5, minus lastIndex zeroing.
if (!RegExpInitializeIgnoringLastIndex(cx, regexp, P, F))
return false;
}
// The final niggling bit of step 5.
//
// |regexp| is user-exposed, but if its "lastIndex" property hasn't been
// made non-writable, we can still use a fast path to zero it.
if (regexp->lookupPure(cx->names().lastIndex)->writable()) {
regexp->zeroLastIndex(cx);
} else {
RootedValue zero(cx, Int32Value(0));
if (!SetProperty(cx, regexp, cx->names().lastIndex, zero))
return false;
}
args.rval().setObject(*regexp);
return true;
}
static bool
regexp_compile(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
/* Steps 1-2. */
return CallNonGenericMethod<IsRegExpObject, regexp_compile_impl>(cx, args);
}
/*
* ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.3.1.
*/
bool
js::regexp_construct(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Steps 1.
bool patternIsRegExp;
if (!IsRegExp(cx, args.get(0), &patternIsRegExp))
return false;
// We can delay step 3 and step 4a until later, during
// GetPrototypeFromBuiltinConstructor calls. Accessing the new.target
// and the callee from the stack is unobservable.
if (!args.isConstructing()) {
// Step 3.b.
if (patternIsRegExp && !args.hasDefined(1)) {
RootedObject patternObj(cx, &args[0].toObject());
// Step 3.b.i.
RootedValue patternConstructor(cx);
if (!GetProperty(cx, patternObj, patternObj, cx->names().constructor, &patternConstructor))
return false;
// Step 3.b.ii.
if (patternConstructor.isObject() && patternConstructor.toObject() == args.callee()) {
args.rval().set(args[0]);
return true;
}
}
}
RootedValue patternValue(cx, args.get(0));
// Step 4.
ESClass cls;
if (!GetClassOfValue(cx, patternValue, &cls))
return false;
if (cls == ESClass::RegExp) {
// Beware! |patternObj| might be a proxy into another compartment, so
// don't assume |patternObj.is<RegExpObject>()|.
RootedObject patternObj(cx, &patternValue.toObject());
RootedAtom sourceAtom(cx);
RegExpFlag flags;
RootedRegExpShared shared(cx);
{
// Step 4.a.
shared = RegExpToShared(cx, patternObj);
if (!shared)
return false;
sourceAtom = shared->getSource();
// Step 4.b.
// Get original flags in all cases, to compare with passed flags.
flags = shared->getFlags();
// If the RegExpShared is in another Zone, don't reuse it.
if (cx->zone() != shared->zone())
shared = nullptr;
}
// Step 7.
RootedObject proto(cx);
if (!GetPrototypeFromBuiltinConstructor(cx, args, &proto))
return false;
Rooted<RegExpObject*> regexp(cx, RegExpAlloc(cx, GenericObject, proto));
if (!regexp)
return false;
// Step 8.
if (args.hasDefined(1)) {
// Step 4.c / 21.2.3.2.2 RegExpInitialize step 4.
RegExpFlag flagsArg = RegExpFlag(0);
RootedString flagStr(cx, ToString<CanGC>(cx, args[1]));
if (!flagStr)
return false;
if (!ParseRegExpFlags(cx, flagStr, &flagsArg))
return false;
// Don't reuse the RegExpShared if we have different flags.
if (flags != flagsArg)
shared = nullptr;
if (!(flags & UnicodeFlag) && flagsArg & UnicodeFlag) {
// Have to check syntax again when adding 'u' flag.
// ES 2017 draft rev 9b49a888e9dfe2667008a01b2754c3662059ae56
// 21.2.3.2.2 step 7.
shared = CheckPatternSyntax(cx, sourceAtom, flagsArg);
if (!shared)
return false;
}
flags = flagsArg;
}
regexp->initAndZeroLastIndex(sourceAtom, flags, cx);
if (shared)
regexp->setShared(*shared);
args.rval().setObject(*regexp);
return true;
}
RootedValue P(cx);
RootedValue F(cx);
// Step 5.
if (patternIsRegExp) {
RootedObject patternObj(cx, &patternValue.toObject());
// Step 5.a.
if (!GetProperty(cx, patternObj, patternObj, cx->names().source, &P))
return false;
// Step 5.b.
F = args.get(1);
if (F.isUndefined()) {
if (!GetProperty(cx, patternObj, patternObj, cx->names().flags, &F))
return false;
}
} else {
// Steps 6.a-b.
P = patternValue;
F = args.get(1);
}
// Step 7.
RootedObject proto(cx);
if (!GetPrototypeFromBuiltinConstructor(cx, args, &proto))
return false;
Rooted<RegExpObject*> regexp(cx, RegExpAlloc(cx, GenericObject, proto));
if (!regexp)
return false;
// Step 8.
if (!RegExpInitializeIgnoringLastIndex(cx, regexp, P, F))
return false;
regexp->zeroLastIndex(cx);
args.rval().setObject(*regexp);
return true;
}
/*
* ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.3.1
* steps 4, 7-8.
*/
bool
js::regexp_construct_raw_flags(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 2);
MOZ_ASSERT(!args.isConstructing());
// Step 4.a.
RootedAtom sourceAtom(cx, AtomizeString(cx, args[0].toString()));
if (!sourceAtom)
return false;
// Step 4.c.
int32_t flags = int32_t(args[1].toNumber());
// Step 7.
RegExpObject* regexp = RegExpAlloc(cx, GenericObject);
if (!regexp)
return false;
// Step 8.
regexp->initAndZeroLastIndex(sourceAtom, RegExpFlag(flags), cx);
args.rval().setObject(*regexp);
return true;
}
MOZ_ALWAYS_INLINE bool
IsRegExpPrototype(HandleValue v)
{
if (IsRegExpObject(v) || !v.isObject())
return false;
// Note: The prototype shares its JSClass with instances.
return StandardProtoKeyOrNull(&v.toObject()) == JSProto_RegExp;
}
// ES 2017 draft 21.2.5.4.
MOZ_ALWAYS_INLINE bool
regexp_global_impl(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(IsRegExpObject(args.thisv()));
// Steps 4-6.
RegExpObject* reObj = &args.thisv().toObject().as<RegExpObject>();
args.rval().setBoolean(reObj->global());
return true;
}
bool
js::regexp_global(JSContext* cx, unsigned argc, JS::Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Step 3.a.
if (IsRegExpPrototype(args.thisv())) {
args.rval().setUndefined();
return true;
}
// Steps 1-3.
return CallNonGenericMethod<IsRegExpObject, regexp_global_impl>(cx, args);
}
// ES 2017 draft 21.2.5.5.
MOZ_ALWAYS_INLINE bool
regexp_ignoreCase_impl(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(IsRegExpObject(args.thisv()));
// Steps 4-6.
RegExpObject* reObj = &args.thisv().toObject().as<RegExpObject>();
args.rval().setBoolean(reObj->ignoreCase());
return true;
}
bool
js::regexp_ignoreCase(JSContext* cx, unsigned argc, JS::Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Step 3.a.
if (IsRegExpPrototype(args.thisv())) {
args.rval().setUndefined();
return true;
}
// Steps 1-3.
return CallNonGenericMethod<IsRegExpObject, regexp_ignoreCase_impl>(cx, args);
}
// ES 2017 draft 21.2.5.7.
MOZ_ALWAYS_INLINE bool
regexp_multiline_impl(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(IsRegExpObject(args.thisv()));
// Steps 4-6.
RegExpObject* reObj = &args.thisv().toObject().as<RegExpObject>();
args.rval().setBoolean(reObj->multiline());
return true;
}
bool
js::regexp_multiline(JSContext* cx, unsigned argc, JS::Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Step 3.a.
if (IsRegExpPrototype(args.thisv())) {
args.rval().setUndefined();
return true;
}
// Steps 1-3.
return CallNonGenericMethod<IsRegExpObject, regexp_multiline_impl>(cx, args);
}
// ES 2017 draft 21.2.5.10.
MOZ_ALWAYS_INLINE bool
regexp_source_impl(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(IsRegExpObject(args.thisv()));
// Step 5.
RegExpObject* reObj = &args.thisv().toObject().as<RegExpObject>();
RootedAtom src(cx, reObj->getSource());
if (!src)
return false;
// Step 7.
JSString* str = EscapeRegExpPattern(cx, src);
if (!str)
return false;
args.rval().setString(str);
return true;
}
static bool
regexp_source(JSContext* cx, unsigned argc, JS::Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Step 3.a.
if (IsRegExpPrototype(args.thisv())) {
args.rval().setString(cx->names().emptyRegExp);
return true;
}
// Steps 1-4.
return CallNonGenericMethod<IsRegExpObject, regexp_source_impl>(cx, args);
}
// ES 2017 draft 21.2.5.12.
MOZ_ALWAYS_INLINE bool
regexp_sticky_impl(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(IsRegExpObject(args.thisv()));
// Steps 4-6.
RegExpObject* reObj = &args.thisv().toObject().as<RegExpObject>();
args.rval().setBoolean(reObj->sticky());
return true;
}
bool
js::regexp_sticky(JSContext* cx, unsigned argc, JS::Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Step 3.a.
if (IsRegExpPrototype(args.thisv())) {
args.rval().setUndefined();
return true;
}
// Steps 1-3.
return CallNonGenericMethod<IsRegExpObject, regexp_sticky_impl>(cx, args);
}
// ES 2017 draft 21.2.5.15.
MOZ_ALWAYS_INLINE bool
regexp_unicode_impl(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(IsRegExpObject(args.thisv()));
// Steps 4-6.
RegExpObject* reObj = &args.thisv().toObject().as<RegExpObject>();
args.rval().setBoolean(reObj->unicode());
return true;
}
bool
js::regexp_unicode(JSContext* cx, unsigned argc, JS::Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Step 3.a.
if (IsRegExpPrototype(args.thisv())) {
args.rval().setUndefined();
return true;
}
// Steps 1-3.
return CallNonGenericMethod<IsRegExpObject, regexp_unicode_impl>(cx, args);
}
const JSPropertySpec js::regexp_properties[] = {
JS_SELF_HOSTED_GET("flags", "RegExpFlagsGetter", 0),
JS_PSG("global", regexp_global, 0),
JS_PSG("ignoreCase", regexp_ignoreCase, 0),
JS_PSG("multiline", regexp_multiline, 0),
JS_PSG("source", regexp_source, 0),
JS_PSG("sticky", regexp_sticky, 0),
JS_PSG("unicode", regexp_unicode, 0),
JS_PS_END
};
const JSFunctionSpec js::regexp_methods[] = {
JS_SELF_HOSTED_FN(js_toSource_str, "RegExpToString", 0, 0),
JS_SELF_HOSTED_FN(js_toString_str, "RegExpToString", 0, 0),
JS_FN("compile", regexp_compile, 2,0),
JS_SELF_HOSTED_FN("exec", "RegExp_prototype_Exec", 1,0),
JS_SELF_HOSTED_FN("test", "RegExpTest" , 1,0),
JS_SELF_HOSTED_SYM_FN(match, "RegExpMatch", 1,0),
JS_SELF_HOSTED_SYM_FN(replace, "RegExpReplace", 2,0),
JS_SELF_HOSTED_SYM_FN(search, "RegExpSearch", 1,0),
JS_SELF_HOSTED_SYM_FN(split, "RegExpSplit", 2,0),
JS_FS_END
};
#define STATIC_PAREN_GETTER_CODE(parenNum) \
if (!res->createParen(cx, parenNum, args.rval())) \
return false; \
if (args.rval().isUndefined()) \
args.rval().setString(cx->runtime()->emptyString); \
return true
/*
* RegExp static properties.
*
* RegExp class static properties and their Perl counterparts:
*
* RegExp.input $_
* RegExp.lastMatch $&
* RegExp.lastParen $+
* RegExp.leftContext $`
* RegExp.rightContext $'
*/
#define DEFINE_STATIC_GETTER(name, code) \
static bool \
name(JSContext* cx, unsigned argc, Value* vp) \
{ \
CallArgs args = CallArgsFromVp(argc, vp); \
RegExpStatics* res = GlobalObject::getRegExpStatics(cx, cx->global()); \
if (!res) \
return false; \
code; \
}
DEFINE_STATIC_GETTER(static_input_getter, return res->createPendingInput(cx, args.rval()))
DEFINE_STATIC_GETTER(static_lastMatch_getter, return res->createLastMatch(cx, args.rval()))
DEFINE_STATIC_GETTER(static_lastParen_getter, return res->createLastParen(cx, args.rval()))
DEFINE_STATIC_GETTER(static_leftContext_getter, return res->createLeftContext(cx, args.rval()))
DEFINE_STATIC_GETTER(static_rightContext_getter, return res->createRightContext(cx, args.rval()))
DEFINE_STATIC_GETTER(static_paren1_getter, STATIC_PAREN_GETTER_CODE(1))
DEFINE_STATIC_GETTER(static_paren2_getter, STATIC_PAREN_GETTER_CODE(2))
DEFINE_STATIC_GETTER(static_paren3_getter, STATIC_PAREN_GETTER_CODE(3))
DEFINE_STATIC_GETTER(static_paren4_getter, STATIC_PAREN_GETTER_CODE(4))
DEFINE_STATIC_GETTER(static_paren5_getter, STATIC_PAREN_GETTER_CODE(5))
DEFINE_STATIC_GETTER(static_paren6_getter, STATIC_PAREN_GETTER_CODE(6))
DEFINE_STATIC_GETTER(static_paren7_getter, STATIC_PAREN_GETTER_CODE(7))
DEFINE_STATIC_GETTER(static_paren8_getter, STATIC_PAREN_GETTER_CODE(8))
DEFINE_STATIC_GETTER(static_paren9_getter, STATIC_PAREN_GETTER_CODE(9))
#define DEFINE_STATIC_SETTER(name, code) \
static bool \
name(JSContext* cx, unsigned argc, Value* vp) \
{ \
RegExpStatics* res = GlobalObject::getRegExpStatics(cx, cx->global()); \
if (!res) \
return false; \
code; \
return true; \
}
static bool
static_input_setter(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
RegExpStatics* res = GlobalObject::getRegExpStatics(cx, cx->global());
if (!res)
return false;
RootedString str(cx, ToString<CanGC>(cx, args.get(0)));
if (!str)
return false;
res->setPendingInput(str);
args.rval().setString(str);
return true;
}
const JSPropertySpec js::regexp_static_props[] = {
JS_PSGS("input", static_input_getter, static_input_setter,
JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("lastMatch", static_lastMatch_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("lastParen", static_lastParen_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("leftContext", static_leftContext_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("rightContext", static_rightContext_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$1", static_paren1_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$2", static_paren2_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$3", static_paren3_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$4", static_paren4_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$5", static_paren5_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$6", static_paren6_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$7", static_paren7_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$8", static_paren8_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$9", static_paren9_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSGS("$_", static_input_getter, static_input_setter, JSPROP_PERMANENT),
JS_PSG("$&", static_lastMatch_getter, JSPROP_PERMANENT),
JS_PSG("$+", static_lastParen_getter, JSPROP_PERMANENT),
JS_PSG("$`", static_leftContext_getter, JSPROP_PERMANENT),
JS_PSG("$'", static_rightContext_getter, JSPROP_PERMANENT),
JS_SELF_HOSTED_SYM_GET(species, "RegExpSpecies", 0),
JS_PS_END
};
template <typename CharT>
static bool
IsTrailSurrogateWithLeadSurrogateImpl(HandleLinearString input, size_t index)
{
JS::AutoCheckCannotGC nogc;
MOZ_ASSERT(index > 0 && index < input->length());
const CharT* inputChars = input->chars<CharT>(nogc);
return unicode::IsTrailSurrogate(inputChars[index]) &&
unicode::IsLeadSurrogate(inputChars[index - 1]);
}
static bool
IsTrailSurrogateWithLeadSurrogate(HandleLinearString input, int32_t index)
{
if (index <= 0 || size_t(index) >= input->length())
return false;
return input->hasLatin1Chars()
? IsTrailSurrogateWithLeadSurrogateImpl<Latin1Char>(input, index)
: IsTrailSurrogateWithLeadSurrogateImpl<char16_t>(input, index);
}
/*
* ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2
* steps 3, 9-14, except 12.a.i, 12.c.i.1.
*/
static RegExpRunStatus
ExecuteRegExp(JSContext* cx, HandleObject regexp, HandleString string, int32_t lastIndex,
VectorMatchPairs* matches, size_t* endIndex)
{
/*
* WARNING: Despite the presence of spec step comment numbers, this
* algorithm isn't consistent with any ES6 version, draft or
* otherwise. YOU HAVE BEEN WARNED.
*/
/* Steps 1-2 performed by the caller. */
Handle<RegExpObject*> reobj = regexp.as<RegExpObject>();
RootedRegExpShared re(cx, RegExpObject::getShared(cx, reobj));
if (!re)
return RegExpRunStatus_Error;
RegExpStatics* res = GlobalObject::getRegExpStatics(cx, cx->global());
if (!res)
return RegExpRunStatus_Error;
RootedLinearString input(cx, string->ensureLinear(cx));
if (!input)
return RegExpRunStatus_Error;
/* Handled by caller */
MOZ_ASSERT(lastIndex >= 0 && size_t(lastIndex) <= input->length());
/* Steps 4-8 performed by the caller. */
/* Step 10. */
if (reobj->unicode()) {
/*
* ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad
* 21.2.2.2 step 2.
* Let listIndex be the index into Input of the character that was
* obtained from element index of str.
*
* In the spec, pattern match is performed with decoded Unicode code
* points, but our implementation performs it with UTF-16 encoded
* string. In step 2, we should decrement lastIndex (index) if it
* points the trail surrogate that has corresponding lead surrogate.
*
* var r = /\uD83D\uDC38/ug;
* r.lastIndex = 1;
* var str = "\uD83D\uDC38";
* var result = r.exec(str); // pattern match starts from index 0
* print(result.index); // prints 0
*
* Note: this doesn't match the current spec text and result in
* different values for `result.index` under certain conditions.
* However, the spec will change to match our implementation's
* behavior. See https://github.com/tc39/ecma262/issues/128.
*/
if (IsTrailSurrogateWithLeadSurrogate(input, lastIndex))
lastIndex--;
}
/* Steps 3, 11-14, except 12.a.i, 12.c.i.1. */
RegExpRunStatus status = ExecuteRegExpImpl(cx, res, &re, input, lastIndex, matches, endIndex);
if (status == RegExpRunStatus_Error)
return RegExpRunStatus_Error;
/* Steps 12.a.i, 12.c.i.i, 15 are done by Self-hosted function. */
return status;
}
/*
* ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2
* steps 3, 9-25, except 12.a.i, 12.c.i.1, 15.
*/
static bool
RegExpMatcherImpl(JSContext* cx, HandleObject regexp, HandleString string, int32_t lastIndex,
MutableHandleValue rval)
{
/* Execute regular expression and gather matches. */
VectorMatchPairs matches;
/* Steps 3, 9-14, except 12.a.i, 12.c.i.1. */
RegExpRunStatus status = ExecuteRegExp(cx, regexp, string, lastIndex, &matches, nullptr);
if (status == RegExpRunStatus_Error)
return false;
/* Steps 12.a, 12.c. */
if (status == RegExpRunStatus_Success_NotFound) {
rval.setNull();
return true;
}
/* Steps 16-25 */
return CreateRegExpMatchResult(cx, string, matches, rval);
}
/*
* ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2
* steps 3, 9-25, except 12.a.i, 12.c.i.1, 15.
*/
bool
js::RegExpMatcher(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 3);
MOZ_ASSERT(IsRegExpObject(args[0]));
MOZ_ASSERT(args[1].isString());
MOZ_ASSERT(args[2].isNumber());
RootedObject regexp(cx, &args[0].toObject());
RootedString string(cx, args[1].toString());
int32_t lastIndex;
MOZ_ALWAYS_TRUE(ToInt32(cx, args[2], &lastIndex));
/* Steps 3, 9-25, except 12.a.i, 12.c.i.1, 15. */
return RegExpMatcherImpl(cx, regexp, string, lastIndex, args.rval());
}
/*
* Separate interface for use by IonMonkey.
* This code cannot re-enter Ion code.
*/
bool
js::RegExpMatcherRaw(JSContext* cx, HandleObject regexp, HandleString input,
int32_t lastIndex,
MatchPairs* maybeMatches, MutableHandleValue output)
{
MOZ_ASSERT(lastIndex >= 0);
// The MatchPairs will always be passed in, but RegExp execution was
// successful only if the pairs have actually been filled in.
if (maybeMatches && maybeMatches->pairsRaw()[0] >= 0)
return CreateRegExpMatchResult(cx, input, *maybeMatches, output);
return RegExpMatcherImpl(cx, regexp, input, lastIndex, output);
}
/*
* ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2
* steps 3, 9-25, except 12.a.i, 12.c.i.1, 15.
* This code is inlined in CodeGenerator.cpp generateRegExpSearcherStub,
* changes to this code need to get reflected in there too.
*/
static bool
RegExpSearcherImpl(JSContext* cx, HandleObject regexp, HandleString string, int32_t lastIndex,
int32_t* result)
{
/* Execute regular expression and gather matches. */
VectorMatchPairs matches;
/* Steps 3, 9-14, except 12.a.i, 12.c.i.1. */
RegExpRunStatus status = ExecuteRegExp(cx, regexp, string, lastIndex, &matches, nullptr);
if (status == RegExpRunStatus_Error)
return false;
/* Steps 12.a, 12.c. */
if (status == RegExpRunStatus_Success_NotFound) {
*result = -1;
return true;
}
/* Steps 16-25 */
*result = CreateRegExpSearchResult(matches);
return true;
}
/*
* ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2
* steps 3, 9-25, except 12.a.i, 12.c.i.1, 15.
*/
bool
js::RegExpSearcher(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 3);
MOZ_ASSERT(IsRegExpObject(args[0]));
MOZ_ASSERT(args[1].isString());
MOZ_ASSERT(args[2].isNumber());
RootedObject regexp(cx, &args[0].toObject());
RootedString string(cx, args[1].toString());
int32_t lastIndex;
MOZ_ALWAYS_TRUE(ToInt32(cx, args[2], &lastIndex));
/* Steps 3, 9-25, except 12.a.i, 12.c.i.1, 15. */
int32_t result = 0;
if (!RegExpSearcherImpl(cx, regexp, string, lastIndex, &result))
return false;
args.rval().setInt32(result);
return true;
}
/*
* Separate interface for use by IonMonkey.
* This code cannot re-enter Ion code.
*/
bool
js::RegExpSearcherRaw(JSContext* cx, HandleObject regexp, HandleString input,
int32_t lastIndex, MatchPairs* maybeMatches, int32_t* result)
{
MOZ_ASSERT(lastIndex >= 0);
// The MatchPairs will always be passed in, but RegExp execution was
// successful only if the pairs have actually been filled in.
if (maybeMatches && maybeMatches->pairsRaw()[0] >= 0) {
*result = CreateRegExpSearchResult(*maybeMatches);
return true;
}
return RegExpSearcherImpl(cx, regexp, input, lastIndex, result);
}
/*
* ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2
* steps 3, 9-14, except 12.a.i, 12.c.i.1.
*/
bool
js::RegExpTester(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 3);
MOZ_ASSERT(IsRegExpObject(args[0]));
MOZ_ASSERT(args[1].isString());
MOZ_ASSERT(args[2].isNumber());
RootedObject regexp(cx, &args[0].toObject());
RootedString string(cx, args[1].toString());
int32_t lastIndex;
MOZ_ALWAYS_TRUE(ToInt32(cx, args[2], &lastIndex));
/* Steps 3, 9-14, except 12.a.i, 12.c.i.1. */
size_t endIndex = 0;
RegExpRunStatus status = ExecuteRegExp(cx, regexp, string, lastIndex, nullptr, &endIndex);
if (status == RegExpRunStatus_Error)
return false;
if (status == RegExpRunStatus_Success) {
MOZ_ASSERT(endIndex <= INT32_MAX);
args.rval().setInt32(int32_t(endIndex));
} else {
args.rval().setInt32(-1);
}
return true;
}
/*
* Separate interface for use by IonMonkey.
* This code cannot re-enter Ion code.
*/
bool
js::RegExpTesterRaw(JSContext* cx, HandleObject regexp, HandleString input,
int32_t lastIndex, int32_t* endIndex)
{
MOZ_ASSERT(lastIndex >= 0);
size_t endIndexTmp = 0;
RegExpRunStatus status = ExecuteRegExp(cx, regexp, input, lastIndex, nullptr, &endIndexTmp);
if (status == RegExpRunStatus_Success) {
MOZ_ASSERT(endIndexTmp <= INT32_MAX);
*endIndex = int32_t(endIndexTmp);
return true;
}
if (status == RegExpRunStatus_Success_NotFound) {
*endIndex = -1;
return true;
}
return false;
}
using CapturesVector = GCVector<Value, 4>;
struct JSSubString
{
JSLinearString* base;
size_t offset;
size_t length;
JSSubString() { mozilla::PodZero(this); }
void initEmpty(JSLinearString* base) {
this->base = base;
offset = length = 0;
}
void init(JSLinearString* base, size_t offset, size_t length) {
this->base = base;
this->offset = offset;
this->length = length;
}
};
static void
GetParen(JSLinearString* matched, const JS::Value& capture, JSSubString* out)
{
if (capture.isUndefined()) {
out->initEmpty(matched);
return;
}
JSLinearString& captureLinear = capture.toString()->asLinear();
out->init(&captureLinear, 0, captureLinear.length());
}
template <typename CharT>
static bool
InterpretDollar(JSLinearString* matched, JSLinearString* string, size_t position, size_t tailPos,
Handle<CapturesVector> captures, JSLinearString* replacement,
const CharT* replacementBegin, const CharT* currentDollar,
const CharT* replacementEnd,
JSSubString* out, size_t* skip)
{
MOZ_ASSERT(*currentDollar == '$');
/* If there is only a dollar, bail now. */
if (currentDollar + 1 >= replacementEnd)
return false;
/* ES 2016 draft Mar 25, 2016 Table 46. */
char16_t c = currentDollar[1];
if (JS7_ISDEC(c)) {
/* $n, $nn */
unsigned num = JS7_UNDEC(c);
if (num > captures.length()) {
// The result is implementation-defined, do not substitute.
return false;
}
const CharT* currentChar = currentDollar + 2;
if (currentChar < replacementEnd) {
c = *currentChar;
if (JS7_ISDEC(c)) {
unsigned tmpNum = 10 * num + JS7_UNDEC(c);
// If num > captures.length(), the result is implementation-defined.
// Consume next character only if num <= captures.length().
if (tmpNum <= captures.length()) {
currentChar++;
num = tmpNum;
}
}
}
if (num == 0) {
// The result is implementation-defined.
// Do not substitute.
return false;
}
*skip = currentChar - currentDollar;
MOZ_ASSERT(num <= captures.length());
GetParen(matched, captures[num -1], out);
return true;
}
*skip = 2;
switch (c) {
default:
return false;
case '$':
out->init(replacement, currentDollar - replacementBegin, 1);
break;
case '&':
out->init(matched, 0, matched->length());
break;
case '+':
// SpiderMonkey extension
if (captures.length() == 0)
out->initEmpty(matched);
else
GetParen(matched, captures[captures.length() - 1], out);
break;
case '`':
out->init(string, 0, position);
break;
case '\'':
out->init(string, tailPos, string->length() - tailPos);
break;
}
return true;
}
template <typename CharT>
static bool
FindReplaceLengthString(JSContext* cx, HandleLinearString matched, HandleLinearString string,
size_t position, size_t tailPos, Handle<CapturesVector> captures,
HandleLinearString replacement, size_t firstDollarIndex, size_t* sizep)
{
CheckedInt<uint32_t> replen = replacement->length();
JS::AutoCheckCannotGC nogc;
MOZ_ASSERT(firstDollarIndex < replacement->length());
const CharT* replacementBegin = replacement->chars<CharT>(nogc);
const CharT* currentDollar = replacementBegin + firstDollarIndex;
const CharT* replacementEnd = replacementBegin + replacement->length();
do {
JSSubString sub;
size_t skip;
if (InterpretDollar(matched, string, position, tailPos, captures, replacement,
replacementBegin, currentDollar, replacementEnd, &sub, &skip))
{
if (sub.length > skip)
replen += sub.length - skip;
else
replen -= skip - sub.length;
currentDollar += skip;
} else {
currentDollar++;
}
currentDollar = js_strchr_limit(currentDollar, '$', replacementEnd);
} while (currentDollar);
if (!replen.isValid()) {
ReportAllocationOverflow(cx);
return false;
}
*sizep = replen.value();
return true;
}
static bool
FindReplaceLength(JSContext* cx, HandleLinearString matched, HandleLinearString string,
size_t position, size_t tailPos, Handle<CapturesVector> captures,
HandleLinearString replacement, size_t firstDollarIndex, size_t* sizep)
{
return replacement->hasLatin1Chars()
? FindReplaceLengthString<Latin1Char>(cx, matched, string, position, tailPos, captures,
replacement, firstDollarIndex, sizep)
: FindReplaceLengthString<char16_t>(cx, matched, string, position, tailPos, captures,
replacement, firstDollarIndex, sizep);
}
/*
* Precondition: |sb| already has necessary growth space reserved (as
* derived from FindReplaceLength), and has been inflated to TwoByte if
* necessary.
*/
template <typename CharT>
static void
DoReplace(HandleLinearString matched, HandleLinearString string,
size_t position, size_t tailPos, Handle<CapturesVector> captures,
HandleLinearString replacement, size_t firstDollarIndex, StringBuffer &sb)
{
JS::AutoCheckCannotGC nogc;
const CharT* replacementBegin = replacement->chars<CharT>(nogc);
const CharT* currentChar = replacementBegin;
MOZ_ASSERT(firstDollarIndex < replacement->length());
const CharT* currentDollar = replacementBegin + firstDollarIndex;
const CharT* replacementEnd = replacementBegin + replacement->length();
do {
/* Move one of the constant portions of the replacement value. */
size_t len = currentDollar - currentChar;
sb.infallibleAppend(currentChar, len);
currentChar = currentDollar;
JSSubString sub;
size_t skip;
if (InterpretDollar(matched, string, position, tailPos, captures, replacement,
replacementBegin, currentDollar, replacementEnd, &sub, &skip))
{
sb.infallibleAppendSubstring(sub.base, sub.offset, sub.length);
currentChar += skip;
currentDollar += skip;
} else {
currentDollar++;
}
currentDollar = js_strchr_limit(currentDollar, '$', replacementEnd);
} while (currentDollar);
sb.infallibleAppend(currentChar, replacement->length() - (currentChar - replacementBegin));
}
static bool
NeedTwoBytes(HandleLinearString string, HandleLinearString replacement,
HandleLinearString matched, Handle<CapturesVector> captures)
{
if (string->hasTwoByteChars())
return true;
if (replacement->hasTwoByteChars())
return true;
if (matched->hasTwoByteChars())
return true;
for (size_t i = 0, len = captures.length(); i < len; i++) {
const Value& capture = captures[i];
if (capture.isUndefined())
continue;
if (capture.toString()->hasTwoByteChars())
return true;
}
return false;
}
/* ES 2016 draft Mar 25, 2016 21.1.3.14.1. */
bool
js::RegExpGetSubstitution(JSContext* cx, HandleArrayObject matchResult, HandleLinearString string,
size_t position, HandleLinearString replacement,
size_t firstDollarIndex, MutableHandleValue rval)
{
MOZ_ASSERT(firstDollarIndex < replacement->length());
// Step 1 (skipped).
// Step 10 (reordered).
uint32_t matchResultLength = matchResult->length();
MOZ_ASSERT(matchResultLength > 0);
MOZ_ASSERT(matchResultLength == matchResult->getDenseInitializedLength());
const Value& matchedValue = matchResult->getDenseElement(0);
RootedLinearString matched(cx, matchedValue.toString()->ensureLinear(cx));
if (!matched)
return false;
// Step 2.
size_t matchLength = matched->length();
// Steps 3-5 (skipped).
// Step 6.
MOZ_ASSERT(position <= string->length());
uint32_t nCaptures = matchResultLength - 1;
Rooted<CapturesVector> captures(cx, CapturesVector(cx));
if (!captures.reserve(nCaptures))
return false;
// Step 7.
for (uint32_t i = 1; i <= nCaptures; i++) {
const Value& capture = matchResult->getDenseElement(i);
if (capture.isUndefined()) {
captures.infallibleAppend(capture);
continue;
}
JSLinearString* captureLinear = capture.toString()->ensureLinear(cx);
if (!captureLinear)
return false;
captures.infallibleAppend(StringValue(captureLinear));
}
// Step 8 (skipped).
// Step 9.
CheckedInt<uint32_t> checkedTailPos(0);
checkedTailPos += position;
checkedTailPos += matchLength;
if (!checkedTailPos.isValid()) {
ReportAllocationOverflow(cx);
return false;
}
uint32_t tailPos = checkedTailPos.value();
// Step 11.
size_t reserveLength;
if (!FindReplaceLength(cx, matched, string, position, tailPos, captures, replacement,
firstDollarIndex, &reserveLength))
{
return false;
}
StringBuffer result(cx);
if (NeedTwoBytes(string, replacement, matched, captures)) {
if (!result.ensureTwoByteChars())
return false;
}
if (!result.reserve(reserveLength))
return false;
if (replacement->hasLatin1Chars()) {
DoReplace<Latin1Char>(matched, string, position, tailPos, captures,
replacement, firstDollarIndex, result);
} else {
DoReplace<char16_t>(matched, string, position, tailPos, captures,
replacement, firstDollarIndex, result);
}
// Step 12.
JSString* resultString = result.finishString();
if (!resultString)
return false;
rval.setString(resultString);
return true;
}
bool
js::GetFirstDollarIndex(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 1);
JSString* str = args[0].toString();
// Should be handled in different path.
MOZ_ASSERT(str->length() != 0);
int32_t index = -1;
if (!GetFirstDollarIndexRaw(cx, str, &index))
return false;
args.rval().setInt32(index);
return true;
}
template <typename TextChar>
static MOZ_ALWAYS_INLINE int
GetFirstDollarIndexImpl(const TextChar* text, uint32_t textLen)
{
const TextChar* end = text + textLen;
for (const TextChar* c = text; c != end; ++c) {
if (*c == '$')
return c - text;
}
return -1;
}
int32_t
js::GetFirstDollarIndexRawFlat(JSLinearString* text)
{
uint32_t len = text->length();
JS::AutoCheckCannotGC nogc;
if (text->hasLatin1Chars())
return GetFirstDollarIndexImpl(text->latin1Chars(nogc), len);
return GetFirstDollarIndexImpl(text->twoByteChars(nogc), len);
}
bool
js::GetFirstDollarIndexRaw(JSContext* cx, JSString* str, int32_t* index)
{
JSLinearString* text = str->ensureLinear(cx);
if (!text)
return false;
*index = GetFirstDollarIndexRawFlat(text);
return true;
}
bool
js::RegExpPrototypeOptimizable(JSContext* cx, unsigned argc, Value* vp)
{
// This can only be called from self-hosted code.
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 1);
args.rval().setBoolean(RegExpPrototypeOptimizableRaw(cx, &args[0].toObject()));
return true;
}
bool
js::RegExpPrototypeOptimizableRaw(JSContext* cx, JSObject* proto)
{
AutoUnsafeCallWithABI unsafe;
AutoAssertNoPendingException aanpe(cx);
if (!proto->isNative())
return false;
NativeObject* nproto = static_cast<NativeObject*>(proto);
Shape* shape = cx->compartment()->regExps.getOptimizableRegExpPrototypeShape();
if (shape == nproto->lastProperty())
return true;
JSFunction* flagsGetter;
if (!GetOwnGetterPure(cx, proto, NameToId(cx->names().flags), &flagsGetter))
return false;
if (!flagsGetter)
return false;
if (!IsSelfHostedFunctionWithName(flagsGetter, cx->names().RegExpFlagsGetter))
return false;
JSNative globalGetter;
if (!GetOwnNativeGetterPure(cx, proto, NameToId(cx->names().global), &globalGetter))
return false;
if (globalGetter != regexp_global)
return false;
JSNative ignoreCaseGetter;
if (!GetOwnNativeGetterPure(cx, proto, NameToId(cx->names().ignoreCase), &ignoreCaseGetter))
return false;
if (ignoreCaseGetter != regexp_ignoreCase)
return false;
JSNative multilineGetter;
if (!GetOwnNativeGetterPure(cx, proto, NameToId(cx->names().multiline), &multilineGetter))
return false;
if (multilineGetter != regexp_multiline)
return false;
JSNative stickyGetter;
if (!GetOwnNativeGetterPure(cx, proto, NameToId(cx->names().sticky), &stickyGetter))
return false;
if (stickyGetter != regexp_sticky)
return false;
JSNative unicodeGetter;
if (!GetOwnNativeGetterPure(cx, proto, NameToId(cx->names().unicode), &unicodeGetter))
return false;
if (unicodeGetter != regexp_unicode)
return false;
// Check if @@match, @@search, and exec are own data properties,
// those values should be tested in selfhosted JS.
bool has = false;
if (!HasOwnDataPropertyPure(cx, proto, SYMBOL_TO_JSID(cx->wellKnownSymbols().match), &has))
return false;
if (!has)
return false;
if (!HasOwnDataPropertyPure(cx, proto, SYMBOL_TO_JSID(cx->wellKnownSymbols().search), &has))
return false;
if (!has)
return false;
if (!HasOwnDataPropertyPure(cx, proto, NameToId(cx->names().exec), &has))
return false;
if (!has)
return false;
cx->compartment()->regExps.setOptimizableRegExpPrototypeShape(nproto->lastProperty());
return true;
}
bool
js::RegExpInstanceOptimizable(JSContext* cx, unsigned argc, Value* vp)
{
// This can only be called from self-hosted code.
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 2);
args.rval().setBoolean(RegExpInstanceOptimizableRaw(cx, &args[0].toObject(),
&args[1].toObject()));
return true;
}
bool
js::RegExpInstanceOptimizableRaw(JSContext* cx, JSObject* obj, JSObject* proto)
{
AutoUnsafeCallWithABI unsafe;
AutoAssertNoPendingException aanpe(cx);
RegExpObject* rx = &obj->as<RegExpObject>();
Shape* shape = cx->compartment()->regExps.getOptimizableRegExpInstanceShape();
if (shape == rx->lastProperty())
return true;
if (!rx->hasStaticPrototype())
return false;
if (rx->staticPrototype() != proto)
return false;
if (!RegExpObject::isInitialShape(rx))
return false;
cx->compartment()->regExps.setOptimizableRegExpInstanceShape(rx->lastProperty());
return true;
}
/*
* Pattern match the script to check if it is is indexing into a particular
* object, e.g. 'function(a) { return b[a]; }'. Avoid calling the script in
* such cases, which are used by javascript packers (particularly the popular
* Dean Edwards packer) to efficiently encode large scripts. We only handle the
* code patterns generated by such packers here.
*/
bool
js::intrinsic_GetElemBaseForLambda(JSContext* cx, unsigned argc, Value* vp)
{
// This can only be called from self-hosted code.
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 1);
JSObject& lambda = args[0].toObject();
args.rval().setUndefined();
if (!lambda.is<JSFunction>())
return true;
RootedFunction fun(cx, &lambda.as<JSFunction>());
if (!fun->isInterpreted() || fun->isClassConstructor())
return true;
JSScript* script = JSFunction::getOrCreateScript(cx, fun);
if (!script)
return false;
jsbytecode* pc = script->code();
/*
* JSOP_GETALIASEDVAR tells us exactly where to find the base object 'b'.
* Rule out the (unlikely) possibility of a function with environment
* objects since it would make our environment walk off.
*/
if (JSOp(*pc) != JSOP_GETALIASEDVAR || fun->needsSomeEnvironmentObject())
return true;
EnvironmentCoordinate ec(pc);
EnvironmentObject* env = &fun->environment()->as<EnvironmentObject>();
for (unsigned i = 0; i < ec.hops(); ++i)
env = &env->enclosingEnvironment().as<EnvironmentObject>();
Value b = env->aliasedBinding(ec);
pc += JSOP_GETALIASEDVAR_LENGTH;
/* Look for 'a' to be the lambda's first argument. */
if (JSOp(*pc) != JSOP_GETARG || GET_ARGNO(pc) != 0)
return true;
pc += JSOP_GETARG_LENGTH;
/* 'b[a]' */
if (JSOp(*pc) != JSOP_GETELEM)
return true;
pc += JSOP_GETELEM_LENGTH;
/* 'return b[a]' */
if (JSOp(*pc) != JSOP_RETURN)
return true;
/* 'b' must behave like a normal object. */
if (!b.isObject())
return true;
JSObject& bobj = b.toObject();
const Class* clasp = bobj.getClass();
if (!clasp->isNative() || clasp->getOpsLookupProperty() || clasp->getOpsGetProperty())
return true;
args.rval().setObject(bobj);
return true;
}
/*
* Emulates `b[a]` property access, that is detected in GetElemBaseForLambda.
* It returns the property value only if the property is data property and the
* property value is a string. Otherwise it returns undefined.
*/
bool
js::intrinsic_GetStringDataProperty(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 2);
RootedObject obj(cx, &args[0].toObject());
if (!obj->isNative()) {
// The object is already checked to be native in GetElemBaseForLambda,
// but it can be swapped to another class that is non-native.
// Return undefined to mark failure to get the property.
args.rval().setUndefined();
return true;
}
JSAtom* atom = AtomizeString(cx, args[1].toString());
if (!atom)
return false;
Value v;
if (GetPropertyPure(cx, obj, AtomToId(atom), &v) && v.isString())
args.rval().set(v);
else
args.rval().setUndefined();
return true;
}
| {
"pile_set_name": "Github"
} |
/**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Aion-Lightning is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License
* along with Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.packetsamurai.parser.datatree;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import com.aionemu.packetsamurai.parser.DataStructure.DataPacketMode;
import com.aionemu.packetsamurai.parser.formattree.Part;
import com.aionemu.packetsamurai.parser.parttypes.StringPartType.stringType;
/**
*
* @author Gilles Duboscq
*
*/
public class StringValuePart extends ValuePart
{
protected String _string;
protected stringType _type;
public StringValuePart(DataTreeNodeContainer parent, Part part, stringType type)
{
super(parent, part);
_type = type;
}
@Override
public void parse(ByteBuffer buf)
{
if(this.getMode() == DataPacketMode.FORGING)
throw new IllegalStateException("Can not parse on a Forging mode Data Packet Tree element");
int pos = buf.position();
int size = 0;
switch(_type)
{
case s:
StringBuffer sb = new StringBuffer();
byte b;
while ((b = buf.get()) != 0)
sb.append((char)b);
_string = sb.toString();
size = sb.length()+1;
break;
case S:
StringBuffer sb2 = new StringBuffer();
char ch;
char first = buf.getChar();
if (first == '$')
{
boolean stringFallback = false;
while ((ch = buf.getChar()) != 0) {
if (ch == '$') {
stringFallback = true;
}
sb2.append(ch);
}
if (stringFallback) {
_string = "$" + sb2.toString();
size = _string.length() * 2 + 2;
break;
}
size = sb2.length() * 2;
buf.position(pos + 2);
byte[] bytes = new byte[size];
for (int i = 0; i < size; i++)
bytes[i] = buf.get();
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.put(bytes);
int value = 0;
if (bytes.length == 1)
value = buffer.get(0);
else if (bytes.length == 2)
value = buffer.getShort(0);
else if (bytes.length == 4)
value = buffer.getInt(0);
_string = Long.toString(value);
size += 4;
}
else
{
buf.position(pos);
while ((ch = buf.getChar()) != 0)
sb2.append(ch);
_string = sb2.toString();
size = sb2.length()*2+2;
}
break;
case Ss:
StringBuffer sb3 = new StringBuffer();
char ch1;
while ((ch1 = buf.getChar()) != 0)
{
sb3.append(ch1);
}
_string = sb3.toString();
size = getBSize();
break;
case Sn:
StringBuffer sb4 = new StringBuffer();
for (int i = 0; i < super.getBSize(); i = i + 2)
{
sb4.append(buf.getChar());
}
_string = sb4.toString();
size = getBSize();
break;
}
// sets the raw bytes
_bytes = new byte[size];
buf.position(pos);
buf.get(_bytes);
}
@Override
public void forge(DataOutput stream) throws IOException
{
if(this.getMode() == DataPacketMode.PARSING)
throw new IllegalStateException("Can not call forge on a Parsing mode Data Packet Tree element");
switch(_type)
{
case S:
if (_string == null)
{
stream.writeChar('\000');
}
else
{
final int len = _string.length();
for (int i=0; i < len; i++)
stream.writeChar(_string.charAt(i));
stream.writeChar('\000');
}
break;
case s:
if (_string == null)
{
stream.write((byte)0x00);
}
else
{
final int len = _string.length();
for (int i=0; i < len; i++)
stream.write((byte) _string.charAt(i));
stream.write((byte)0x00);
}
break;
case Ss:
for (int i = 0; i < (_string.getBytes().length /2); i++)
{
stream.writeChar(_string.charAt(i));
}
break;
default:
break;
}
}
public String getStringValue()
{
return _string;
}
public void setStringValue(String s)
{
if(this.getMode() == DataPacketMode.PARSING)
throw new IllegalStateException("Can not set value on a Parsing mode Data Packet Tree element");
_string = s;
}
@Override
public String getValueAsString()
{
return _string;
}
} | {
"pile_set_name": "Github"
} |
/* Template-specific stuff
*
* Customizations just for the template; these are not necessary for anything
* with disabling the responsiveness.
*/
/* Account for fixed navbar */
body {
padding-top: 70px;
padding-bottom: 30px;
}
body,
.navbar-fixed-top,
.navbar-fixed-bottom {
min-width: 970px;
}
/* Don't let the lead text change font-size. */
.lead {
font-size: 16px;
}
/* Finesse the page header spacing */
.page-header {
margin-bottom: 30px;
}
.page-header .lead {
margin-bottom: 10px;
}
/* Non-responsive overrides
*
* Utilize the following CSS to disable the responsive-ness of the container,
* grid system, and navbar.
*/
/* Reset the container */
.container {
width: 970px;
max-width: none !important;
}
/* Demonstrate the grids */
.col-xs-4 {
padding-top: 15px;
padding-bottom: 15px;
background-color: #eee;
background-color: rgba(86,61,124,.15);
border: 1px solid #ddd;
border: 1px solid rgba(86,61,124,.2);
}
.container .navbar-header,
.container .navbar-collapse {
margin-right: 0;
margin-left: 0;
}
/* Always float the navbar header */
.navbar-header {
float: right;
}
/* Undo the collapsing navbar */
.navbar-collapse {
display: block !important;
height: auto !important;
padding-bottom: 0;
overflow: visible !important;
visibility: visible !important;
}
.navbar-toggle {
display: none;
}
.navbar-collapse {
border-top: 0;
}
.navbar-brand {
margin-right: -15px;
}
/* Always apply the floated nav */
.navbar-nav {
float: right;
margin: 0;
}
.navbar-nav > li {
float: right;
}
.navbar-nav > li > a {
padding: 15px;
}
/* Redeclare since we override the float above */
.navbar-nav.navbar-right {
float: left;
}
/* Undo custom dropdowns */
.navbar .navbar-nav .open .dropdown-menu {
position: absolute;
float: right;
background-color: #fff;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, .15);
border-width: 0 1px 1px;
border-radius: 0 0 4px 4px;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
}
.navbar-default .navbar-nav .open .dropdown-menu > li > a {
color: #333;
}
.navbar .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar .navbar-nav .open .dropdown-menu > li > a:focus,
.navbar .navbar-nav .open .dropdown-menu > .active > a,
.navbar .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar .navbar-nav .open .dropdown-menu > .active > a:focus {
color: #fff !important;
background-color: #428bca !important;
}
.navbar .navbar-nav .open .dropdown-menu > .disabled > a,
.navbar .navbar-nav .open .dropdown-menu > .disabled > a:hover,
.navbar .navbar-nav .open .dropdown-menu > .disabled > a:focus {
color: #999 !important;
background-color: transparent !important;
}
/* Undo form expansion */
.navbar-form {
float: right;
width: auto;
padding-top: 0;
padding-bottom: 0;
margin-right: 0;
margin-left: 0;
border: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
/* Copy-pasted from forms.less since we mixin the .form-inline styles. */
.navbar-form .form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .form-control {
display: inline-block;
width: auto;
vertical-align: middle;
}
.navbar-form .form-control-static {
display: inline-block;
}
.navbar-form .input-group {
display: inline-table;
vertical-align: middle;
}
.navbar-form .input-group .input-group-addon,
.navbar-form .input-group .input-group-btn,
.navbar-form .input-group .form-control {
width: auto;
}
.navbar-form .input-group > .form-control {
width: 100%;
}
.navbar-form .control-label {
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .radio,
.navbar-form .checkbox {
display: inline-block;
margin-top: 0;
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .radio label,
.navbar-form .checkbox label {
padding-right: 0;
}
.navbar-form .radio input[type="radio"],
.navbar-form .checkbox input[type="checkbox"] {
position: relative;
margin-right: 0;
}
.navbar-form .has-feedback .form-control-feedback {
top: 0;
}
| {
"pile_set_name": "Github"
} |
var convert = require('./convert'),
func = convert('omitBy', require('../omitBy'));
func.placeholder = require('./placeholder');
module.exports = func;
| {
"pile_set_name": "Github"
} |
<?php
/* Icinga Web 2 | (c) 2013 Icinga Development Team | GPLv2+ */
namespace Icinga\Module\Monitoring\DataView;
class Customvar extends DataView
{
/**
* {@inheritdoc}
*/
public function getColumns()
{
return array(
'varname',
'varvalue',
'is_json',
'host_name',
'service_description',
'contact_name',
'object_type',
'object_type_id'
);
}
/**
* {@inheritdoc}
*/
public function getSortRules()
{
return array(
'varname' => array(
'columns' => array(
'varname',
'varvalue'
)
)
);
}
/**
* {@inheritdoc}
*/
public function getStaticFilterColumns()
{
return array('host', 'service', 'contact');
}
}
| {
"pile_set_name": "Github"
} |
/*
* contrib/hstore/hstore_gist.c
*/
#include "postgres.h"
#include "access/gist.h"
#include "access/stratnum.h"
#include "catalog/pg_type.h"
#include "utils/pg_crc.h"
#include "hstore.h"
/* bigint defines */
#define BITBYTE 8
#define SIGLENINT 4 /* >122 => key will toast, so very slow!!! */
#define SIGLEN ( sizeof(int)*SIGLENINT )
#define SIGLENBIT (SIGLEN*BITBYTE)
typedef char BITVEC[SIGLEN];
typedef char *BITVECP;
#define SIGPTR(x) ( (BITVECP) ARR_DATA_PTR(x) )
#define LOOPBYTE \
for(i=0;i<SIGLEN;i++)
#define LOOPBIT \
for(i=0;i<SIGLENBIT;i++)
/* beware of multiple evaluation of arguments to these macros! */
#define GETBYTE(x,i) ( *( (BITVECP)(x) + (int)( (i) / BITBYTE ) ) )
#define GETBITBYTE(x,i) ( (*((char*)(x)) >> (i)) & 0x01 )
#define CLRBIT(x,i) GETBYTE(x,i) &= ~( 0x01 << ( (i) % BITBYTE ) )
#define SETBIT(x,i) GETBYTE(x,i) |= ( 0x01 << ( (i) % BITBYTE ) )
#define GETBIT(x,i) ( (GETBYTE(x,i) >> ( (i) % BITBYTE )) & 0x01 )
#define HASHVAL(val) (((unsigned int)(val)) % SIGLENBIT)
#define HASH(sign, val) SETBIT((sign), HASHVAL(val))
typedef struct
{
int32 vl_len_; /* varlena header (do not touch directly!) */
int32 flag;
char data[FLEXIBLE_ARRAY_MEMBER];
} GISTTYPE;
#define ALLISTRUE 0x04
#define ISALLTRUE(x) ( ((GISTTYPE*)x)->flag & ALLISTRUE )
#define GTHDRSIZE (VARHDRSZ + sizeof(int32))
#define CALCGTSIZE(flag) ( GTHDRSIZE+(((flag) & ALLISTRUE) ? 0 : SIGLEN) )
#define GETSIGN(x) ( (BITVECP)( (char*)x+GTHDRSIZE ) )
#define SUMBIT(val) ( \
GETBITBYTE((val),0) + \
GETBITBYTE((val),1) + \
GETBITBYTE((val),2) + \
GETBITBYTE((val),3) + \
GETBITBYTE((val),4) + \
GETBITBYTE((val),5) + \
GETBITBYTE((val),6) + \
GETBITBYTE((val),7) \
)
#define GETENTRY(vec,pos) ((GISTTYPE *) DatumGetPointer((vec)->vector[(pos)].key))
#define WISH_F(a,b,c) (double)( -(double)(((a)-(b))*((a)-(b))*((a)-(b)))*(c) )
/* shorthand for calculating CRC-32 of a single chunk of data. */
static pg_crc32
crc32_sz(char *buf, int size)
{
pg_crc32 crc;
INIT_TRADITIONAL_CRC32(crc);
COMP_TRADITIONAL_CRC32(crc, buf, size);
FIN_TRADITIONAL_CRC32(crc);
return crc;
}
PG_FUNCTION_INFO_V1(ghstore_in);
PG_FUNCTION_INFO_V1(ghstore_out);
Datum
ghstore_in(PG_FUNCTION_ARGS)
{
elog(ERROR, "Not implemented");
PG_RETURN_DATUM(0);
}
Datum
ghstore_out(PG_FUNCTION_ARGS)
{
elog(ERROR, "Not implemented");
PG_RETURN_DATUM(0);
}
PG_FUNCTION_INFO_V1(ghstore_consistent);
PG_FUNCTION_INFO_V1(ghstore_compress);
PG_FUNCTION_INFO_V1(ghstore_decompress);
PG_FUNCTION_INFO_V1(ghstore_penalty);
PG_FUNCTION_INFO_V1(ghstore_picksplit);
PG_FUNCTION_INFO_V1(ghstore_union);
PG_FUNCTION_INFO_V1(ghstore_same);
Datum
ghstore_compress(PG_FUNCTION_ARGS)
{
GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
GISTENTRY *retval = entry;
if (entry->leafkey)
{
GISTTYPE *res = (GISTTYPE *) palloc0(CALCGTSIZE(0));
HStore *val = DatumGetHStoreP(entry->key);
HEntry *hsent = ARRPTR(val);
char *ptr = STRPTR(val);
int count = HS_COUNT(val);
int i;
SET_VARSIZE(res, CALCGTSIZE(0));
for (i = 0; i < count; ++i)
{
int h;
h = crc32_sz((char *) HSTORE_KEY(hsent, ptr, i),
HSTORE_KEYLEN(hsent, i));
HASH(GETSIGN(res), h);
if (!HSTORE_VALISNULL(hsent, i))
{
h = crc32_sz((char *) HSTORE_VAL(hsent, ptr, i),
HSTORE_VALLEN(hsent, i));
HASH(GETSIGN(res), h);
}
}
retval = (GISTENTRY *) palloc(sizeof(GISTENTRY));
gistentryinit(*retval, PointerGetDatum(res),
entry->rel, entry->page,
entry->offset,
FALSE);
}
else if (!ISALLTRUE(DatumGetPointer(entry->key)))
{
int32 i;
GISTTYPE *res;
BITVECP sign = GETSIGN(DatumGetPointer(entry->key));
LOOPBYTE
{
if ((sign[i] & 0xff) != 0xff)
PG_RETURN_POINTER(retval);
}
res = (GISTTYPE *) palloc(CALCGTSIZE(ALLISTRUE));
SET_VARSIZE(res, CALCGTSIZE(ALLISTRUE));
res->flag = ALLISTRUE;
retval = (GISTENTRY *) palloc(sizeof(GISTENTRY));
gistentryinit(*retval, PointerGetDatum(res),
entry->rel, entry->page,
entry->offset,
FALSE);
}
PG_RETURN_POINTER(retval);
}
/*
* Since type ghstore isn't toastable (and doesn't need to be),
* this function can be a no-op.
*/
Datum
ghstore_decompress(PG_FUNCTION_ARGS)
{
PG_RETURN_POINTER(PG_GETARG_POINTER(0));
}
Datum
ghstore_same(PG_FUNCTION_ARGS)
{
GISTTYPE *a = (GISTTYPE *) PG_GETARG_POINTER(0);
GISTTYPE *b = (GISTTYPE *) PG_GETARG_POINTER(1);
bool *result = (bool *) PG_GETARG_POINTER(2);
if (ISALLTRUE(a) && ISALLTRUE(b))
*result = true;
else if (ISALLTRUE(a))
*result = false;
else if (ISALLTRUE(b))
*result = false;
else
{
int32 i;
BITVECP sa = GETSIGN(a),
sb = GETSIGN(b);
*result = true;
LOOPBYTE
{
if (sa[i] != sb[i])
{
*result = false;
break;
}
}
}
PG_RETURN_POINTER(result);
}
static int32
sizebitvec(BITVECP sign)
{
int32 size = 0,
i;
LOOPBYTE
{
size += SUMBIT(sign);
sign = (BITVECP) (((char *) sign) + 1);
}
return size;
}
static int
hemdistsign(BITVECP a, BITVECP b)
{
int i,
dist = 0;
LOOPBIT
{
if (GETBIT(a, i) != GETBIT(b, i))
dist++;
}
return dist;
}
static int
hemdist(GISTTYPE *a, GISTTYPE *b)
{
if (ISALLTRUE(a))
{
if (ISALLTRUE(b))
return 0;
else
return SIGLENBIT - sizebitvec(GETSIGN(b));
}
else if (ISALLTRUE(b))
return SIGLENBIT - sizebitvec(GETSIGN(a));
return hemdistsign(GETSIGN(a), GETSIGN(b));
}
static int32
unionkey(BITVECP sbase, GISTTYPE *add)
{
int32 i;
BITVECP sadd = GETSIGN(add);
if (ISALLTRUE(add))
return 1;
LOOPBYTE
sbase[i] |= sadd[i];
return 0;
}
Datum
ghstore_union(PG_FUNCTION_ARGS)
{
GistEntryVector *entryvec = (GistEntryVector *) PG_GETARG_POINTER(0);
int32 len = entryvec->n;
int *size = (int *) PG_GETARG_POINTER(1);
BITVEC base;
int32 i;
int32 flag = 0;
GISTTYPE *result;
MemSet((void *) base, 0, sizeof(BITVEC));
for (i = 0; i < len; i++)
{
if (unionkey(base, GETENTRY(entryvec, i)))
{
flag = ALLISTRUE;
break;
}
}
len = CALCGTSIZE(flag);
result = (GISTTYPE *) palloc(len);
SET_VARSIZE(result, len);
result->flag = flag;
if (!ISALLTRUE(result))
memcpy((void *) GETSIGN(result), (void *) base, sizeof(BITVEC));
*size = len;
PG_RETURN_POINTER(result);
}
Datum
ghstore_penalty(PG_FUNCTION_ARGS)
{
GISTENTRY *origentry = (GISTENTRY *) PG_GETARG_POINTER(0); /* always ISSIGNKEY */
GISTENTRY *newentry = (GISTENTRY *) PG_GETARG_POINTER(1);
float *penalty = (float *) PG_GETARG_POINTER(2);
GISTTYPE *origval = (GISTTYPE *) DatumGetPointer(origentry->key);
GISTTYPE *newval = (GISTTYPE *) DatumGetPointer(newentry->key);
*penalty = hemdist(origval, newval);
PG_RETURN_POINTER(penalty);
}
typedef struct
{
OffsetNumber pos;
int32 cost;
} SPLITCOST;
static int
comparecost(const void *a, const void *b)
{
return ((const SPLITCOST *) a)->cost - ((const SPLITCOST *) b)->cost;
}
Datum
ghstore_picksplit(PG_FUNCTION_ARGS)
{
GistEntryVector *entryvec = (GistEntryVector *) PG_GETARG_POINTER(0);
OffsetNumber maxoff = entryvec->n - 2;
GIST_SPLITVEC *v = (GIST_SPLITVEC *) PG_GETARG_POINTER(1);
OffsetNumber k,
j;
GISTTYPE *datum_l,
*datum_r;
BITVECP union_l,
union_r;
int32 size_alpha,
size_beta;
int32 size_waste,
waste = -1;
int32 nbytes;
OffsetNumber seed_1 = 0,
seed_2 = 0;
OffsetNumber *left,
*right;
BITVECP ptr;
int i;
SPLITCOST *costvector;
GISTTYPE *_k,
*_j;
nbytes = (maxoff + 2) * sizeof(OffsetNumber);
v->spl_left = (OffsetNumber *) palloc(nbytes);
v->spl_right = (OffsetNumber *) palloc(nbytes);
for (k = FirstOffsetNumber; k < maxoff; k = OffsetNumberNext(k))
{
_k = GETENTRY(entryvec, k);
for (j = OffsetNumberNext(k); j <= maxoff; j = OffsetNumberNext(j))
{
size_waste = hemdist(_k, GETENTRY(entryvec, j));
if (size_waste > waste)
{
waste = size_waste;
seed_1 = k;
seed_2 = j;
}
}
}
left = v->spl_left;
v->spl_nleft = 0;
right = v->spl_right;
v->spl_nright = 0;
if (seed_1 == 0 || seed_2 == 0)
{
seed_1 = 1;
seed_2 = 2;
}
/* form initial .. */
if (ISALLTRUE(GETENTRY(entryvec, seed_1)))
{
datum_l = (GISTTYPE *) palloc(GTHDRSIZE);
SET_VARSIZE(datum_l, GTHDRSIZE);
datum_l->flag = ALLISTRUE;
}
else
{
datum_l = (GISTTYPE *) palloc(GTHDRSIZE + SIGLEN);
SET_VARSIZE(datum_l, GTHDRSIZE + SIGLEN);
datum_l->flag = 0;
memcpy((void *) GETSIGN(datum_l), (void *) GETSIGN(GETENTRY(entryvec, seed_1)), sizeof(BITVEC))
;
}
if (ISALLTRUE(GETENTRY(entryvec, seed_2)))
{
datum_r = (GISTTYPE *) palloc(GTHDRSIZE);
SET_VARSIZE(datum_r, GTHDRSIZE);
datum_r->flag = ALLISTRUE;
}
else
{
datum_r = (GISTTYPE *) palloc(GTHDRSIZE + SIGLEN);
SET_VARSIZE(datum_r, GTHDRSIZE + SIGLEN);
datum_r->flag = 0;
memcpy((void *) GETSIGN(datum_r), (void *) GETSIGN(GETENTRY(entryvec, seed_2)), sizeof(BITVEC));
}
maxoff = OffsetNumberNext(maxoff);
/* sort before ... */
costvector = (SPLITCOST *) palloc(sizeof(SPLITCOST) * maxoff);
for (j = FirstOffsetNumber; j <= maxoff; j = OffsetNumberNext(j))
{
costvector[j - 1].pos = j;
_j = GETENTRY(entryvec, j);
size_alpha = hemdist(datum_l, _j);
size_beta = hemdist(datum_r, _j);
costvector[j - 1].cost = abs(size_alpha - size_beta);
}
qsort((void *) costvector, maxoff, sizeof(SPLITCOST), comparecost);
union_l = GETSIGN(datum_l);
union_r = GETSIGN(datum_r);
for (k = 0; k < maxoff; k++)
{
j = costvector[k].pos;
if (j == seed_1)
{
*left++ = j;
v->spl_nleft++;
continue;
}
else if (j == seed_2)
{
*right++ = j;
v->spl_nright++;
continue;
}
_j = GETENTRY(entryvec, j);
size_alpha = hemdist(datum_l, _j);
size_beta = hemdist(datum_r, _j);
if (size_alpha < size_beta + WISH_F(v->spl_nleft, v->spl_nright, 0.0001))
{
if (ISALLTRUE(datum_l) || ISALLTRUE(_j))
{
if (!ISALLTRUE(datum_l))
MemSet((void *) union_l, 0xff, sizeof(BITVEC));
}
else
{
ptr = GETSIGN(_j);
LOOPBYTE
union_l[i] |= ptr[i];
}
*left++ = j;
v->spl_nleft++;
}
else
{
if (ISALLTRUE(datum_r) || ISALLTRUE(_j))
{
if (!ISALLTRUE(datum_r))
MemSet((void *) union_r, 0xff, sizeof(BITVEC));
}
else
{
ptr = GETSIGN(_j);
LOOPBYTE
union_r[i] |= ptr[i];
}
*right++ = j;
v->spl_nright++;
}
}
*right = *left = FirstOffsetNumber;
v->spl_ldatum = PointerGetDatum(datum_l);
v->spl_rdatum = PointerGetDatum(datum_r);
PG_RETURN_POINTER(v);
}
Datum
ghstore_consistent(PG_FUNCTION_ARGS)
{
GISTTYPE *entry = (GISTTYPE *) DatumGetPointer(((GISTENTRY *) PG_GETARG_POINTER(0))->key);
StrategyNumber strategy = (StrategyNumber) PG_GETARG_UINT16(2);
/* Oid subtype = PG_GETARG_OID(3); */
bool *recheck = (bool *) PG_GETARG_POINTER(4);
bool res = true;
BITVECP sign;
/* All cases served by this function are inexact */
*recheck = true;
if (ISALLTRUE(entry))
PG_RETURN_BOOL(true);
sign = GETSIGN(entry);
if (strategy == HStoreContainsStrategyNumber ||
strategy == HStoreOldContainsStrategyNumber)
{
HStore *query = PG_GETARG_HS(1);
HEntry *qe = ARRPTR(query);
char *qv = STRPTR(query);
int count = HS_COUNT(query);
int i;
for (i = 0; res && i < count; ++i)
{
int crc = crc32_sz((char *) HSTORE_KEY(qe, qv, i),
HSTORE_KEYLEN(qe, i));
if (GETBIT(sign, HASHVAL(crc)))
{
if (!HSTORE_VALISNULL(qe, i))
{
crc = crc32_sz((char *) HSTORE_VAL(qe, qv, i),
HSTORE_VALLEN(qe, i));
if (!GETBIT(sign, HASHVAL(crc)))
res = false;
}
}
else
res = false;
}
}
else if (strategy == HStoreExistsStrategyNumber)
{
text *query = PG_GETARG_TEXT_PP(1);
int crc = crc32_sz(VARDATA_ANY(query), VARSIZE_ANY_EXHDR(query));
res = (GETBIT(sign, HASHVAL(crc))) ? true : false;
}
else if (strategy == HStoreExistsAllStrategyNumber)
{
ArrayType *query = PG_GETARG_ARRAYTYPE_P(1);
Datum *key_datums;
bool *key_nulls;
int key_count;
int i;
deconstruct_array(query,
TEXTOID, -1, false, 'i',
&key_datums, &key_nulls, &key_count);
for (i = 0; res && i < key_count; ++i)
{
int crc;
if (key_nulls[i])
continue;
crc = crc32_sz(VARDATA(key_datums[i]), VARSIZE(key_datums[i]) - VARHDRSZ);
if (!(GETBIT(sign, HASHVAL(crc))))
res = FALSE;
}
}
else if (strategy == HStoreExistsAnyStrategyNumber)
{
ArrayType *query = PG_GETARG_ARRAYTYPE_P(1);
Datum *key_datums;
bool *key_nulls;
int key_count;
int i;
deconstruct_array(query,
TEXTOID, -1, false, 'i',
&key_datums, &key_nulls, &key_count);
res = FALSE;
for (i = 0; !res && i < key_count; ++i)
{
int crc;
if (key_nulls[i])
continue;
crc = crc32_sz(VARDATA(key_datums[i]), VARSIZE(key_datums[i]) - VARHDRSZ);
if (GETBIT(sign, HASHVAL(crc)))
res = TRUE;
}
}
else
elog(ERROR, "Unsupported strategy number: %d", strategy);
PG_RETURN_BOOL(res);
}
| {
"pile_set_name": "Github"
} |
del libWrapper_CAN.a
g++ -DNO_INCLUDE_TEMPSTRUCT -c Trigonometric.cpp BMCANDefines.cpp BMUtility.cpp StringFunctions.cpp FileOperations.cpp OtherCaplFunc.cpp CANCAPLWrapper.cpp Wrapper_Common.cpp
ar -rcs libWrapper_CAN.a Trigonometric.o StringFunctions.o BMCANDefines.o BMUtility.o OtherCaplFunc.o FileOperations.o CANCAPLWrapper.o Wrapper_Common.o
del Trigonometric.o StringFunctions.o BMCANDefines.o BMUtility.o OtherCaplFunc.o FileOperations.o CANCAPLWrapper.o Wrapper_Common.o
copy /Y libWrapper_CAN.a ..\OBJ\
| {
"pile_set_name": "Github"
} |
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
FROM jupyter/all-spark-notebook:dbb9c7b50531
# Install Kernel Gateway
RUN pip install --no-cache-dir jupyter_kernel_gateway
# Configure container startup
ENTRYPOINT ["tini", "--", "jupyter", "kernelgateway"]
LABEL version="1.0.0"
LABEL service="Swagger Petstore"
CMD [ \
"--KernelGatewayApp.api=notebook-http", \
"--KernelGatewayApp.seed_uri=/srv/notebooks/SwaggerPetstoreApi.ipynb", \
"--KernelGatewayApp.allow_origin='http://editor.swagger.io'", \
" --KernelGatewayApp.allow_methods='GET, POST, PUT, DELETE'", \
"--KernelGatewayApp.allow_headers='accept, accept-language, content-type'", \
"--KernelGatewayApp.ip=0.0.0.0" \
]
ADD SwaggerPetstoreApi.ipynb /srv/notebooks/
| {
"pile_set_name": "Github"
} |
Templating Component
====================
Templating provides all the tools needed to build any kind of template system.
It provides an infrastructure to load template files and optionally monitor
them for changes. It also provides a concrete template engine implementation
using PHP with additional tools for escaping and separating templates into
blocks and layouts.
Resources
---------
You can run the unit tests with the following command:
$ cd path/to/Symfony/Component/Templating/
$ composer.phar install
$ phpunit
| {
"pile_set_name": "Github"
} |
/// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
* @path ch15/15.2/15.2.3/15.2.3.7/15.2.3.7-5-b-264.js
* @description Object.defineProperties - TypeError is thrown if both 'get' property and 'writable' property of 'descObj' are present (8.10.5 step 9.a)
*/
function testcase() {
var getFun = function () {};
var obj = {};
try {
Object.defineProperties(obj, {
"prop": {
writable: true,
get: getFun
}
});
return false;
} catch (e) {
return (e instanceof TypeError);
}
}
runTestCase(testcase);
| {
"pile_set_name": "Github"
} |
"""
SymPy core decorators.
The purpose of this module is to expose decorators without any other
dependencies, so that they can be easily imported anywhere in sympy/core.
"""
from __future__ import print_function, division
from functools import wraps
from .sympify import SympifyError, sympify
from sympy.core.compatibility import get_function_code
def deprecated(**decorator_kwargs):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used."""
def deprecated_decorator(func):
@wraps(func)
def new_func(*args, **kwargs):
from sympy.utilities.exceptions import SymPyDeprecationWarning
decorator_kwargs.setdefault('feature', func.__name__)
SymPyDeprecationWarning(**decorator_kwargs).warn(stacklevel=3)
return func(*args, **kwargs)
return new_func
return deprecated_decorator
def _sympifyit(arg, retval=None):
"""decorator to smartly _sympify function arguments
@_sympifyit('other', NotImplemented)
def add(self, other):
...
In add, other can be thought of as already being a SymPy object.
If it is not, the code is likely to catch an exception, then other will
be explicitly _sympified, and the whole code restarted.
if _sympify(arg) fails, NotImplemented will be returned
see: __sympifyit
"""
def deco(func):
return __sympifyit(func, arg, retval)
return deco
def __sympifyit(func, arg, retval=None):
"""decorator to _sympify `arg` argument for function `func`
don't use directly -- use _sympifyit instead
"""
# we support f(a,b) only
assert get_function_code(func).co_argcount
# only b is _sympified
assert get_function_code(func).co_varnames[1] == arg
if retval is None:
@wraps(func)
def __sympifyit_wrapper(a, b):
return func(a, sympify(b, strict=True))
else:
@wraps(func)
def __sympifyit_wrapper(a, b):
try:
# If an external class has _op_priority, it knows how to deal
# with sympy objects. Otherwise, it must be converted.
if not hasattr(b, '_op_priority'):
b = sympify(b, strict=True)
return func(a, b)
except SympifyError:
return retval
return __sympifyit_wrapper
def call_highest_priority(method_name):
"""A decorator for binary special methods to handle _op_priority.
Binary special methods in Expr and its subclasses use a special attribute
'_op_priority' to determine whose special method will be called to
handle the operation. In general, the object having the highest value of
'_op_priority' will handle the operation. Expr and subclasses that define
custom binary special methods (__mul__, etc.) should decorate those
methods with this decorator to add the priority logic.
The ``method_name`` argument is the name of the method of the other class
that will be called. Use this decorator in the following manner::
# Call other.__rmul__ if other._op_priority > self._op_priority
@call_highest_priority('__rmul__')
def __mul__(self, other):
...
# Call other.__mul__ if other._op_priority > self._op_priority
@call_highest_priority('__mul__')
def __rmul__(self, other):
...
"""
def priority_decorator(func):
@wraps(func)
def binary_op_wrapper(self, other):
if hasattr(other, '_op_priority'):
if other._op_priority > self._op_priority:
try:
f = getattr(other, method_name)
except AttributeError:
pass
else:
return f(self)
return func(self, other)
return binary_op_wrapper
return priority_decorator
| {
"pile_set_name": "Github"
} |
/*!
* Datepicker for Bootstrap
*
* Copyright 2012 Stefan Petre
* Improvements by Andrew Rowls
* Licensed under the Apache License v2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
*/
.datepicker {
padding: 4px;
.border-radius(4px);
&-inline {
width: 220px;
}
direction: ltr;
&&-rtl {
direction: rtl;
table tr td span {
float: right;
}
}
&-dropdown {
top: 0;
left: 0;
&:before {
content: '';
display: inline-block;
border-left: 7px solid transparent;
border-right: 7px solid transparent;
border-bottom: 7px solid #ccc;
border-bottom-color: rgba(0,0,0,.2);
position: absolute;
top: -7px;
left: 6px;
}
&:after {
content: '';
display: inline-block;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
border-bottom: 6px solid @white;
position: absolute;
top: -6px;
left: 7px;
}
}
>div {
display: none;
}
&.days div.datepicker-days {
display: block;
}
&.months div.datepicker-months {
display: block;
}
&.years div.datepicker-years {
display: block;
}
table{
margin: 0;
}
td,
th{
text-align: center;
width: 20px;
height: 20px;
.border-radius(4px);
border: none;
}
// Inline display inside a table presents some problems with
// border and background colors.
.table-striped & table tr {
td, th {
background-color:transparent;
}
}
table tr td {
&.day:hover {
background: @grayLighter;
cursor: pointer;
}
&.old,
&.new {
color: @grayLight;
}
&.disabled,
&.disabled:hover {
background: none;
color: @grayLight;
cursor: default;
}
&.today,
&.today:hover,
&.today.disabled,
&.today.disabled:hover {
@todayBackground: lighten(@orange, 30%);
.buttonBackground(@todayBackground, spin(@todayBackground, 20));
color: #000 !important;
}
&.range,
&.range:hover,
&.range.disabled,
&.range.disabled:hover {
background:@grayLighter;
.border-radius(0);
}
&.range.today,
&.range.today:hover,
&.range.today.disabled,
&.range.today.disabled:hover {
@todayBackground: mix(@orange, @grayLighter);
.buttonBackground(@todayBackground, spin(@todayBackground, 20));
.border-radius(0);
}
&.selected,
&.selected:hover,
&.selected.disabled,
&.selected.disabled:hover {
.buttonBackground(lighten(@grayLight, 10), darken(@grayLight, 10));
color: #fff;
text-shadow: 0 -1px 0 rgba(0,0,0,.25);
}
&.active,
&.active:hover,
&.active.disabled,
&.active.disabled:hover {
.buttonBackground(@btnPrimaryBackground, spin(@btnPrimaryBackground, 20));
color: #fff;
text-shadow: 0 -1px 0 rgba(0,0,0,.25);
}
span {
display: block;
width: 23%;
height: 54px;
line-height: 54px;
float: left;
margin: 1%;
cursor: pointer;
.border-radius(4px);
&:hover {
background: @grayLighter;
}
&.disabled,
&.disabled:hover {
background:none;
color: @grayLight;
cursor: default;
}
&.active,
&.active:hover,
&.active.disabled,
&.active.disabled:hover {
.buttonBackground(@btnPrimaryBackground, spin(@btnPrimaryBackground, 20));
color: #fff;
text-shadow: 0 -1px 0 rgba(0,0,0,.25);
}
&.old {
color: @grayLight;
}
}
}
th.datepicker-switch {
width: 145px;
}
thead tr:first-child th,
tfoot tr:first-child th {
cursor: pointer;
&:hover{
background: @grayLighter;
}
}
/*.dow {
border-top: 1px solid #ddd !important;
}*/
// Basic styling for calendar-week cells
.cw {
font-size: 10px;
width: 12px;
padding: 0 2px 0 5px;
vertical-align: middle;
}
thead tr:first-child th.cw {
cursor: default;
background-color: transparent;
}
}
.input-append,
.input-prepend {
&.date {
.add-on i {
display: block;
cursor: pointer;
width: 16px;
height: 16px;
}
}
}
.input-daterange {
input {
text-align:center;
}
input:first-child {
.border-radius(3px 0 0 3px);
}
input:last-child {
.border-radius(0 3px 3px 0);
}
.add-on {
display: inline-block;
width: auto;
min-width: 16px;
height: @baseLineHeight;
padding: 4px 5px;
font-weight: normal;
line-height: @baseLineHeight;
text-align: center;
text-shadow: 0 1px 0 @white;
vertical-align: middle;
background-color: @grayLighter;
border: 1px solid #ccc;
margin-left:-5px;
margin-right:-5px;
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package systemd
import (
"bytes"
"io"
"github.com/coreos/go-systemd/v22/unit"
)
// UnitSerialize encodes all of the given UnitOption objects into a unit file.
// Renamed from Serialize from github.com/coreos/go-systemd/unit so as to not
// conflict with the exported internal function in export_test.go.
func UnitSerialize(opts []*unit.UnitOption) io.Reader {
var buf bytes.Buffer
if len(opts) == 0 {
return &buf
}
idx := map[string][]*unit.UnitOption{}
for _, opt := range opts {
idx[opt.Section] = append(idx[opt.Section], opt)
}
// CHANGED HERE: Output in the following order:
// - Unit
// - Service
// - Install
// rather than just iterating over the map in random order.
for _, curSection := range []string{"Unit", "Service", "Install"} {
curOpts, found := idx[curSection]
if !found {
continue
}
writeSectionHeader(&buf, curSection)
writeNewline(&buf)
for _, opt := range curOpts {
writeOption(&buf, opt)
writeNewline(&buf)
}
writeNewline(&buf)
}
return &buf
}
func writeNewline(buf *bytes.Buffer) {
buf.WriteRune('\n')
}
func writeSectionHeader(buf *bytes.Buffer, section string) {
buf.WriteRune('[')
buf.WriteString(section)
buf.WriteRune(']')
}
func writeOption(buf *bytes.Buffer, opt *unit.UnitOption) {
buf.WriteString(opt.Name)
buf.WriteRune('=')
buf.WriteString(opt.Value)
}
| {
"pile_set_name": "Github"
} |
package org.zstack.test.storage.volume;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.header.identity.SessionInventory;
import org.zstack.header.query.QueryCondition;
import org.zstack.header.query.QueryOp;
import org.zstack.header.vm.VmInstanceInventory;
import org.zstack.header.volume.APIQueryVolumeMsg;
import org.zstack.header.volume.APIQueryVolumeReply;
import org.zstack.header.volume.VolumeInventory;
import org.zstack.test.Api;
import org.zstack.test.ApiSenderException;
import org.zstack.test.DBUtil;
import org.zstack.test.deployer.Deployer;
import org.zstack.test.identity.IdentityCreator;
import org.zstack.test.search.QueryTestValidator;
import org.zstack.utils.data.SizeUnit;
import java.util.List;
public class TestQueryVolume {
Deployer deployer;
Api api;
ComponentLoader loader;
CloudBus bus;
DatabaseFacade dbf;
@Before
public void setUp() throws Exception {
DBUtil.reDeployDB();
deployer = new Deployer("deployerXml/volume/TestQueryVolume.xml");
deployer.build();
api = deployer.getApi();
loader = deployer.getComponentLoader();
bus = loader.getComponent(CloudBus.class);
dbf = loader.getComponent(DatabaseFacade.class);
}
@Test
public void test() throws ApiSenderException, InterruptedException {
IdentityCreator identityCreator = new IdentityCreator(api);
identityCreator.useAccount("test");
SessionInventory session = identityCreator.getAccountSession();
VmInstanceInventory vm = deployer.vms.get("TestVm");
List<VolumeInventory> volumes = vm.getAllVolumes();
for (VolumeInventory vol : volumes) {
QueryTestValidator.validateEQ(new APIQueryVolumeMsg(), api, APIQueryVolumeReply.class, vol, session);
QueryTestValidator.validateRandomEQConjunction(new APIQueryVolumeMsg(), api, APIQueryVolumeReply.class, vol, session, 3);
}
APIQueryVolumeMsg msg = new APIQueryVolumeMsg();
QueryCondition c = new QueryCondition();
c.setName("size");
c.setOp(QueryOp.GT_AND_EQ.toString());
c.setValue(String.valueOf(SizeUnit.GIGABYTE.toByte(100)));
msg.getConditions().add(c);
APIQueryVolumeReply reply = api.query(msg, APIQueryVolumeReply.class, session);
Assert.assertEquals(2, reply.getInventories().size());
msg = new APIQueryVolumeMsg();
c = new QueryCondition();
c.setName("size");
c.setOp(QueryOp.LT.toString());
c.setValue(String.valueOf(SizeUnit.GIGABYTE.toByte(120)));
msg.getConditions().add(c);
reply = api.query(msg, APIQueryVolumeReply.class, session);
Assert.assertEquals(2, reply.getInventories().size());
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<wodefinitions>
<wo class="AjaxAccordionTab2.java" wocomponentcontent="true">
<binding name="title"/>
</wo>
</wodefinitions>
| {
"pile_set_name": "Github"
} |
module.exports = require('./pre');
| {
"pile_set_name": "Github"
} |
var convert = require('./convert'),
func = convert('findLastKey', require('../findLastKey'));
func.placeholder = require('./placeholder');
module.exports = func;
| {
"pile_set_name": "Github"
} |
// See bug75
module autoinst_interface
(/*AUTOINOUTMODULE("autoinst_interface_sub")*/
// Beginning of automatic in/out/inouts (from specific module)
logic [7:0] count,
logic clk,
logic reset,
logic start,
my_svi.master my_svi_port,
my_svi my_svi_noport,
my_svi my_svi_noport_upper_decl
// End of automatics
);
endmodule
module autoinst_interface
(/*AUTOINOUTCOMP("autoinst_interface_sub")*/
// Beginning of automatic in/out/inouts (from specific module)
logic clk,
logic reset,
logic start,
logic [7:0] count,
my_svi.master my_svi_port,
my_svi my_svi_noport,
my_svi my_svi_noport_upper_decl
// End of automatics
);
endmodule
module top;
/*AUTOLOGIC*/
// Beginning of automatic wires (for undeclared instantiated-module outputs)
logic [7:0] count; // From submod0 of autoinst_interface_sub.v
// End of automatics
my_svi my_svi_noport_upper_decl ();
autoinst_interface_sub submod0 (/*AUTOINST*/
// Interfaces
.my_svi_port (my_svi_port.master),
.my_svi_noport (my_svi_noport),
.my_svi_noport_upper_decl(my_svi_noport_upper_decl),
// Outputs
.count (count[7:0]),
// Inputs
.clk (clk),
.reset (reset),
.start (start));
endmodule
| {
"pile_set_name": "Github"
} |
# This is a comment
# We can use equal or colon notation
DIR: root
FLAVOUR: none
INSIDE_FOLDER=false | {
"pile_set_name": "Github"
} |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Threading.Tasks;
using FluentAssertions;
using Xunit;
namespace NotIntegration.Tests
{
public class IntegrationTests : IClassFixture<DotnetTryFixture>
{
private readonly DotnetTryFixture _fixture;
public IntegrationTests(DotnetTryFixture fixture)
{
_fixture = fixture;
}
[ConditionalIntegrationTestFact(Skip = "This doesn't work yet")]
public async Task Can_serve_blazor_console_code_runner()
{
var response = await _fixture.GetAsync(@"/LocalCodeRunner/blazor-console");
response.StatusCode.Should().Be(200);
var result = await response.Content.ReadAsStringAsync();
result.Should().Contain("Loading...");
}
[ConditionalIntegrationTestFact]
public async Task Can_serve_bundleCss()
{
var response = await _fixture.GetAsync(@"/client/bundle.css");
response.StatusCode.Should().Be(200);
var content = await response.Content.ReadAsStringAsync();
content.Should().NotBeNullOrEmpty();
}
[ConditionalIntegrationTestFact]
public async Task Can_serve_bundlejs()
{
var response = await _fixture.GetAsync(@"/client/2.bundle.js");
response.StatusCode.Should().Be(200);
var content = await response.Content.ReadAsStringAsync();
content.Should().NotBeNullOrEmpty();
}
[ConditionalIntegrationTestFact]
public async Task Can_serve_clientapi()
{
var response = await _fixture.GetAsync(@"/api/trydotnet.min.js");
response.StatusCode.Should().Be(200);
var content = await response.Content.ReadAsStringAsync();
content.Should().NotBeNullOrEmpty();
}
}
}
| {
"pile_set_name": "Github"
} |
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// +k8s:deepcopy-gen=package
// +k8s:openapi-gen=true
// +groupName=authorization.k8s.io
package v1beta1 // import "k8s.io/api/authorization/v1beta1"
| {
"pile_set_name": "Github"
} |
Version:1.0
Anvil
ANV-3M
Config:Biped
TechBase:Inner Sphere
Era:3055
Source:TRO 3055 - Clan Invasion
Rules Level:2
Mass:60
Engine:300 Fusion Engine
Structure:Endo Steel
Myomer:Standard
Heat Sinks:12 Double
Walk MP:5
Jump MP:3
Armor:Standard(Inner Sphere)
LA Armor:15
RA Armor:15
LT Armor:19
RT Armor:19
CT Armor:24
HD Armor:9
LL Armor:15
RL Armor:15
RTL Armor:7
RTR Armor:7
RTC Armor:7
Weapons:4
Large Pulse Laser, Left Torso
Large Pulse Laser, Right Torso
Medium Laser, Center Torso
Medium Laser, Head
Left Arm:
Shoulder
Upper Arm Actuator
Lower Arm Actuator
Hand Actuator
Endo Steel
Endo Steel
-Empty-
-Empty-
-Empty-
-Empty-
-Empty-
-Empty-
Right Arm:
Shoulder
Upper Arm Actuator
Lower Arm Actuator
Hand Actuator
Endo Steel
Endo Steel
-Empty-
-Empty-
-Empty-
-Empty-
-Empty-
-Empty-
Left Torso:
ISLargePulseLaser
ISLargePulseLaser
Endo Steel
Endo Steel
Endo Steel
Endo Steel
-Empty-
-Empty-
-Empty-
-Empty-
-Empty-
-Empty-
Right Torso:
ISLargePulseLaser
ISLargePulseLaser
ISGuardianECMSuite
ISGuardianECMSuite
Endo Steel
Endo Steel
Endo Steel
Endo Steel
-Empty-
-Empty-
-Empty-
-Empty-
Center Torso:
Fusion Engine
Fusion Engine
Fusion Engine
Gyro
Gyro
Gyro
Gyro
Fusion Engine
Fusion Engine
Fusion Engine
Jump Jet
Medium Laser
Head:
Life Support
Sensors
Cockpit
Medium Laser
Sensors
Life Support
-Empty-
-Empty-
-Empty-
-Empty-
-Empty-
-Empty-
Left Leg:
Hip
Upper Leg Actuator
Lower Leg Actuator
Foot Actuator
Jump Jet
Endo Steel
-Empty-
-Empty-
-Empty-
-Empty-
-Empty-
-Empty-
Right Leg:
Hip
Upper Leg Actuator
Lower Leg Actuator
Foot Actuator
Jump Jet
Endo Steel
-Empty-
-Empty-
-Empty-
-Empty-
-Empty-
-Empty-
| {
"pile_set_name": "Github"
} |
// 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.
#ifndef GPU_IPC_GPU_PARAM_TRAITS_H_
#define GPU_IPC_GPU_PARAM_TRAITS_H_
#include "ipc/ipc_message_utils.h"
#include "gpu/command_buffer/common/command_buffer.h"
#include "gpu/gpu_export.h"
namespace IPC {
template <>
struct GPU_EXPORT ParamTraits<gpu::CommandBuffer::State> {
typedef gpu::CommandBuffer::State param_type;
static void Write(Message* m, const param_type& p);
static bool Read(const Message* m, PickleIterator* iter, param_type* p);
static void Log(const param_type& p, std::string* l);
};
} // namespace IPC
#endif // GPU_IPC_GPU_PARAM_TRAITS_H_
| {
"pile_set_name": "Github"
} |
## [`Rx.Observable.prototype.lastOrDefault([predicate], [defaultValue], [thisArg])`](https://github.com/Reactive-Extensions/RxJS/blob/master/src/core/linq/observable/lastordefault.js)
{% if book.isPdf %}

{% else %}
{% endif %}
Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element.
#### Arguments
1. `predicate` *(`Function`)*: A predicate function to evaluate for elements in the source sequence. The callback is called with the following information:
1. the value of the element
2. the index of the element
3. the Observable object being subscribed
2. `[defaultValue]` *(`Any`)*: The default value if no such element exists. If not specified, defaults to null.
3. `[thisArg]` *(`Any`)*: Object to use as `this` when executing the predicate.
#### Returns
*(`Observable`)*: Sequence containing the last element in the observable sequence that satisfies the condition in the predicate.
#### Example
##### No Match
[](http://jsbin.com/wokaki/1/embed?js,console)
##### Without predicate
[](http://jsbin.com/cubuh/1/embed?js,console)
##### With predicate
[](http://jsbin.com/vayal/1/embed?js,console)
| {
"pile_set_name": "Github"
} |
@c GNUstep AppKit Guide
@c
@c Copyright (c) 2005-2006 Christopher Armstrong.
@c
@c Permission is granted to copy, distribute and/or modify this document
@c under the terms of the GNU Free Documentation License, Version 1.2
@c with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
@c A copy of the license is included in the section entitled "GNU
@c Free Documentation License".
@c
@c This documentation is provided on an "AS IS" BASIS, WITHOUT WARRANTY
@c OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED
@c TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
@c PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND USEFULNESS
@c OF THE DOCUMENTATION IS WITH YOU (THE LICENSEE). IN NO EVENT WILL THE COPYRIGHT
@c HOLDERS BE LIABLE FOR DAMAGES, INCLUDING ANY DIRECT, INDIRECT,
@c SPECIAL, GENERAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF
@c THE USE OR INABILITY TO USE THIS DOCUMENTATION (INCLUDING BUT NOT
@c LIMITED TO LOSS OF DATA, USE, OR PROFITS; PROCUREMENT OF SUBSTITUTE
@c GOODS AND SERVICES; OR BUSINESS INTERUPTION) HOWEVER CAUSED, EVEN
@c IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@node tableview, outlineviews, eventhandling, Top
@chapter Tableviews
@anchor{Tableviews}
@cindex tableview, definition
@cindex controls, tableviews
A tableview is a grid of rows and columns for the display of data. In the AppKit, you use the @code{NSTableView} class to put a tableview in your application.
Gorm already has a palette set up for a tableview, that you can simply drag and drop onto your application window (refer to the sections on Gorm and the Gorm manual).
More involved, however, is getting data into your tableview and responding to certain tableview specific events. Both of these are implemented using objects that respond to certain protocols, as described below.
@section Columns
@cindex tableview, columns
Instead of taking an array oriented model of a table, the @code{NSTableView} class uses a column-oriented model, where columns are used as objects of separate classes, @code{NSTableColumn}.
These can be instantiated with the @code{-initWithIdentifier:} method, where the identifier is an internal object, not displayed, used by the data source (see below) to identify what column data should be placed in. You can retrieve the table column's identifier from the @code{-identifier} method.
This column-oriented model for displaying data makes tableviews useful for information originating from a database, where columns are akin to fields, and each row represents a record in a table or query.
FIXME: How do you initialize a table's column's and it's identifiers when a nib is loaded. Do you use one of it's delegates methods to set all this stuff up?
@section Supplying Data
@cindex tableview, data source
When you first create your tableview, Gorm puts some example data into it for you. However, you will want to put in your own data. GNUstep uses a @dfn{data source} model, which means that you need to supply an object that will provide data for your table view.
Firstly, you will need to connect the @code{dataSource} outlet of a tableview in Gorm to an instantiated object of a class. Create a class that will have it's objects provide data for your tableview(s), and instantiate it so that it appears as a @dfn{top level object} in the Objects pane.
@cindex protocols, NSTableDataSource
Your object will need to implement an informal protocol to supply data to the tableview, namely the @code{NSTableDataSource} protocol (for more information on informal protocols, see the @cite{GNUstep Base Programming Manual}).
Most of the methods in this protocol are optional. The compulsory methods, however, are called quite often, so you should optimise them so that they run as fast as possible.
The @code{-numberOfRowsInTableView:} method is called to determine how many rows are to be shown in your table view. This could change from time to time, and as the data in your table view changes, you will need to inform the @code{NSTableView} object that data has changed (usually via the @code{-update} method). When it performs it's update, it will use this method to determine how many rows to draw. This method is compulsory to implement, and your will experience errors if you don't implement it.
Another compulsory method is the @code{-tableView:objectValueForTableColumn:row:}. This is used to get the data that the table view will put in it's cells. It will pass you the table column that the cell appears in, the cell's row, and the associated tableview. The method returns an object to be displayed in the relevant cell; this object is usually a string.
Note that if the data to be displayed in a tableview changes, it has no way of knowing if and when it has changed. For this reason, you need to call @code{-update} manually on the tableview to force it to redisplay. Only then will it again invoke the methods above on your data source.
If you want your tableview to be editable, you will need to implement the @code{-tableView:setObjectValue: forTableColumn:row:} method. You use this to update your internal representation of what is displayed in the table view to the user.
Both these methods supply a reference to a tableview as well, so the same object (or objects of the same class) can be used as a data source for more than one tableview (e.g. across many documents, or for many tables in a database).
You can setup your tableview to accept drop operations. It must implement @code{-tableView:writeRows:toPasteboard:}. This method is called first, and is asking you to write the data in the specified rows to the specified pasteboard. This method should return @var{YES} to authorise the drop, or @var{NO} to reject it.
More methods that can be implemented to provide information to the tableview during a drop operation include @code{-tableView:acceptDrop:row:dropOperation:} and @code{-tableView:validateDrop: proposedRow:proposedDropOperation:} methods. These are used to validate and accept drop operations, where the latter is called to validate a potential drop operation, the former just before a validated drop operation is about to take place.
If the data in your data source changes for any reason, e.g. the action of a user, you must notify the tableview. You could do this by calling @code{-reloadData} on the tableview object, which you can reference by an outlet on your application's controller class (or otherwise).
@section Delegates
@cindex tableview, delegates
@cindex protocols, NSTableViewDelegate
Tableviews support a delegate for catching certain events in the lifetime of an @code{NSTableView} object. You will need to implement the informal @code{NSTableViewDelegate} protocol. This is different from the data source - you implement a delegate if you wish to catch tableview specific events created by the user.
@section Notifications
A tableview many post notifications to indicate changes to it (that otherwise are not sent to the delegate) such as user selection changes or the reordering of columns or rows.
| {
"pile_set_name": "Github"
} |
<fontshader>
<font path="NotoSansTC-Regular.otf" w="512" h="256"/>
<effect name="default">
<pass>
</pass>
</effect>
<effect name="drop_shadow">
<pass>
</pass>
<pass>
<color r="0" g="0" b="0" a="1"/>
<pos x="1" y="1"/>
</pass>
</effect>
</fontshader>
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 0b0ae4ff46cb00648990f935f6b14f1c
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
@import "../style/typography";
@import "../style/spacing";
@import "./chip-sizes";
.Chip {
display: inline-flex;
align-items: center;
position: relative;
overflow: hidden;
padding: 0 $spacing-half;
height: $chip-size;
min-height: 1px;
border-radius: 2.5px;
line-height: $chip-size - 2px;
font: {
size: $font-size;
weight: $font-weight-normal;
};
&:after {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
opacity: 0;
content: "";
pointer-events: none;
background-color: #000;
}
&:focus {
outline: none;
&:after {
opacity: 0.16;
}
}
}
.ChipRemove {
margin-left: $spacing-half;
font-size: 85% !important;
border-radius: 50%;
}
| {
"pile_set_name": "Github"
} |
/*
* File: sound/soc/blackfin/bf5xx-ad193x.c
* Author: Barry Song <[email protected]>
*
* Created: Thur June 4 2009
* Description: Board driver for ad193x sound chip
*
* Bugs: Enter bugs at http://blackfin.uclinux.org/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see the file COPYING, or write
* to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/soc.h>
#include <sound/pcm_params.h>
#include <asm/blackfin.h>
#include <asm/cacheflush.h>
#include <asm/irq.h>
#include <asm/dma.h>
#include <asm/portmux.h>
#include "../codecs/ad193x.h"
static struct snd_soc_card bf5xx_ad193x;
static int bf5xx_ad193x_link_init(struct snd_soc_pcm_runtime *rtd)
{
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
int ret;
/* set the codec system clock for DAC and ADC */
ret = snd_soc_dai_set_sysclk(codec_dai, 0, 24576000, SND_SOC_CLOCK_IN);
if (ret < 0)
return ret;
/* set codec DAI slots, 8 channels, all channels are enabled */
ret = snd_soc_dai_set_tdm_slot(codec_dai, 0xFF, 0xFF, 8, 32);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_tdm_slot(cpu_dai, 0xFF, 0xFF, 8, 32);
if (ret < 0)
return ret;
return 0;
}
#define BF5XX_AD193X_DAIFMT (SND_SOC_DAIFMT_DSP_A | SND_SOC_DAIFMT_IB_IF | \
SND_SOC_DAIFMT_CBM_CFM)
static struct snd_soc_dai_link bf5xx_ad193x_dai[] = {
{
.name = "ad193x",
.stream_name = "AD193X",
.cpu_dai_name = "bfin-i2s.0",
.codec_dai_name ="ad193x-hifi",
.platform_name = "bfin-i2s-pcm-audio",
.codec_name = "spi0.5",
.dai_fmt = BF5XX_AD193X_DAIFMT,
.init = bf5xx_ad193x_link_init,
},
{
.name = "ad193x",
.stream_name = "AD193X",
.cpu_dai_name = "bfin-i2s.1",
.codec_dai_name ="ad193x-hifi",
.platform_name = "bfin-i2s-pcm-audio",
.codec_name = "spi0.5",
.dai_fmt = BF5XX_AD193X_DAIFMT,
.init = bf5xx_ad193x_link_init,
},
};
static struct snd_soc_card bf5xx_ad193x = {
.name = "bfin-ad193x",
.owner = THIS_MODULE,
.dai_link = &bf5xx_ad193x_dai[CONFIG_SND_BF5XX_SPORT_NUM],
.num_links = 1,
};
static struct platform_device *bfxx_ad193x_snd_device;
static int __init bf5xx_ad193x_init(void)
{
int ret;
bfxx_ad193x_snd_device = platform_device_alloc("soc-audio", -1);
if (!bfxx_ad193x_snd_device)
return -ENOMEM;
platform_set_drvdata(bfxx_ad193x_snd_device, &bf5xx_ad193x);
ret = platform_device_add(bfxx_ad193x_snd_device);
if (ret)
platform_device_put(bfxx_ad193x_snd_device);
return ret;
}
static void __exit bf5xx_ad193x_exit(void)
{
platform_device_unregister(bfxx_ad193x_snd_device);
}
module_init(bf5xx_ad193x_init);
module_exit(bf5xx_ad193x_exit);
/* Module information */
MODULE_AUTHOR("Barry Song");
MODULE_DESCRIPTION("ALSA SoC AD193X board driver");
MODULE_LICENSE("GPL");
| {
"pile_set_name": "Github"
} |
import storage.sd_salt
from storage.sd_salt import SD_CARD_HOT_SWAPPABLE
from trezor import fatfs, sdcard, ui, wire
from trezor.ui.text import Text
from apps.common.confirm import confirm, hold_to_confirm
if False:
from typing import Optional
class SdCardUnavailable(wire.ProcessError):
pass
async def _wrong_card_dialog(ctx: wire.GenericContext) -> bool:
text = Text("SD card protection", ui.ICON_WRONG)
text.bold("Wrong SD card.")
text.br_half()
if SD_CARD_HOT_SWAPPABLE:
text.normal("Please insert the", "correct SD card for", "this device.")
btn_confirm = "Retry" # type: Optional[str]
btn_cancel = "Abort"
else:
text.normal("Please unplug the", "device and insert the", "correct SD card.")
btn_confirm = None
btn_cancel = "Close"
return await confirm(ctx, text, confirm=btn_confirm, cancel=btn_cancel)
async def insert_card_dialog(ctx: wire.GenericContext) -> bool:
text = Text("SD card protection", ui.ICON_WRONG)
text.bold("SD card required.")
text.br_half()
if SD_CARD_HOT_SWAPPABLE:
text.normal("Please insert your", "SD card.")
btn_confirm = "Retry" # type: Optional[str]
btn_cancel = "Abort"
else:
text.normal("Please unplug the", "device and insert your", "SD card.")
btn_confirm = None
btn_cancel = "Close"
return await confirm(ctx, text, confirm=btn_confirm, cancel=btn_cancel)
async def format_card_dialog(ctx: wire.GenericContext) -> bool:
# Format card? yes/no
text = Text("SD card error", ui.ICON_WRONG, ui.RED)
text.bold("Unknown filesystem.")
text.br_half()
text.normal("Use a different card or")
text.normal("format the SD card to")
text.normal("the FAT32 filesystem.")
if not await confirm(ctx, text, confirm="Format", cancel="Cancel"):
return False
# Confirm formatting
text = Text("Format SD card", ui.ICON_WIPE, ui.RED)
text.normal("Do you really want to", "format the SD card?")
text.br_half()
text.bold("All data on the SD card", "will be lost.")
return await hold_to_confirm(ctx, text, confirm="Format SD card")
async def sd_problem_dialog(ctx: wire.GenericContext) -> bool:
text = Text("SD card problem", ui.ICON_WRONG, ui.RED)
text.normal("There was a problem", "accessing the SD card.")
return await confirm(ctx, text, confirm="Retry", cancel="Abort")
async def ensure_sdcard(
ctx: wire.GenericContext, ensure_filesystem: bool = True
) -> None:
"""Ensure a SD card is ready for use.
This function runs the UI flow needed to ask the user to insert a SD card if there
isn't one.
If `ensure_filesystem` is True (the default), it also tries to mount the SD card
filesystem, and allows the user to format the card if a filesystem cannot be
mounted.
"""
while not sdcard.is_present():
if not await insert_card_dialog(ctx):
raise SdCardUnavailable("SD card required.")
if not ensure_filesystem:
return
while True:
try:
try:
with sdcard.filesystem(mounted=False):
fatfs.mount()
except fatfs.NoFilesystem:
# card not formatted. proceed out of the except clause
pass
else:
# no error when mounting
return
if not await format_card_dialog(ctx):
raise SdCardUnavailable("SD card not formatted.")
# Proceed to formatting. Failure is caught by the outside OSError handler
with sdcard.filesystem(mounted=False):
fatfs.mkfs()
fatfs.mount()
fatfs.setlabel("TREZOR")
# format and mount succeeded
return
except OSError:
# formatting failed, or generic I/O error (SD card power-on failed)
if not await sd_problem_dialog(ctx):
raise SdCardUnavailable("Error accessing SD card.")
async def request_sd_salt(
ctx: wire.GenericContext = wire.DUMMY_CONTEXT,
) -> Optional[bytearray]:
if not storage.sd_salt.is_enabled():
return None
while True:
await ensure_sdcard(ctx, ensure_filesystem=False)
try:
return storage.sd_salt.load_sd_salt()
except (storage.sd_salt.WrongSdCard, fatfs.NoFilesystem):
if not await _wrong_card_dialog(ctx):
raise SdCardUnavailable("Wrong SD card.")
except OSError:
# Generic problem with loading the SD salt (hardware problem, or we could
# not read the file, or there is a staged salt which cannot be committed).
# In either case, there is no good way to recover. If the user clicks Retry,
# we will try again.
if not await sd_problem_dialog(ctx):
raise SdCardUnavailable("Error accessing SD card.")
| {
"pile_set_name": "Github"
} |
/* tslint:disable */
/* eslint-disable */
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL query operation: Channels
// ====================================================
export interface Channels_guild_channels_CategoryChannel {
__typename: "CategoryChannel" | "VoiceChannel";
name: string;
id: string;
}
export interface Channels_guild_channels_TextChannel_parent {
__typename: "CategoryChannel";
name: string;
}
export interface Channels_guild_channels_TextChannel {
__typename: "TextChannel";
name: string;
id: string;
parent: Channels_guild_channels_TextChannel_parent | null;
}
export type Channels_guild_channels = Channels_guild_channels_CategoryChannel | Channels_guild_channels_TextChannel;
export interface Channels_guild {
__typename: "Guild";
channels: Channels_guild_channels[];
}
export interface Channels {
guild: Channels_guild;
}
export interface ChannelsVariables {
guild: string;
}
| {
"pile_set_name": "Github"
} |
"", "\n\n\t003C/tbody\u003E\n\u003C/tabl\n\n\u003C/div\u003E\n\n\n\n\n\u003Cdiv class=\u003E\n\n\u003C/div\u003E\n"
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 6e7f468aa7fc2964a8e61e57c48cadba
folderAsset: yes
timeCreated: 1436222976
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import torch
class Stage9(torch.nn.Module):
def __init__(self):
super(Stage9, self).__init__()
self.layer5 = torch.nn.LSTM(2048, 1024)
self.layer8 = torch.nn.Dropout(p=0.2)
def forward(self, input3, input2, input0):
out0 = input0.clone()
out1 = input3.clone()
out2 = input2.clone()
out3 = None
out4 = torch.cat([out0, out1], 2)
out5 = self.layer5(out4, out3)
out6 = out5[0]
out6 = out6 + out2
out8 = self.layer8(out6)
out9 = torch.cat([out8, out1], 2)
return (out6, out9, out1)
def _initialize_weights(self):
for m in self.modules():
if isinstance(m, torch.nn.Conv2d):
torch.nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
if m.bias is not None:
torch.nn.init.constant_(m.bias, 0)
elif isinstance(m, torch.nn.BatchNorm2d):
torch.nn.init.constant_(m.weight, 1)
torch.nn.init.constant_(m.bias, 0)
elif isinstance(m, torch.nn.Linear):
torch.nn.init.normal_(m.weight, 0, 0.01)
torch.nn.init.constant_(m.bias, 0)
| {
"pile_set_name": "Github"
} |
platform OpenBSD
hostname openbsd.my.domain
uptime 1:14, 1 user, load averages: 0.44, 0.20, 0.16
kernel 201111
release 5.0
CPU_ARCH 32-bit
OS_ARCH 32-bit
virt No virtualization detected
rss 5541888
raid_controller No RAID controller detected
| {
"pile_set_name": "Github"
} |
function a = idct2(arg1,mrows,ncols)
%IDCT2 Compute 2-D inverse discrete cosine transform.
% B = IDCT2(A) returns the two-dimensional inverse discrete
% cosine transform of A.
%
% B = IDCT2(A,[M N]) or B = IDCT2(A,M,N) pads A with zeros (or
% truncates A) to create a matrix of size M-by-N before
% transforming.
%
% For any A, IDCT2(DCT2(A)) equals A to within roundoff error.
%
% The discrete cosine transform is often used for image
% compression applications.
%
% Class Support
% -------------
% The input matrix A can be of class double or of any
% numeric class. The output matrix B is of class double.
%
% See also DCT2, DCTMTX, FFT2, IFFT2.
% Copyright 1993-2003 The MathWorks, Inc.
% $Revision: 5.17.4.1 $ $Date: 2003/01/26 05:55:39 $
% References:
% 1) A. K. Jain, "Fundamentals of Digital Image
% Processing", pp. 150-153.
% 2) Wallace, "The JPEG Still Picture Compression Standard",
% Communications of the ACM, April 1991.
% checknargin(1,3,nargin,mfilename);
[m, n] = size(arg1);
% Basic algorithm.
if (nargin == 1),
if (m > 1) & (n > 1),
a = idct(idct(arg1).').';
return;
else
mrows = m;
ncols = n;
end
end
% Padding for vector input.
b = arg1;
if nargin==2,
ncols = mrows(2);
mrows = mrows(1);
end
mpad = mrows; npad = ncols;
if m == 1 & mpad > m, b(2, 1) = 0; m = 2; end
if n == 1 & npad > n, b(1, 2) = 0; n = 2; end
if m == 1, mpad = npad; npad = 1; end % For row vector.
% Transform.
a = idct(b, mpad);
if m > 1 & n > 1, a = idct(a.', npad).'; end
| {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using UnityEngine;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
namespace ImGuiNET.Unity
{
class SpriteInfo
{
public Texture texture;
public Vector2 size;
public Vector2 uv0, uv1;
}
class TextureManager
{
Texture2D _atlasTex;
int _currentTextureId;
readonly Dictionary<int, Texture> _textures = new Dictionary<int, Texture>();
readonly Dictionary<Texture, int> _textureIds = new Dictionary<Texture, int>();
readonly Dictionary<Sprite, SpriteInfo> _spriteData = new Dictionary<Sprite, SpriteInfo>();
readonly HashSet<IntPtr> _allocatedGlyphRangeArrays = new HashSet<IntPtr>(IntPtrEqualityComparer.Instance);
public void PrepareFrame(ImGuiIOPtr io)
{
_currentTextureId = 0;
_textures.Clear();
_textureIds.Clear();
int id = RegisterTexture(_atlasTex);
io.Fonts.SetTexID((IntPtr)id);
}
int RegisterTexture(Texture texture)
{
_textures[++_currentTextureId] = texture;
_textureIds[texture] = _currentTextureId;
return _currentTextureId;
}
public Texture GetTexture(int id)
{
_textures.TryGetValue(id, out Texture texture);
return texture;
}
public int GetTextureId(Texture texture)
{
return _textureIds.TryGetValue(texture, out int id)
? id
: RegisterTexture(texture);
}
public SpriteInfo GetSpriteInfo(Sprite sprite)
{
if (!_spriteData.TryGetValue(sprite, out SpriteInfo sprInfo))
{
Vector2[] uvs = sprite.uv; // allocates
_spriteData[sprite] = sprInfo = new SpriteInfo
{
texture = sprite.texture,
size = sprite.rect.size,
uv0 = new Vector2(uvs[0].x, 1f - uvs[0].y),
uv1 = new Vector2(uvs[1].x, 1f - uvs[1].y),
};
}
return sprInfo;
}
unsafe IntPtr AllocateGlyphRangeArray(in FontConfig fontConfig)
{
var values = fontConfig.BuildRanges();
if (values.Count == 0)
return IntPtr.Zero;
int byteCount = sizeof(ushort) * (values.Count + 1); // terminating zero
var ranges = (ushort*)Util.Allocate(byteCount);
_allocatedGlyphRangeArrays.Add((IntPtr)ranges);
for (var i = 0; i < values.Count; ++i)
ranges[i] = values[i];
ranges[values.Count] = 0;
return (IntPtr)ranges;
}
unsafe void FreeGlyphRangeArrays()
{
foreach (var range in _allocatedGlyphRangeArrays)
Util.Free((byte*)range);
_allocatedGlyphRangeArrays.Clear();
}
public void BuildFontAtlas(ImGuiIOPtr io, in FontAtlasConfigAsset settings)
{
if (io.Fonts.IsBuilt())
DestroyFontAtlas(io);
// don't add cursors if not drawing them
if (!io.MouseDrawCursor)
io.Fonts.Flags |= ImFontAtlasFlags.NoMouseCursors;
// no font config asset: use defaults
if (settings == null)
{
io.Fonts.AddFontDefault();
io.Fonts.Build();
return;
}
// add fonts from config asset
foreach (var fontDefinition in settings.Fonts)
{
var fontPath = System.IO.Path.Combine(Application.streamingAssetsPath, fontDefinition.FontPath);
if (!System.IO.File.Exists(fontPath))
{
Debug.Log($"Font file not found: {fontPath}");
continue;
}
var fontConfig = new ImFontConfig();
var fontConfigPtr = new ImFontConfigPtr(ref fontConfig);
fontDefinition.Config.ApplyTo(fontConfigPtr);
fontConfigPtr.GlyphRanges = AllocateGlyphRangeArray(fontDefinition.Config);
io.Fonts.AddFontFromFileTTF(fontPath, fontDefinition.Config.SizeInPixels, fontConfigPtr);
}
if (io.Fonts.Fonts.Size == 0)
io.Fonts.AddFontDefault();
switch (settings.Rasterizer)
{
case FontRasterizerType.StbTrueType:
io.Fonts.Build();
break;
#if IMGUI_FEATURE_FREETYPE
case FontRasterizerType.FreeType:
ImFreetype.BuildFontAtlas(io.Fonts, (ImFreetype.RasterizerFlags)settings.RasterizerFlags);
break;
#endif
default:
Debug.LogWarning($"{settings.Rasterizer:G} rasterizer not available, using {default(FontRasterizerType):G}. Check if feature is enabled (PluginFeatures.cs).");
io.Fonts.Build();
break;
}
}
public unsafe void DestroyFontAtlas(ImGuiIOPtr io)
{
FreeGlyphRangeArrays();
io.Fonts.Clear(); // previous FontDefault reference no longer valid
io.NativePtr->FontDefault = default; // NULL uses Fonts[0]
}
public void Initialize(ImGuiIOPtr io)
{
// load and register font atlas
_atlasTex = CreateAtlasTexture(io.Fonts);
}
public void Shutdown()
{
_currentTextureId = 0;
_textures.Clear();
_textureIds.Clear();
_spriteData.Clear();
if (_atlasTex != null) { GameObject.Destroy(_atlasTex); _atlasTex = null; }
}
unsafe Texture2D CreateAtlasTexture(ImFontAtlasPtr atlas)
{
atlas.GetTexDataAsRGBA32(out byte* pixels, out int width, out int height, out int bytesPerPixel);
var atlasTexture = new Texture2D(width, height, TextureFormat.RGBA32, false, false) { filterMode = FilterMode.Point };
NativeArray<byte> srcData = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(
(void*)pixels, width * height * bytesPerPixel, Allocator.None);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref srcData, AtomicSafetyHandle.GetTempMemoryHandle());
#endif
// invert y while copying the atlas texture
NativeArray<byte> dstData = atlasTexture.GetRawTextureData<byte>();
int stride = width * bytesPerPixel;
for (int y = 0; y < height; ++y)
NativeArray<byte>.Copy(srcData, y * stride, dstData, (height - y - 1) * stride, stride);
atlasTexture.Apply();
return atlasTexture;
}
}
}
| {
"pile_set_name": "Github"
} |
/**
* Copyright 2016 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE
*
* @flow
*/
import { GraphQLSchema } from "graphql";
import { queryType } from "./query";
export default new GraphQLSchema({
query: queryType
});
| {
"pile_set_name": "Github"
} |
This is the Debian GNU/Linux's prepackaged version of the
Dynamic Library Tracer ``ltrace''.
It was downloaded from http://www.ltrace.org/
Copyrights
----------
Copyright (C) 1997-2009 Juan Cespedes <[email protected]>
ARMLinux port: Copyright (C) 1998 Pat Beirne <[email protected]>
m68k port: Copyright (C) 1998 Roman Hodek <[email protected]>
Misc fixes: Copyright (C) 1999 Morten Eriksen <[email protected]>
s390 port: Copyright (C) 2001 IBM Poughkeepsie, IBM Cororation <[email protected]>
ELF hacking: Copyright (C) 1999 Silvio Cesare <[email protected]>
PowerPC port: Copyright (C) 2001-2002 Anton Blanchard <[email protected]>
SPARC port: Copyright (C) 1999 Jakub Jelinek <[email protected]>
C++ demangle: Copyright 1989-1997 Free Software Foundation, Inc.
License
-------
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
A copy of the GNU General Public License is available as
`/usr/share/common-licenses/GPL' in the Debian GNU/Linux distribution
or on the World Wide Web at `http://www.gnu.org/copyleft/gpl.html'.
You can also obtain it by writing to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 62a7573e463b4f68b578fcba3a94110c
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<ZopeData>
<record id="1" aka="AAAAAAAAAAE=">
<pickle>
<global name="ERP5 Form" module="erp5.portal_type"/>
</pickle>
<pickle>
<dictionary>
<item>
<key> <string>_bind_names</string> </key>
<value>
<object>
<klass>
<global name="NameAssignments" module="Shared.DC.Scripts.Bindings"/>
</klass>
<tuple/>
<state>
<dictionary>
<item>
<key> <string>_asgns</string> </key>
<value>
<dictionary/>
</value>
</item>
</dictionary>
</state>
</object>
</value>
</item>
<item>
<key> <string>_objects</string> </key>
<value>
<tuple/>
</value>
</item>
<item>
<key> <string>action</string> </key>
<value> <string>Base_doSelect</string> </value>
</item>
<item>
<key> <string>encoding</string> </key>
<value> <string>UTF-8</string> </value>
</item>
<item>
<key> <string>enctype</string> </key>
<value> <string></string> </value>
</item>
<item>
<key> <string>group_list</string> </key>
<value>
<list>
<string>bottom</string>
<string>hidden</string>
</list>
</value>
</item>
<item>
<key> <string>groups</string> </key>
<value>
<dictionary>
<item>
<key> <string>bottom</string> </key>
<value>
<list>
<string>listbox</string>
</list>
</value>
</item>
<item>
<key> <string>hidden</string> </key>
<value>
<list>
<string>listbox_preferred_gap_id</string>
<string>listbox_debit</string>
<string>listbox_credit</string>
<string>listbox_credit_balance</string>
<string>listbox_debit_balance</string>
</list>
</value>
</item>
</dictionary>
</value>
</item>
<item>
<key> <string>id</string> </key>
<value> <string>AccountModule_viewAccountList</string> </value>
</item>
<item>
<key> <string>method</string> </key>
<value> <string>POST</string> </value>
</item>
<item>
<key> <string>name</string> </key>
<value> <string>AccountModule_viewAccountList</string> </value>
</item>
<item>
<key> <string>pt</string> </key>
<value> <string>form_list</string> </value>
</item>
<item>
<key> <string>row_length</string> </key>
<value> <int>4</int> </value>
</item>
<item>
<key> <string>stored_encoding</string> </key>
<value> <string>UTF-8</string> </value>
</item>
<item>
<key> <string>title</string> </key>
<value> <string>Accounts</string> </value>
</item>
<item>
<key> <string>unicode_mode</string> </key>
<value> <int>0</int> </value>
</item>
<item>
<key> <string>update_action</string> </key>
<value> <string></string> </value>
</item>
</dictionary>
</pickle>
</record>
</ZopeData>
| {
"pile_set_name": "Github"
} |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Internal;
using Xunit;
namespace Microsoft.AspNetCore.SignalR.Common.Tests.Internal.Protocol
{
using Microsoft.AspNetCore.SignalR.Protocol;
using static HubMessageHelpers;
public class MessagePackHubProtocolTests
{
private static readonly IDictionary<string, string> TestHeaders = new Dictionary<string, string>
{
{ "Foo", "Bar" },
{ "KeyWith\nNew\r\nLines", "Still Works" },
{ "ValueWithNewLines", "Also\nWorks\r\nFine" },
};
private static readonly MessagePackHubProtocol _hubProtocol
= new MessagePackHubProtocol();
public enum TestEnum
{
Zero = 0,
One
}
// Test Data for Parse/WriteMessages:
// * Name: A string name that is used when reporting the test (it's the ToString value for ProtocolTestData)
// * Message: The HubMessage that is either expected (in Parse) or used as input (in Write)
// * Binary: Base64-encoded binary "baseline" to sanity-check MessagePack-CSharp behavior
//
// When changing the tests/message pack parsing if you get test failures look at the base64 encoding and
// use a tool like https://sugendran.github.io/msgpack-visualizer/ to verify that the MsgPack is correct and then just replace the Base64 value.
public static IEnumerable<object[]> TestDataNames
{
get
{
foreach (var k in TestData.Keys)
{
yield return new object[] { k };
}
}
}
public static IDictionary<string, ProtocolTestData> TestData => new[]
{
// Invocation messages
new ProtocolTestData(
name: "InvocationWithNoHeadersAndNoArgs",
message: new InvocationMessage("xyz", "method", Array.Empty<object>()),
binary: "lQGAo3h5eqZtZXRob2SQ"),
new ProtocolTestData(
name: "InvocationWithNoHeadersNoIdAndNoArgs",
message: new InvocationMessage("method", Array.Empty<object>()),
binary: "lQGAwKZtZXRob2SQ"),
new ProtocolTestData(
name: "InvocationWithNoHeadersNoIdAndSingleNullArg",
message: new InvocationMessage("method", new object[] { null }),
binary: "lQGAwKZtZXRob2SRwA=="),
new ProtocolTestData(
name: "InvocationWithNoHeadersNoIdAndSingleIntArg",
message: new InvocationMessage("method", new object[] { 42 }),
binary: "lQGAwKZtZXRob2SRKg=="),
new ProtocolTestData(
name: "InvocationWithNoHeadersNoIdIntAndStringArgs",
message: new InvocationMessage("method", new object[] { 42, "string" }),
binary: "lQGAwKZtZXRob2SSKqZzdHJpbmc="),
new ProtocolTestData(
name: "InvocationWithNoHeadersNoIdIntAndEnumArgs",
message: new InvocationMessage("method", new object[] { 42, TestEnum.One }),
binary: "lQGAwKZtZXRob2SSKqNPbmU="),
new ProtocolTestData(
name: "InvocationWithNoHeadersNoIdAndCustomObjectArg",
message: new InvocationMessage("method", new object[] { 42, "string", new CustomObject() }),
binary: "lQGAwKZtZXRob2STKqZzdHJpbmeGqlN0cmluZ1Byb3CoU2lnbmFsUiGqRG91YmxlUHJvcMtAGSH7VELPEqdJbnRQcm9wKqxEYXRlVGltZVByb3DW/1jsHICoTnVsbFByb3DAq0J5dGVBcnJQcm9wxAMBAgM="),
new ProtocolTestData(
name: "InvocationWithNoHeadersNoIdAndArrayOfCustomObjectArgs",
message: new InvocationMessage("method", new object[] { new CustomObject(), new CustomObject() }),
binary: "lQGAwKZtZXRob2SShqpTdHJpbmdQcm9wqFNpZ25hbFIhqkRvdWJsZVByb3DLQBkh+1RCzxKnSW50UHJvcCqsRGF0ZVRpbWVQcm9w1v9Y7ByAqE51bGxQcm9wwKtCeXRlQXJyUHJvcMQDAQIDhqpTdHJpbmdQcm9wqFNpZ25hbFIhqkRvdWJsZVByb3DLQBkh+1RCzxKnSW50UHJvcCqsRGF0ZVRpbWVQcm9w1v9Y7ByAqE51bGxQcm9wwKtCeXRlQXJyUHJvcMQDAQID"),
new ProtocolTestData(
name: "InvocationWithHeadersNoIdAndArrayOfCustomObjectArgs",
message: AddHeaders(TestHeaders, new InvocationMessage("method", new object[] { new CustomObject(), new CustomObject() })),
binary: "lQGDo0Zvb6NCYXKyS2V5V2l0aApOZXcNCkxpbmVzq1N0aWxsIFdvcmtzsVZhbHVlV2l0aE5ld0xpbmVzsEFsc28KV29ya3MNCkZpbmXApm1ldGhvZJKGqlN0cmluZ1Byb3CoU2lnbmFsUiGqRG91YmxlUHJvcMtAGSH7VELPEqdJbnRQcm9wKqxEYXRlVGltZVByb3DW/1jsHICoTnVsbFByb3DAq0J5dGVBcnJQcm9wxAMBAgOGqlN0cmluZ1Byb3CoU2lnbmFsUiGqRG91YmxlUHJvcMtAGSH7VELPEqdJbnRQcm9wKqxEYXRlVGltZVByb3DW/1jsHICoTnVsbFByb3DAq0J5dGVBcnJQcm9wxAMBAgM="),
new ProtocolTestData(
name: "InvocationWithStreamPlaceholderObject",
message: new InvocationMessage(null, "Target", new object[] { new StreamPlaceholder("__test_id__")}),
binary: "lQGAwKZUYXJnZXSRgahTdHJlYW1JZKtfX3Rlc3RfaWRfXw=="
),
// StreamItem Messages
new ProtocolTestData(
name: "StreamItemWithNoHeadersAndNullItem",
message: new StreamItemMessage("xyz", item: null),
binary: "lAKAo3h5esA="),
new ProtocolTestData(
name: "StreamItemWithNoHeadersAndIntItem",
message: new StreamItemMessage("xyz", item: 42),
binary: "lAKAo3h5eio="),
new ProtocolTestData(
name: "StreamItemWithNoHeadersAndFloatItem",
message: new StreamItemMessage("xyz", item: 42.0f),
binary: "lAKAo3h5espCKAAA"),
new ProtocolTestData(
name: "StreamItemWithNoHeadersAndStringItem",
message: new StreamItemMessage("xyz", item: "string"),
binary: "lAKAo3h5eqZzdHJpbmc="),
new ProtocolTestData(
name: "StreamItemWithNoHeadersAndBoolItem",
message: new StreamItemMessage("xyz", item: true),
binary: "lAKAo3h5esM="),
new ProtocolTestData(
name: "StreamItemWithNoHeadersAndEnumItem",
message: new StreamItemMessage("xyz", item: TestEnum.One),
binary: "lAKAo3h5eqNPbmU="),
new ProtocolTestData(
name: "StreamItemWithNoHeadersAndCustomObjectItem",
message: new StreamItemMessage("xyz", item: new CustomObject()),
binary: "lAKAo3h5eoaqU3RyaW5nUHJvcKhTaWduYWxSIapEb3VibGVQcm9wy0AZIftUQs8Sp0ludFByb3AqrERhdGVUaW1lUHJvcNb/WOwcgKhOdWxsUHJvcMCrQnl0ZUFyclByb3DEAwECAw=="),
new ProtocolTestData(
name: "StreamItemWithNoHeadersAndCustomObjectArrayItem",
message: new StreamItemMessage("xyz", item: new[] { new CustomObject(), new CustomObject() }),
binary: "lAKAo3h5epKGqlN0cmluZ1Byb3CoU2lnbmFsUiGqRG91YmxlUHJvcMtAGSH7VELPEqdJbnRQcm9wKqxEYXRlVGltZVByb3DW/1jsHICoTnVsbFByb3DAq0J5dGVBcnJQcm9wxAMBAgOGqlN0cmluZ1Byb3CoU2lnbmFsUiGqRG91YmxlUHJvcMtAGSH7VELPEqdJbnRQcm9wKqxEYXRlVGltZVByb3DW/1jsHICoTnVsbFByb3DAq0J5dGVBcnJQcm9wxAMBAgM="),
new ProtocolTestData(
name: "StreamItemWithHeadersAndCustomObjectArrayItem",
message: AddHeaders(TestHeaders, new StreamItemMessage("xyz", item: new[] { new CustomObject(), new CustomObject() })),
binary: "lAKDo0Zvb6NCYXKyS2V5V2l0aApOZXcNCkxpbmVzq1N0aWxsIFdvcmtzsVZhbHVlV2l0aE5ld0xpbmVzsEFsc28KV29ya3MNCkZpbmWjeHl6koaqU3RyaW5nUHJvcKhTaWduYWxSIapEb3VibGVQcm9wy0AZIftUQs8Sp0ludFByb3AqrERhdGVUaW1lUHJvcNb/WOwcgKhOdWxsUHJvcMCrQnl0ZUFyclByb3DEAwECA4aqU3RyaW5nUHJvcKhTaWduYWxSIapEb3VibGVQcm9wy0AZIftUQs8Sp0ludFByb3AqrERhdGVUaW1lUHJvcNb/WOwcgKhOdWxsUHJvcMCrQnl0ZUFyclByb3DEAwECAw=="),
// Completion Messages
new ProtocolTestData(
name: "CompletionWithNoHeadersAndError",
message: CompletionMessage.WithError("xyz", error: "Error not found!"),
binary: "lQOAo3h5egGwRXJyb3Igbm90IGZvdW5kIQ=="),
new ProtocolTestData(
name: "CompletionWithHeadersAndError",
message: AddHeaders(TestHeaders, CompletionMessage.WithError("xyz", error: "Error not found!")),
binary: "lQODo0Zvb6NCYXKyS2V5V2l0aApOZXcNCkxpbmVzq1N0aWxsIFdvcmtzsVZhbHVlV2l0aE5ld0xpbmVzsEFsc28KV29ya3MNCkZpbmWjeHl6AbBFcnJvciBub3QgZm91bmQh"),
new ProtocolTestData(
name: "CompletionWithNoHeadersAndNoResult",
message: CompletionMessage.Empty("xyz"),
binary: "lAOAo3h5egI="),
new ProtocolTestData(
name: "CompletionWithHeadersAndNoResult",
message: AddHeaders(TestHeaders, CompletionMessage.Empty("xyz")),
binary: "lAODo0Zvb6NCYXKyS2V5V2l0aApOZXcNCkxpbmVzq1N0aWxsIFdvcmtzsVZhbHVlV2l0aE5ld0xpbmVzsEFsc28KV29ya3MNCkZpbmWjeHl6Ag=="),
new ProtocolTestData(
name: "CompletionWithNoHeadersAndNullResult",
message: CompletionMessage.WithResult("xyz", payload: null),
binary: "lQOAo3h5egPA"),
new ProtocolTestData(
name: "CompletionWithNoHeadersAndIntResult",
message: CompletionMessage.WithResult("xyz", payload: 42),
binary: "lQOAo3h5egMq"),
new ProtocolTestData(
name: "CompletionWithNoHeadersAndEnumResult",
message: CompletionMessage.WithResult("xyz", payload: TestEnum.One),
binary: "lQOAo3h5egOjT25l"),
new ProtocolTestData(
name: "CompletionWithNoHeadersAndFloatResult",
message: CompletionMessage.WithResult("xyz", payload: 42.0f),
binary: "lQOAo3h5egPKQigAAA=="),
new ProtocolTestData(
name: "CompletionWithNoHeadersAndStringResult",
message: CompletionMessage.WithResult("xyz", payload: "string"),
binary: "lQOAo3h5egOmc3RyaW5n"),
new ProtocolTestData(
name: "CompletionWithNoHeadersAndBooleanResult",
message: CompletionMessage.WithResult("xyz", payload: true),
binary: "lQOAo3h5egPD"),
new ProtocolTestData(
name: "CompletionWithNoHeadersAndCustomObjectResult",
message: CompletionMessage.WithResult("xyz", payload: new CustomObject()),
binary: "lQOAo3h5egOGqlN0cmluZ1Byb3CoU2lnbmFsUiGqRG91YmxlUHJvcMtAGSH7VELPEqdJbnRQcm9wKqxEYXRlVGltZVByb3DW/1jsHICoTnVsbFByb3DAq0J5dGVBcnJQcm9wxAMBAgM="),
new ProtocolTestData(
name: "CompletionWithNoHeadersAndCustomObjectArrayResult",
message: CompletionMessage.WithResult("xyz", payload: new[] { new CustomObject(), new CustomObject() }),
binary: "lQOAo3h5egOShqpTdHJpbmdQcm9wqFNpZ25hbFIhqkRvdWJsZVByb3DLQBkh+1RCzxKnSW50UHJvcCqsRGF0ZVRpbWVQcm9w1v9Y7ByAqE51bGxQcm9wwKtCeXRlQXJyUHJvcMQDAQIDhqpTdHJpbmdQcm9wqFNpZ25hbFIhqkRvdWJsZVByb3DLQBkh+1RCzxKnSW50UHJvcCqsRGF0ZVRpbWVQcm9w1v9Y7ByAqE51bGxQcm9wwKtCeXRlQXJyUHJvcMQDAQID"),
new ProtocolTestData(
name: "CompletionWithHeadersAndCustomObjectArrayResult",
message: AddHeaders(TestHeaders, CompletionMessage.WithResult("xyz", payload: new[] { new CustomObject(), new CustomObject() })),
binary: "lQODo0Zvb6NCYXKyS2V5V2l0aApOZXcNCkxpbmVzq1N0aWxsIFdvcmtzsVZhbHVlV2l0aE5ld0xpbmVzsEFsc28KV29ya3MNCkZpbmWjeHl6A5KGqlN0cmluZ1Byb3CoU2lnbmFsUiGqRG91YmxlUHJvcMtAGSH7VELPEqdJbnRQcm9wKqxEYXRlVGltZVByb3DW/1jsHICoTnVsbFByb3DAq0J5dGVBcnJQcm9wxAMBAgOGqlN0cmluZ1Byb3CoU2lnbmFsUiGqRG91YmxlUHJvcMtAGSH7VELPEqdJbnRQcm9wKqxEYXRlVGltZVByb3DW/1jsHICoTnVsbFByb3DAq0J5dGVBcnJQcm9wxAMBAgM="),
// StreamInvocation Messages
new ProtocolTestData(
name: "StreamInvocationWithNoHeadersAndNoArgs",
message: new StreamInvocationMessage("xyz", "method", Array.Empty<object>()),
binary: "lQSAo3h5eqZtZXRob2SQ"),
new ProtocolTestData(
name: "StreamInvocationWithNoHeadersAndNullArg",
message: new StreamInvocationMessage("xyz", "method", new object[] { null }),
binary: "lQSAo3h5eqZtZXRob2SRwA=="),
new ProtocolTestData(
name: "StreamInvocationWithNoHeadersAndIntArg",
message: new StreamInvocationMessage("xyz", "method", new object[] { 42 }),
binary: "lQSAo3h5eqZtZXRob2SRKg=="),
new ProtocolTestData(
name: "StreamInvocationWithNoHeadersAndEnumArg",
message: new StreamInvocationMessage("xyz", "method", new object[] { TestEnum.One }),
binary: "lQSAo3h5eqZtZXRob2SRo09uZQ=="),
new ProtocolTestData(
name: "StreamInvocationWithNoHeadersAndIntAndStringArgs",
message: new StreamInvocationMessage("xyz", "method", new object[] { 42, "string" }),
binary: "lQSAo3h5eqZtZXRob2SSKqZzdHJpbmc="),
new ProtocolTestData(
name: "StreamInvocationWithNoHeadersAndIntStringAndCustomObjectArgs",
message: new StreamInvocationMessage("xyz", "method", new object[] { 42, "string", new CustomObject() }),
binary: "lQSAo3h5eqZtZXRob2STKqZzdHJpbmeGqlN0cmluZ1Byb3CoU2lnbmFsUiGqRG91YmxlUHJvcMtAGSH7VELPEqdJbnRQcm9wKqxEYXRlVGltZVByb3DW/1jsHICoTnVsbFByb3DAq0J5dGVBcnJQcm9wxAMBAgM="),
new ProtocolTestData(
name: "StreamInvocationWithNoHeadersAndCustomObjectArrayArg",
message: new StreamInvocationMessage("xyz", "method", new object[] { new CustomObject(), new CustomObject() }),
binary: "lQSAo3h5eqZtZXRob2SShqpTdHJpbmdQcm9wqFNpZ25hbFIhqkRvdWJsZVByb3DLQBkh+1RCzxKnSW50UHJvcCqsRGF0ZVRpbWVQcm9w1v9Y7ByAqE51bGxQcm9wwKtCeXRlQXJyUHJvcMQDAQIDhqpTdHJpbmdQcm9wqFNpZ25hbFIhqkRvdWJsZVByb3DLQBkh+1RCzxKnSW50UHJvcCqsRGF0ZVRpbWVQcm9w1v9Y7ByAqE51bGxQcm9wwKtCeXRlQXJyUHJvcMQDAQID"),
new ProtocolTestData(
name: "StreamInvocationWithHeadersAndCustomObjectArrayArg",
message: AddHeaders(TestHeaders, new StreamInvocationMessage("xyz", "method", new object[] { new CustomObject(), new CustomObject() })),
binary: "lQSDo0Zvb6NCYXKyS2V5V2l0aApOZXcNCkxpbmVzq1N0aWxsIFdvcmtzsVZhbHVlV2l0aE5ld0xpbmVzsEFsc28KV29ya3MNCkZpbmWjeHl6pm1ldGhvZJKGqlN0cmluZ1Byb3CoU2lnbmFsUiGqRG91YmxlUHJvcMtAGSH7VELPEqdJbnRQcm9wKqxEYXRlVGltZVByb3DW/1jsHICoTnVsbFByb3DAq0J5dGVBcnJQcm9wxAMBAgOGqlN0cmluZ1Byb3CoU2lnbmFsUiGqRG91YmxlUHJvcMtAGSH7VELPEqdJbnRQcm9wKqxEYXRlVGltZVByb3DW/1jsHICoTnVsbFByb3DAq0J5dGVBcnJQcm9wxAMBAgM="),
// CancelInvocation Messages
new ProtocolTestData(
name: "CancelInvocationWithNoHeaders",
message: new CancelInvocationMessage("xyz"),
binary: "kwWAo3h5eg=="),
new ProtocolTestData(
name: "CancelInvocationWithHeaders",
message: AddHeaders(TestHeaders, new CancelInvocationMessage("xyz")),
binary: "kwWDo0Zvb6NCYXKyS2V5V2l0aApOZXcNCkxpbmVzq1N0aWxsIFdvcmtzsVZhbHVlV2l0aE5ld0xpbmVzsEFsc28KV29ya3MNCkZpbmWjeHl6"),
// StreamComplete Messages
new ProtocolTestData(
name: "StreamComplete",
message: new StreamCompleteMessage("xyz"),
binary: "kwijeHl6wA=="),
new ProtocolTestData(
name: "StreamCompleteWithError",
message: new StreamCompleteMessage("xyz", "zoinks"),
binary: "kwijeHl6pnpvaW5rcw=="),
// Ping Messages
new ProtocolTestData(
name: "Ping",
message: PingMessage.Instance,
binary: "kQY="),
}.ToDictionary(t => t.Name);
[Theory]
[MemberData(nameof(TestDataNames))]
public void ParseMessages(string testDataName)
{
var testData = TestData[testDataName];
// Verify that the input binary string decodes to the expected MsgPack primitives
var bytes = Convert.FromBase64String(testData.Binary);
// Parse the input fully now.
bytes = Frame(bytes);
var data = new ReadOnlySequence<byte>(bytes);
Assert.True(_hubProtocol.TryParseMessage(ref data, new TestBinder(testData.Message), out var message));
Assert.NotNull(message);
Assert.Equal(testData.Message, message, TestHubMessageEqualityComparer.Instance);
}
[Fact]
public void ParseMessageWithExtraData()
{
var expectedMessage = new InvocationMessage("xyz", "method", Array.Empty<object>());
// Verify that the input binary string decodes to the expected MsgPack primitives
var bytes = new byte[] { ArrayBytes(8),
1,
0x80,
StringBytes(3), (byte)'x', (byte)'y', (byte)'z',
StringBytes(6), (byte)'m', (byte)'e', (byte)'t', (byte)'h', (byte)'o', (byte)'d',
ArrayBytes(0),
0xc3,
StringBytes(2), (byte)'e', (byte)'x' };
// Parse the input fully now.
bytes = Frame(bytes);
var data = new ReadOnlySequence<byte>(bytes);
Assert.True(_hubProtocol.TryParseMessage(ref data, new TestBinder(expectedMessage), out var message));
Assert.NotNull(message);
Assert.Equal(expectedMessage, message, TestHubMessageEqualityComparer.Instance);
}
[Theory]
[MemberData(nameof(TestDataNames))]
public void WriteMessages(string testDataName)
{
var testData = TestData[testDataName];
var bytes = Write(testData.Message);
// Unframe the message to check the binary encoding
var byteSpan = new ReadOnlySequence<byte>(bytes);
Assert.True(BinaryMessageParser.TryParseMessage(ref byteSpan, out var unframed));
// Check the baseline binary encoding, use Assert.True in order to configure the error message
var actual = Convert.ToBase64String(unframed.ToArray());
Assert.True(string.Equals(actual, testData.Binary, StringComparison.Ordinal), $"Binary encoding changed from{Environment.NewLine} [{testData.Binary}]{Environment.NewLine} to{Environment.NewLine} [{actual}]{Environment.NewLine}Please verify the MsgPack output and update the baseline");
}
[Fact]
public void WriteAndParseDateTimeConvertsToUTC()
{
var dateTime = new DateTime(2018, 4, 9);
var writer = MemoryBufferWriter.Get();
try
{
_hubProtocol.WriteMessage(CompletionMessage.WithResult("xyz", dateTime), writer);
var bytes = new ReadOnlySequence<byte>(writer.ToArray());
_hubProtocol.TryParseMessage(ref bytes, new TestBinder(typeof(DateTime)), out var hubMessage);
var completionMessage = Assert.IsType<CompletionMessage>(hubMessage);
var resultDateTime = (DateTime)completionMessage.Result;
// The messagepack Timestamp format specifies that time is stored as seconds since 1970-01-01 UTC
// so the library has no choice but to store the time as UTC
// https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type
Assert.Equal(dateTime.ToUniversalTime(), resultDateTime);
}
finally
{
MemoryBufferWriter.Return(writer);
}
}
[Fact]
public void WriteAndParseDateTimeOffset()
{
var dateTimeOffset = new DateTimeOffset(new DateTime(2018, 4, 9), TimeSpan.FromHours(10));
var writer = MemoryBufferWriter.Get();
try
{
_hubProtocol.WriteMessage(CompletionMessage.WithResult("xyz", dateTimeOffset), writer);
var bytes = new ReadOnlySequence<byte>(writer.ToArray());
_hubProtocol.TryParseMessage(ref bytes, new TestBinder(typeof(DateTimeOffset)), out var hubMessage);
var completionMessage = Assert.IsType<CompletionMessage>(hubMessage);
var resultDateTimeOffset = (DateTimeOffset)completionMessage.Result;
Assert.Equal(dateTimeOffset, resultDateTimeOffset);
}
finally
{
MemoryBufferWriter.Return(writer);
}
}
public static IDictionary<string, InvalidMessageData> InvalidPayloads => new[]
{
// Message Type
new InvalidMessageData("MessageTypeString", new byte[] { 0x91, 0xa3, (byte)'f', (byte)'o', (byte)'o' }, "Reading 'messageType' as Int32 failed."),
// Headers
new InvalidMessageData("HeadersNotAMap", new byte[] { 0x92, 1, 0xa3, (byte)'f', (byte)'o', (byte)'o' }, "Reading map length for 'headers' failed."),
new InvalidMessageData("HeaderKeyInt", new byte[] { 0x92, 1, 0x82, 0x2a, 0xa3, (byte)'f', (byte)'o', (byte)'o' }, "Reading 'headers[0].Key' as String failed."),
new InvalidMessageData("HeaderValueInt", new byte[] { 0x92, 1, 0x82, 0xa3, (byte)'f', (byte)'o', (byte)'o', 42 }, "Reading 'headers[0].Value' as String failed."),
new InvalidMessageData("HeaderKeyArray", new byte[] { 0x92, 1, 0x84, 0xa3, (byte)'f', (byte)'o', (byte)'o', 0xa3, (byte)'f', (byte)'o', (byte)'o', 0x90, 0xa3, (byte)'f', (byte)'o', (byte)'o' }, "Reading 'headers[1].Key' as String failed."),
new InvalidMessageData("HeaderValueArray", new byte[] { 0x92, 1, 0x84, 0xa3, (byte)'f', (byte)'o', (byte)'o', 0xa3, (byte)'f', (byte)'o', (byte)'o', 0xa3, (byte)'f', (byte)'o', (byte)'o', 0x90 }, "Reading 'headers[1].Value' as String failed."),
// InvocationMessage
new InvalidMessageData("InvocationMissingId", new byte[] { 0x92, 1, 0x80 }, "Reading 'invocationId' as String failed."),
new InvalidMessageData("InvocationIdBoolean", new byte[] { 0x91, 1, 0x80, 0xc2 }, "Reading 'invocationId' as String failed."),
new InvalidMessageData("InvocationTargetMissing", new byte[] { 0x93, 1, 0x80, 0xa3, (byte)'a', (byte)'b', (byte)'c' }, "Reading 'target' as String failed."),
new InvalidMessageData("InvocationTargetInt", new byte[] { 0x94, 1, 0x80, 0xa3, (byte)'a', (byte)'b', (byte)'c', 42 }, "Reading 'target' as String failed."),
// StreamInvocationMessage
new InvalidMessageData("StreamInvocationMissingId", new byte[] { 0x92, 4, 0x80 }, "Reading 'invocationId' as String failed."),
new InvalidMessageData("StreamInvocationIdBoolean", new byte[] { 0x93, 4, 0x80, 0xc2 }, "Reading 'invocationId' as String failed."),
new InvalidMessageData("StreamInvocationTargetMissing", new byte[] { 0x93, 4, 0x80, 0xa3, (byte)'a', (byte)'b', (byte)'c' }, "Reading 'target' as String failed."),
new InvalidMessageData("StreamInvocationTargetInt", new byte[] { 0x94, 4, 0x80, 0xa3, (byte)'a', (byte)'b', (byte)'c', 42 }, "Reading 'target' as String failed."),
// StreamItemMessage
new InvalidMessageData("StreamItemMissingId", new byte[] { 0x92, 2, 0x80 }, "Reading 'invocationId' as String failed."),
new InvalidMessageData("StreamItemInvocationIdBoolean", new byte[] { 0x93, 2, 0x80, 0xc2 }, "Reading 'invocationId' as String failed."),
new InvalidMessageData("StreamItemMissing", new byte[] { 0x93, 2, 0x80, 0xa3, (byte)'x', (byte)'y', (byte)'z' }, "Deserializing object of the `String` type for 'item' failed."),
new InvalidMessageData("StreamItemTypeMismatch", new byte[] { 0x94, 2, 0x80, 0xa3, (byte)'x', (byte)'y', (byte)'z', 42 }, "Deserializing object of the `String` type for 'item' failed."),
// CompletionMessage
new InvalidMessageData("CompletionMissingId", new byte[] { 0x92, 3, 0x80 }, "Reading 'invocationId' as String failed."),
new InvalidMessageData("CompletionIdBoolean", new byte[] { 0x93, 3, 0x80, 0xc2 }, "Reading 'invocationId' as String failed."),
new InvalidMessageData("CompletionResultKindString", new byte[] { 0x94, 3, 0x80, 0xa3, (byte)'x', (byte)'y', (byte)'z', 0xa3, (byte)'x', (byte)'y', (byte)'z' }, "Reading 'resultKind' as Int32 failed."),
new InvalidMessageData("CompletionResultKindOutOfRange", new byte[] { 0x94, 3, 0x80, 0xa3, (byte)'x', (byte)'y', (byte)'z', 42 }, "Invalid invocation result kind."),
new InvalidMessageData("CompletionErrorMissing", new byte[] { 0x94, 3, 0x80, 0xa3, (byte)'x', (byte)'y', (byte)'z', 0x01 }, "Reading 'error' as String failed."),
new InvalidMessageData("CompletionErrorInt", new byte[] { 0x95, 3, 0x80, 0xa3, (byte)'x', (byte)'y', (byte)'z', 0x01, 42 }, "Reading 'error' as String failed."),
new InvalidMessageData("CompletionResultMissing", new byte[] { 0x94, 3, 0x80, 0xa3, (byte)'x', (byte)'y', (byte)'z', 0x03 }, "Deserializing object of the `String` type for 'argument' failed."),
new InvalidMessageData("CompletionResultTypeMismatch", new byte[] { 0x95, 3, 0x80, 0xa3, (byte)'x', (byte)'y', (byte)'z', 0x03, 42 }, "Deserializing object of the `String` type for 'argument' failed."),
}.ToDictionary(t => t.Name);
public static IEnumerable<object[]> InvalidPayloadNames => InvalidPayloads.Keys.Select(name => new object[] { name });
[Theory]
[MemberData(nameof(InvalidPayloadNames))]
public void ParserThrowsForInvalidMessages(string invalidPayloadName)
{
var testData = InvalidPayloads[invalidPayloadName];
var buffer = Frame(testData.Encoded);
var binder = new TestBinder(new[] { typeof(string) }, typeof(string));
var data = new ReadOnlySequence<byte>(buffer);
var exception = Assert.Throws<InvalidDataException>(() => _hubProtocol.TryParseMessage(ref data, binder, out _));
Assert.Equal(testData.ErrorMessage, exception.Message);
}
public static IDictionary<string, InvalidMessageData> ArgumentBindingErrors => new[]
{
// InvocationMessage
new InvalidMessageData("InvocationArgumentArrayMissing", new byte[] { 0x94, 1, 0x80, 0xa3, (byte)'a', (byte)'b', (byte)'c', 0xa3, (byte)'x', (byte)'y', (byte)'z' }, "Reading array length for 'arguments' failed."),
new InvalidMessageData("InvocationArgumentArrayNotAnArray", new byte[] { 0x95, 1, 0x80, 0xa3, (byte)'a', (byte)'b', (byte)'c', 0xa3, (byte)'x', (byte)'y', (byte)'z', 42 }, "Reading array length for 'arguments' failed."),
new InvalidMessageData("InvocationArgumentArraySizeMismatchEmpty", new byte[] { 0x95, 1, 0x80, 0xa3, (byte)'a', (byte)'b', (byte)'c', 0xa3, (byte)'x', (byte)'y', (byte)'z', 0x90 }, "Invocation provides 0 argument(s) but target expects 1."),
new InvalidMessageData("InvocationArgumentArraySizeMismatchTooLarge", new byte[] { 0x95, 1, 0x80, 0xa3, (byte)'a', (byte)'b', (byte)'c', 0xa3, (byte)'x', (byte)'y', (byte)'z', 0x92, 0xa1, (byte)'a', 0xa1, (byte)'b' }, "Invocation provides 2 argument(s) but target expects 1."),
new InvalidMessageData("InvocationArgumentTypeMismatch", new byte[] { 0x95, 1, 0x80, 0xa3, (byte)'a', (byte)'b', (byte)'c', 0xa3, (byte)'x', (byte)'y', (byte)'z', 0x91, 42 }, "Error binding arguments. Make sure that the types of the provided values match the types of the hub method being invoked."),
// StreamInvocationMessage
new InvalidMessageData("StreamInvocationArgumentArrayMissing", new byte[] { 0x94, 4, 0x80, 0xa3, (byte)'a', (byte)'b', (byte)'c', 0xa3, (byte)'x', (byte)'y', (byte)'z' }, "Reading array length for 'arguments' failed."), // array is missing
new InvalidMessageData("StreamInvocationArgumentArrayNotAnArray", new byte[] { 0x95, 4, 0x80, 0xa3, (byte)'a', (byte)'b', (byte)'c', 0xa3, (byte)'x', (byte)'y', (byte)'z', 42 }, "Reading array length for 'arguments' failed."), // arguments isn't an array
new InvalidMessageData("StreamInvocationArgumentArraySizeMismatchEmpty", new byte[] { 0x95, 4, 0x80, 0xa3, (byte)'a', (byte)'b', (byte)'c', 0xa3, (byte)'x', (byte)'y', (byte)'z', 0x90 }, "Invocation provides 0 argument(s) but target expects 1."), // array is missing elements
new InvalidMessageData("StreamInvocationArgumentArraySizeMismatchTooLarge", new byte[] { 0x95, 4, 0x80, 0xa3, (byte)'a', (byte)'b', (byte)'c', 0xa3, (byte)'x', (byte)'y', (byte)'z', 0x92, 0xa1, (byte)'a', 0xa1, (byte)'b' }, "Invocation provides 2 argument(s) but target expects 1."), // argument count does not match binder argument count
new InvalidMessageData("StreamInvocationArgumentTypeMismatch", new byte[] { 0x95, 4, 0x80, 0xa3, (byte)'a', (byte)'b', (byte)'c', 0xa3, (byte)'x', (byte)'y', (byte)'z', 0x91, 42 }, "Error binding arguments. Make sure that the types of the provided values match the types of the hub method being invoked."), // argument type mismatch
}.ToDictionary(t => t.Name);
public static IEnumerable<object[]> ArgumentBindingErrorNames => ArgumentBindingErrors.Keys.Select(name => new object[] { name });
[Theory]
[MemberData(nameof(ArgumentBindingErrorNames))]
public void GettingArgumentsThrowsIfBindingFailed(string argumentBindingErrorName)
{
var testData = ArgumentBindingErrors[argumentBindingErrorName];
var buffer = Frame(testData.Encoded);
var binder = new TestBinder(new[] { typeof(string) }, typeof(string));
var data = new ReadOnlySequence<byte>(buffer);
_hubProtocol.TryParseMessage(ref data, binder, out var message);
var bindingFailure = Assert.IsType<InvocationBindingFailureMessage>(message);
Assert.Equal(testData.ErrorMessage, bindingFailure.BindingFailure.SourceException.Message);
}
[Theory]
[InlineData(new byte[] { 0x05, 0x01 })]
public void ParserDoesNotConsumePartialData(byte[] payload)
{
var binder = new TestBinder(new[] { typeof(string) }, typeof(string));
var data = new ReadOnlySequence<byte>(payload);
var result = _hubProtocol.TryParseMessage(ref data, binder, out var message);
Assert.Null(message);
}
[Fact]
public void SerializerCanSerializeTypesWithNoDefaultCtor()
{
var result = Write(CompletionMessage.WithResult("0", new List<int> { 42 }.AsReadOnly()));
AssertMessages(new byte[] { ArrayBytes(5), 3, 0x80, StringBytes(1), (byte)'0', 0x03, ArrayBytes(1), 42 }, result);
}
private byte ArrayBytes(int size)
{
Debug.Assert(size < 16, "Test code doesn't support array sizes greater than 15");
return (byte)(0x90 | size);
}
private byte StringBytes(int size)
{
Debug.Assert(size < 16, "Test code doesn't support string sizes greater than 15");
return (byte)(0xa0 | size);
}
private static void AssertMessages(byte[] expectedOutput, ReadOnlyMemory<byte> bytes)
{
var data = new ReadOnlySequence<byte>(bytes);
Assert.True(BinaryMessageParser.TryParseMessage(ref data, out var message));
Assert.Equal(expectedOutput, message.ToArray());
}
private static byte[] Frame(byte[] input)
{
var stream = MemoryBufferWriter.Get();
try
{
BinaryMessageFormatter.WriteLengthPrefix(input.Length, stream);
stream.Write(input);
return stream.ToArray();
}
finally
{
MemoryBufferWriter.Return(stream);
}
}
private static byte[] Write(HubMessage message)
{
var writer = MemoryBufferWriter.Get();
try
{
_hubProtocol.WriteMessage(message, writer);
return writer.ToArray();
}
finally
{
MemoryBufferWriter.Return(writer);
}
}
public class InvalidMessageData
{
public string Name { get; private set; }
public byte[] Encoded { get; private set; }
public string ErrorMessage { get; private set; }
public InvalidMessageData(string name, byte[] encoded, string errorMessage)
{
Name = name;
Encoded = encoded;
ErrorMessage = errorMessage;
}
public override string ToString() => Name;
}
public class ProtocolTestData
{
public string Name { get; }
public string Binary { get; }
public HubMessage Message { get; }
public ProtocolTestData(string name, HubMessage message, string binary)
{
Name = name;
Message = message;
Binary = binary;
}
public override string ToString() => Name;
}
}
}
| {
"pile_set_name": "Github"
} |
/// Specifies the number of columns an element should span. If the selector is nested the number of columns of its parent element should be passed as an argument as well.
///
/// @param {List} $span
/// A list containing `$columns`, the unitless number of columns the element spans (required), and `$container-columns`, the number of columns the parent element spans (optional).
///
/// If only one value is passed, it is assumed that it's `$columns` and that that `$container-columns` is equal to `$grid-columns`, the total number of columns in the grid.
///
/// The values can be separated with any string such as `of`, `/`, etc.
///
/// @param {String} $display (block)
/// Sets the display property of the element. By default it sets the display propert of the element to `block`.
///
/// If passed `block-collapse`, it also removes the margin gutter by adding it to the element width.
///
/// If passed `table`, it sets the display property to `table-cell` and calculates the width of the element without taking gutters into consideration. The result does not align with the block-based grid.
///
/// @example scss - Usage
/// .element {
/// @include span-columns(6);
///
/// .nested-element {
/// @include span-columns(2 of 6);
/// }
/// }
///
/// @example css - CSS Output
/// .element {
/// display: block;
/// float: left;
/// margin-right: 2.35765%;
/// width: 48.82117%;
/// }
///
/// .element:last-child {
/// margin-right: 0;
/// }
///
/// .element .nested-element {
/// display: block;
/// float: left;
/// margin-right: 4.82916%;
/// width: 30.11389%;
/// }
///
/// .element .nested-element:last-child {
/// margin-right: 0;
/// }
@mixin span-columns($span: $columns of $container-columns, $display: block) {
$columns: nth($span, 1);
$container-columns: container-span($span);
$parent-columns: get-parent-columns($container-columns) !global;
$direction: get-direction($layout-direction, $default-layout-direction);
$opposite-direction: get-opposite-direction($direction);
$display-table: is-display-table($container-display-table, $display);
@if $display-table {
display: table-cell;
width: percentage($columns / $container-columns);
} @else {
float: #{$opposite-direction};
@if $display != no-display {
display: block;
}
@if $display == collapse {
@include -neat-warn("The 'collapse' argument will be deprecated. Use 'block-collapse' instead.");
}
@if $display == collapse or $display == block-collapse {
width: flex-grid($columns, $container-columns) + flex-gutter($container-columns);
&:last-child {
width: flex-grid($columns, $container-columns);
}
} @else {
margin-#{$direction}: flex-gutter($container-columns);
width: flex-grid($columns, $container-columns);
&:last-child {
margin-#{$direction}: 0;
}
}
}
}
| {
"pile_set_name": "Github"
} |
/**
* Framework7 1.0.7
* Full Featured Mobile HTML Framework For Building iOS Apps
*
* http://www.idangero.us/framework7
*
* Copyright 2015, Vladimir Kharlampidi
* The iDangero.us
* http://www.idangero.us/
*
* Licensed under MIT
*
* Released on: June 20, 2015
*/
/*==========================
Framework7 Layouts Themes
==========================*/
/* === Dark layout === */
.layout-dark .navbar,
.navbar.layout-dark,
.layout-dark .subnavbar,
.subnavbar.layout-dark {
background-color: #131313;
color: #ffffff;
}
.layout-dark .navbar:after,
.navbar.layout-dark:after,
.layout-dark .subnavbar:after,
.subnavbar.layout-dark:after {
background-color: #333333;
}
.layout-dark .toolbar,
.toolbar.layout-dark {
background-color: #131313;
color: #ffffff;
}
.layout-dark .toolbar:before,
.toolbar.layout-dark:before {
background-color: #333333;
}
.layout-dark .picker-calendar-week-days {
color: #fff;
background-color: #131313;
}
.layout-dark .popover .picker-modal .picker-center-highlight:before,
.layout-dark .picker-modal.picker-modal-inline .picker-center-highlight:before {
background-color: #333333;
}
.layout-dark .popover .picker-modal .picker-center-highlight:after,
.layout-dark .picker-modal.picker-modal-inline .picker-center-highlight:after {
background-color: #333333;
}
.layout-dark .popover .picker-modal .picker-item.picker-selected,
.layout-dark .picker-modal.picker-modal-inline .picker-item.picker-selected {
color: #fff;
}
.layout-dark .popover .picker-modal .picker-calendar-week-days,
.layout-dark .picker-modal.picker-modal-inline .picker-calendar-week-days {
color: #fff;
}
.layout-dark .popover .picker-modal .picker-calendar-day,
.layout-dark .picker-modal.picker-modal-inline .picker-calendar-day {
color: #fff;
}
.layout-dark .popover .picker-modal .picker-calendar-day.picker-calendar-day-prev,
.layout-dark .picker-modal.picker-modal-inline .picker-calendar-day.picker-calendar-day-prev,
.layout-dark .popover .picker-modal .picker-calendar-day.picker-calendar-day-next,
.layout-dark .picker-modal.picker-modal-inline .picker-calendar-day.picker-calendar-day-next {
color: #777;
}
.layout-dark .popover .picker-modal .picker-calendar-day.picker-calendar-day-disabled,
.layout-dark .picker-modal.picker-modal-inline .picker-calendar-day.picker-calendar-day-disabled {
color: #555;
}
.layout-dark .popover .picker-modal .picker-calendar-day.picker-calendar-day-today span,
.layout-dark .picker-modal.picker-modal-inline .picker-calendar-day.picker-calendar-day-today span {
background: #444;
}
.layout-dark .popover .picker-modal .picker-calendar-week-days:after,
.layout-dark .picker-modal.picker-modal-inline .picker-calendar-week-days:after,
.layout-dark .popover .picker-modal .picker-calendar-row:after,
.layout-dark .picker-modal.picker-modal-inline .picker-calendar-row:after {
background-color: #333333;
}
.layout-dark .popover .picker-modal .toolbar ~ .picker-modal-inner .picker-calendar-months:before,
.layout-dark .picker-modal.picker-modal-inline .toolbar ~ .picker-modal-inner .picker-calendar-months:before,
.layout-dark .popover .picker-modal .picker-calendar-week-days ~ .picker-calendar-months:before,
.layout-dark .picker-modal.picker-modal-inline .picker-calendar-week-days ~ .picker-calendar-months:before {
background-color: #333333;
}
.layout-dark .popover .picker-modal .toolbar:after {
background-color: #333333;
}
.layout-dark .photo-browser .navbar,
.photo-browser.layout-dark .navbar,
.layout-dark .view[data-page="photo-browser-slides"] .navbar,
.view[data-page="photo-browser-slides"].layout-dark .navbar,
.layout-dark .photo-browser .toolbar,
.photo-browser.layout-dark .toolbar,
.layout-dark .view[data-page="photo-browser-slides"] .toolbar,
.view[data-page="photo-browser-slides"].layout-dark .toolbar {
background: rgba(19, 19, 19, 0.95);
}
.layout-dark .tabbar a:not(.active) {
color: #ffffff;
}
.layout-dark .page,
.layout-dark .login-screen-content,
.page.layout-dark,
.layout-dark .panel,
.panel.layout-dark {
background-color: #222426;
color: #dddddd;
}
.layout-dark .content-block-title {
color: #ffffff;
}
.layout-dark .content-block,
.content-block.layout-dark {
color: #bbbbbb;
}
.layout-dark .content-block-inner {
background: #1c1d1f;
color: #dddddd;
}
.layout-dark .content-block-inner:before {
background-color: #393939;
}
.layout-dark .content-block-inner:after {
background-color: #393939;
}
.layout-dark .list-block ul,
.list-block.layout-dark ul {
background: #1c1d1f;
}
.layout-dark .list-block ul:before,
.list-block.layout-dark ul:before {
background-color: #393939;
}
.layout-dark .list-block ul:after,
.list-block.layout-dark ul:after {
background-color: #393939;
}
.layout-dark .list-block.inset ul,
.list-block.layout-dark.inset ul {
background: #1c1d1f;
}
.layout-dark .list-block.notifications > ul,
.list-block.layout-dark.notifications > ul {
background: none;
}
.layout-dark .card {
background: #1c1d1f;
}
.layout-dark .card-header:after {
background-color: #393939;
}
.layout-dark .card-footer {
color: #bbbbbb;
}
.layout-dark .card-footer:before {
background-color: #393939;
}
.layout-dark .popover,
.popover.layout-dark {
background: rgba(0, 0, 0, 0.8);
}
.layout-dark .popover .popover-angle:after,
.popover.layout-dark .popover-angle:after {
background: rgba(0, 0, 0, 0.8);
}
.layout-dark .popover .list-block ul,
.popover.layout-dark .list-block ul {
background: none;
}
.layout-dark .actions-popover .list-block ul:before {
background-color: #393939;
}
.layout-dark .actions-popover .list-block ul:after {
background-color: #393939;
}
.layout-dark .actions-popover .actions-popover-label:after {
background-color: #393939;
}
.layout-dark li.sorting {
background-color: #29292f;
}
.layout-dark .swipeout-actions-left a,
.layout-dark .swipeout-actions-right a {
background-color: #444444;
}
.layout-dark .item-inner:after,
.layout-dark .list-block ul ul li:last-child .item-inner:after {
background-color: #393939;
}
.layout-dark .item-after {
color: #bbbbbb;
}
html:not(.watch-active-state) .layout-dark .item-link:active,
html:not(.watch-active-state) .layout-dark label.label-checkbox:active,
html:not(.watch-active-state) .layout-dark label.label-radio:active,
.layout-dark .item-link.active-state,
.layout-dark label.label-checkbox.active-state,
.layout-dark label.label-radio.active-state {
background-color: #29292f;
}
.layout-dark .item-link.list-button:after {
background-color: #393939;
}
.layout-dark .list-block-label {
color: #bbbbbb;
}
.layout-dark .item-divider,
.layout-dark .list-group-title {
background: #1a1a1a;
color: #bbbbbb;
}
.layout-dark .item-divider:before,
.layout-dark .list-group-title:before {
background-color: #393939;
}
.layout-dark .searchbar {
background: #333333;
}
.layout-dark .searchbar:after {
background-color: #333333;
}
.layout-dark .list-block input[type="text"],
.list-block.layout-dark input[type="text"],
.layout-dark .list-block input[type="password"],
.list-block.layout-dark input[type="password"],
.layout-dark .list-block input[type="email"],
.list-block.layout-dark input[type="email"],
.layout-dark .list-block input[type="tel"],
.list-block.layout-dark input[type="tel"],
.layout-dark .list-block input[type="url"],
.list-block.layout-dark input[type="url"],
.layout-dark .list-block input[type="date"],
.list-block.layout-dark input[type="date"],
.layout-dark .list-block input[type="datetime-local"],
.list-block.layout-dark input[type="datetime-local"],
.layout-dark .list-block input[type="number"],
.list-block.layout-dark input[type="number"],
.layout-dark .list-block select,
.list-block.layout-dark select,
.layout-dark .list-block textarea,
.list-block.layout-dark textarea {
color: #ffffff;
}
.layout-dark .label-switch .checkbox {
background-color: #393939;
}
.layout-dark .label-switch .checkbox:before {
background-color: #1c1d1f;
}
.layout-dark .range-slider input[type="range"]:after {
background: #1c1d1f;
}
/* === White layout === */
.layout-white .navbar,
.navbar.layout-white,
.layout-white .subnavbar,
.subnavbar.layout-white {
background-color: #ffffff;
color: #000000;
}
.layout-white .navbar:after,
.navbar.layout-white:after,
.layout-white .subnavbar:after,
.subnavbar.layout-white:after {
background-color: #dddddd;
}
.layout-white .toolbar,
.toolbar.layout-white {
background-color: #ffffff;
color: #000000;
}
.layout-white .toolbar:before,
.toolbar.layout-white:before {
background-color: #dddddd;
}
.layout-white .popover .picker-modal .picker-center-highlight:before,
.layout-white .picker-modal.picker-modal-inline .picker-center-highlight:before {
background-color: #dddddd;
}
.layout-white .popover .picker-modal .picker-center-highlight:after,
.layout-white .picker-modal.picker-modal-inline .picker-center-highlight:after {
background-color: #dddddd;
}
.layout-white .popover .picker-modal .picker-calendar-week-days:after,
.layout-white .picker-modal.picker-modal-inline .picker-calendar-week-days:after,
.layout-white .popover .picker-modal .picker-calendar-row:after,
.layout-white .picker-modal.picker-modal-inline .picker-calendar-row:after {
background-color: #dddddd;
}
.layout-white .popover .picker-modal .toolbar ~ .picker-modal-inner .picker-calendar-months:before,
.layout-white .picker-modal.picker-modal-inline .toolbar ~ .picker-modal-inner .picker-calendar-months:before,
.layout-white .popover .picker-modal .picker-calendar-week-days ~ .picker-calendar-months:before,
.layout-white .picker-modal.picker-modal-inline .picker-calendar-week-days ~ .picker-calendar-months:before {
background-color: #dddddd;
}
.layout-white .popover .picker-modal .toolbar:after {
background-color: #dddddd;
}
.layout-white .photo-browser .navbar,
.photo-browser.layout-white .navbar,
.layout-white .view[data-page="photo-browser-slides"] .navbar,
.view[data-page="photo-browser-slides"].layout-white .navbar,
.layout-white .photo-browser .toolbar,
.photo-browser.layout-white .toolbar,
.layout-white .view[data-page="photo-browser-slides"] .toolbar,
.view[data-page="photo-browser-slides"].layout-white .toolbar {
background: rgba(255, 255, 255, 0.95);
}
.layout-white .tabbar a:not(.active) {
color: #777777;
}
.layout-white .page,
.layout-white .login-screen-content,
.page.layout-white,
.layout-white .panel,
.panel.layout-white {
background-color: #ffffff;
color: #000000;
}
.layout-white .content-block-title {
color: #777777;
}
.layout-white .content-block,
.content-block.layout-white {
color: #777777;
}
.layout-white .content-block-inner {
background: #fafafa;
color: #000000;
}
.layout-white .content-block-inner:after {
background-color: #dddddd;
}
.layout-white .content-block-inner:before {
background-color: #dddddd;
}
.layout-white .list-block ul,
.list-block.layout-white ul {
background: #ffffff;
}
.layout-white .list-block ul:after,
.list-block.layout-white ul:after {
background-color: #dddddd;
}
.layout-white .list-block ul:before,
.list-block.layout-white ul:before {
background-color: #dddddd;
}
.layout-white .list-block.inset ul,
.list-block.layout-white.inset ul {
background: #fafafa;
}
.layout-white .list-block.notifications > ul,
.list-block.layout-white.notifications > ul {
background: none;
}
.layout-white .popover-inner > .list-block ul {
background: none;
}
.layout-white li.sorting {
background-color: #eeeeee;
}
.layout-white .swipeout-actions-left a,
.layout-white .swipeout-actions-right a {
background-color: #c7c7cc;
}
.layout-white .item-inner,
.layout-white .list-block ul ul li:last-child .item-inner {
border-color: #dddddd;
}
.layout-white .item-inner:after,
.layout-white .list-block ul ul li:last-child .item-inner:after {
background-color: #dddddd;
}
.layout-white .item-after {
color: #8e8e93;
}
html:not(.watch-active-state) .layout-white .item-link:active,
html:not(.watch-active-state) .layout-white label.label-checkbox:active,
html:not(.watch-active-state) .layout-white label.label-radio:active,
.layout-white .item-link.active-state,
.layout-white label.label-checkbox.active-state,
.layout-white label.label-radio.active-state {
background-color: #eeeeee;
}
.layout-white .item-link.list-button:after {
background-color: #dddddd;
}
.layout-white .list-block-label {
color: #777777;
}
.layout-white .item-divider,
.layout-white .list-group-title {
background: #f7f7f7;
color: #777777;
}
.layout-white .item-divider:before,
.layout-white .list-group-title:before {
background-color: #dddddd;
}
.layout-white .searchbar {
background: #c9c9ce;
}
.layout-white .searchbar:after {
background-color: #b4b4b4;
}
.layout-white .list-block input[type="text"],
.list-block.layout-white input[type="text"],
.layout-white .list-block input[type="password"],
.list-block.layout-white input[type="password"],
.layout-white .list-block input[type="email"],
.list-block.layout-white input[type="email"],
.layout-white .list-block input[type="tel"],
.list-block.layout-white input[type="tel"],
.layout-white .list-block input[type="url"],
.list-block.layout-white input[type="url"],
.layout-white .list-block input[type="date"],
.list-block.layout-white input[type="date"],
.layout-white .list-block input[type="datetime-local"],
.list-block.layout-white input[type="datetime-local"],
.layout-white .list-block input[type="number"],
.list-block.layout-white input[type="number"],
.layout-white .list-block select,
.list-block.layout-white select,
.layout-white .list-block textarea,
.list-block.layout-white textarea {
color: #777777;
}
.layout-white .label-switch .checkbox {
background-color: #e5e5e5;
}
.layout-white .label-switch .checkbox:before {
background-color: #ffffff;
}
.layout-white .range-slider input[type="range"]:after {
background: #ffffff;
}
| {
"pile_set_name": "Github"
} |
$ echo "hello" > /tmp/dat
$ echo "go" >> /tmp/dat
$ go run reading-files.go
hello
go
5 bytes: hello
2 bytes @ 6: go
2 bytes @ 6: go
5 bytes: hello
# 下面我们来看一下写入文件。
| {
"pile_set_name": "Github"
} |
# Software License Agreement
#
# Copyright(C) 1994-2020 David Lindauer, (LADSoft)
#
# This file is part of the Orange C Compiler package.
#
# The Orange C Compiler package is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# The Orange C Compiler package is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Orange C. If not, see <http://www.gnu.org/licenses/>.
#
# contact information:
# email: [email protected] <David Lindauer>
#
include ../pathext2.mak
NAME=onm
MAIN_FILE=nmMain.cpp
INCLUDES=..$(PATHEXT2)util ..$(PATHEXT2)objlib ..$(PATHEXT2)olink ..$(PATHEXT2)olib
CPP_DEPENDENCIES=$(wildcard *.cpp)
LIB_DEPENDENCIES=util objlib olink olib
H_FILES=$(wildcard *.h)
include ../redirect.mak
DISTRIBUTE: copyexe
| {
"pile_set_name": "Github"
} |
# 5.4
* The passed arguments to the callable $error of `ILIAS\Validation\Factory::custom`
(or `ILIAS\Validation\Constraint\Custom` respectively) changed. The callable now
gets a function to perform i18n and replace placeholder and the faulty value as
a second parameter.
* `ILIAS\Validation\Factory` got a new dependency on `\ilLanguage` to satisfy that
dependency of `ILIAS\Validation\Constraint\Custom` and the derived classes.
| {
"pile_set_name": "Github"
} |
//
// FKFlickrPlacesTagsForPlace.m
// FlickrKit
//
// Generated by FKAPIBuilder.
// Copyright (c) 2013 DevedUp Ltd. All rights reserved. http://www.devedup.com
//
// DO NOT MODIFY THIS FILE - IT IS MACHINE GENERATED
#import "FKFlickrPlacesTagsForPlace.h"
@implementation FKFlickrPlacesTagsForPlace
- (BOOL) needsLogin {
return NO;
}
- (BOOL) needsSigning {
return NO;
}
- (FKPermission) requiredPerms {
return -1;
}
- (NSString *) name {
return @"flickr.places.tagsForPlace";
}
- (BOOL) isValid:(NSError **)error {
BOOL valid = YES;
NSMutableString *errorDescription = [[NSMutableString alloc] initWithString:@"You are missing required params: "];
if(error != NULL) {
if(!valid) {
NSDictionary *userInfo = @{NSLocalizedDescriptionKey: errorDescription};
*error = [NSError errorWithDomain:FKFlickrKitErrorDomain code:FKErrorInvalidArgs userInfo:userInfo];
}
}
return valid;
}
- (NSDictionary *) args {
NSMutableDictionary *args = [NSMutableDictionary dictionary];
if(self.woe_id) {
[args setValue:self.woe_id forKey:@"woe_id"];
}
if(self.place_id) {
[args setValue:self.place_id forKey:@"place_id"];
}
if(self.min_upload_date) {
[args setValue:self.min_upload_date forKey:@"min_upload_date"];
}
if(self.max_upload_date) {
[args setValue:self.max_upload_date forKey:@"max_upload_date"];
}
if(self.min_taken_date) {
[args setValue:self.min_taken_date forKey:@"min_taken_date"];
}
if(self.max_taken_date) {
[args setValue:self.max_taken_date forKey:@"max_taken_date"];
}
return [args copy];
}
- (NSString *) descriptionForError:(NSInteger)error {
switch(error) {
case FKFlickrPlacesTagsForPlaceError_RequiredParameterMissing:
return @"Required parameter missing";
case FKFlickrPlacesTagsForPlaceError_NotAValidPlacesID:
return @"Not a valid Places ID";
case FKFlickrPlacesTagsForPlaceError_PlaceNotFound:
return @"Place not found";
case FKFlickrPlacesTagsForPlaceError_InvalidAPIKey:
return @"Invalid API Key";
case FKFlickrPlacesTagsForPlaceError_ServiceCurrentlyUnavailable:
return @"Service currently unavailable";
case FKFlickrPlacesTagsForPlaceError_WriteOperationFailed:
return @"Write operation failed";
case FKFlickrPlacesTagsForPlaceError_FormatXXXNotFound:
return @"Format \"xxx\" not found";
case FKFlickrPlacesTagsForPlaceError_MethodXXXNotFound:
return @"Method \"xxx\" not found";
case FKFlickrPlacesTagsForPlaceError_InvalidSOAPEnvelope:
return @"Invalid SOAP envelope";
case FKFlickrPlacesTagsForPlaceError_InvalidXMLRPCMethodCall:
return @"Invalid XML-RPC Method Call";
case FKFlickrPlacesTagsForPlaceError_BadURLFound:
return @"Bad URL found";
default:
return @"Unknown error code";
}
}
@end
| {
"pile_set_name": "Github"
} |
/*******************************************************************************
* AMetal
* ----------------------------
* innovating embedded platform
*
* Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd.
* All rights reserved.
*
* Contact information:
* web site: http://www.zlg.cn/
*******************************************************************************/
/**
* \file
* \brief 环境光、接近传感器 TMD2750 例程,通过标准接口实现(通过查询方式获取数据)
*
* - 实验现象:
* 1. 每过一秒,通过串口打印接近AD值以及ALS、IR的AD值
*
* \par 源代码
* \snippet demo_zlg237_core_sensor_tmd2750.c src_zlg237_core_sensor_tmd2750
*
* \internal
* \par Modification history
* - 1.00 20-04-26 fzb, first implementation
* \endinternal
*/
#include "am_gpio.h"
#include "am_delay.h"
#include "am_zlg237.h"
#include "am_sensor.h"
#include "am_hwconf_sensor_tmd2750.h"
#include "demo_std_entries.h"
#include "demo_am237_core_entries.h"
/* 1.8V使能引脚,用于控制相同从机地址的通断电 */
#define PIN_1P8_OUT1 PIOC_4
#define PIN_1P8_OUT2 PIOC_5
/**
* \brief 传感器例程入口
*/
void demo_zlg237_core_sensor_tmd2750_entry (void)
{
/* 使能 1.8V_OUT2 引脚 */
am_gpio_pin_cfg(PIN_1P8_OUT2, AM_GPIO_OUTPUT_INIT_HIGH);
/* 等待供电稳定 */
am_mdelay(2);
am_sensor_handle_t handle = am_sensor_tmd2750_inst_init();
demo_std_tmd2750_entry(handle);
}
/* end of file */
| {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Dotmim.Sync.Tools
{
public class Project
{
/// <summary>
/// Gets or Sets the project name
/// </summary>
public String Name { get; set; }
/// <summary>
/// Gets or Sets the Server provider used
/// </summary>
public Provider ServerProvider { get; set; }
/// <summary>
/// Gets or Sets the Client provider used
/// </summary>
public Provider ClientProvider { get; set; }
/// <summary>
/// Gets or Sets the Table list
/// </summary>
public List<Table> Tables { get; set; } = new List<Table>();
/// <summary>
/// Gets or Sets the Configuration used
/// </summary>
public Configuration Configuration { get; set; } = new Configuration();
public Project()
{
}
/// <summary>
/// Create the default project
/// </summary>
/// <returns></returns>
public static Project CreateProject(string name)
{
return new Project
{
Name = name,
ServerProvider = new Provider
{
ConnectionString = String.Empty,
ProviderType = ProviderType.SqlServer,
SyncType = SyncType.Server
},
ClientProvider = new Provider
{
ConnectionString = String.Empty,
ProviderType = ProviderType.SqlServer,
SyncType = SyncType.Client
},
Configuration = new Configuration
{
BatchDirectory = Path.Combine(Path.GetTempPath(), "DotmimSync"),
SerializationFormat = Enumerations.SerializationFormat.Json,
UseBulkOperations = true,
ConflictResolutionPolicy = Enumerations.ConflictResolutionPolicy.ServerWins
},
Tables = new List<Table>()
};
}
}
}
| {
"pile_set_name": "Github"
} |
/*
Copyright (C) GridGain Systems. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/* _________ _____ __________________ _____
* __ ____/___________(_)______ /__ ____/______ ____(_)_______
* _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \
* / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / /
* \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/
*/
package org.gridgain.grid.kernal.processors.cache.datastructures;
import org.gridgain.grid.*;
import org.gridgain.grid.kernal.processors.cache.*;
import org.gridgain.grid.util.tostring.*;
import org.gridgain.grid.util.typedef.internal.*;
import java.io.*;
/**
* Set item key.
*/
public class GridCacheSetItemKey implements GridCacheInternal, Externalizable {
/** */
private static final long serialVersionUID = 0L;
/** */
private GridUuid setId;
/** */
@GridToStringInclude
private Object item;
/**
* Required by {@link Externalizable}.
*/
public GridCacheSetItemKey() {
// No-op.
}
/**
* @param setId Set unique ID.
* @param item Set item.
*/
GridCacheSetItemKey(GridUuid setId, Object item) {
this.setId = setId;
this.item = item;
}
/**
* @return Set UUID.
*/
public GridUuid setId() {
return setId;
}
/**
* @return Set item.
*/
public Object item() {
return item;
}
/** {@inheritDoc} */
@Override public int hashCode() {
int result = setId.hashCode();
result = 31 * result + item.hashCode();
return result;
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
GridCacheSetItemKey that = (GridCacheSetItemKey)o;
return setId.equals(that.setId) && item.equals(that.item);
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
U.writeGridUuid(out, setId);
out.writeObject(item);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
setId = U.readGridUuid(in);
item = in.readObject();
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridCacheSetItemKey.class, this);
}
}
| {
"pile_set_name": "Github"
} |
listen = 0.0.0.0:4222
authorization {
username = shijuvar
password = gopher
}
| {
"pile_set_name": "Github"
} |
// PluginWinExe.h
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8" ?>
<result>
<row>
<label>event action 1</label>
<nb_uniq_visitors>1</nb_uniq_visitors>
<nb_visits>5</nb_visits>
<nb_events>5</nb_events>
<nb_events_with_value>0</nb_events_with_value>
<sum_event_value>0</sum_event_value>
<min_event_value>0</min_event_value>
<max_event_value>0</max_event_value>
<avg_event_value>0</avg_event_value>
<segment>eventAction==event+action+1</segment>
<subtable>
<row>
<label>event name0</label>
<nb_uniq_visitors>1</nb_uniq_visitors>
<nb_visits>5</nb_visits>
<nb_events>5</nb_events>
<nb_events_with_value>0</nb_events_with_value>
<sum_event_value>0</sum_event_value>
<min_event_value>0</min_event_value>
<max_event_value>0</max_event_value>
<avg_event_value>0</avg_event_value>
</row>
</subtable>
</row>
<row>
<label>event action 2</label>
<nb_uniq_visitors>1</nb_uniq_visitors>
<nb_visits>5</nb_visits>
<nb_events>5</nb_events>
<nb_events_with_value>0</nb_events_with_value>
<sum_event_value>0</sum_event_value>
<min_event_value>0</min_event_value>
<max_event_value>0</max_event_value>
<avg_event_value>0</avg_event_value>
<segment>eventAction==event+action+2</segment>
<subtable>
<row>
<label>event name1</label>
<nb_uniq_visitors>1</nb_uniq_visitors>
<nb_visits>5</nb_visits>
<nb_events>5</nb_events>
<nb_events_with_value>0</nb_events_with_value>
<sum_event_value>0</sum_event_value>
<min_event_value>0</min_event_value>
<max_event_value>0</max_event_value>
<avg_event_value>0</avg_event_value>
</row>
</subtable>
</row>
<row>
<label>Others</label>
<nb_uniq_visitors>3</nb_uniq_visitors>
<nb_visits>15</nb_visits>
<nb_events>15</nb_events>
<nb_events_with_value>0</nb_events_with_value>
<sum_event_value>0</sum_event_value>
<min_event_value>0</min_event_value>
<max_event_value>0</max_event_value>
<avg_event_value>0</avg_event_value>
</row>
</result> | {
"pile_set_name": "Github"
} |
framework module AppCenterDistribute {
umbrella header "AppCenterDistribute.h"
export *
module * { export * }
link framework "Foundation"
link framework "SafariServices"
link framework "UIKit"
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server.hdmi;
import static org.junit.Assert.assertEquals;
import android.annotation.Nullable;
import android.hardware.hdmi.HdmiDeviceInfo;
import android.hardware.tv.cec.V1_0.SendMessageResult;
import android.os.Looper;
import android.os.test.TestLooper;
import androidx.test.InstrumentationRegistry;
import androidx.test.filters.SmallTest;
import com.android.server.hdmi.HdmiCecLocalDeviceAudioSystem.TvSystemAudioModeSupportedCallback;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link DetectTvSystemAudioModeSupportAction} class. */
@SmallTest
@RunWith(JUnit4.class)
public class DetectTvSystemAudioModeSupportActionTest {
private HdmiDeviceInfo mDeviceInfoForTests;
private HdmiCecLocalDeviceAudioSystem mHdmiCecLocalDeviceAudioSystem;
private DetectTvSystemAudioModeSupportAction mAction;
private TestLooper mTestLooper = new TestLooper();
private boolean mSendCecCommandSuccess;
private boolean mShouldDispatchFeatureAbort;
private Boolean mSupported;
@Before
public void SetUp() {
mDeviceInfoForTests = new HdmiDeviceInfo(1001, 1234);
HdmiControlService hdmiControlService =
new HdmiControlService(InstrumentationRegistry.getTargetContext()) {
@Override
void sendCecCommand(
HdmiCecMessage command, @Nullable SendMessageCallback callback) {
switch (command.getOpcode()) {
case Constants.MESSAGE_SET_SYSTEM_AUDIO_MODE:
if (callback != null) {
callback.onSendCompleted(
mSendCecCommandSuccess
? SendMessageResult.SUCCESS
: SendMessageResult.NACK);
}
if (mShouldDispatchFeatureAbort) {
mHdmiCecLocalDeviceAudioSystem.dispatchMessage(
HdmiCecMessageBuilder.buildFeatureAbortCommand(
Constants.ADDR_TV,
mHdmiCecLocalDeviceAudioSystem.mAddress,
Constants.MESSAGE_SET_SYSTEM_AUDIO_MODE,
Constants.ABORT_UNRECOGNIZED_OPCODE));
}
break;
default:
throw new IllegalArgumentException("Unexpected message");
}
}
@Override
boolean isPowerStandby() {
return false;
}
@Override
boolean isAddressAllocated() {
return true;
}
@Override
Looper getServiceLooper() {
return mTestLooper.getLooper();
}
};
mHdmiCecLocalDeviceAudioSystem =
new HdmiCecLocalDeviceAudioSystem(hdmiControlService) {
@Override
HdmiDeviceInfo getDeviceInfo() {
return mDeviceInfoForTests;
}
};
mHdmiCecLocalDeviceAudioSystem.init();
Looper looper = mTestLooper.getLooper();
hdmiControlService.setIoLooper(looper);
mAction =
new DetectTvSystemAudioModeSupportAction(
mHdmiCecLocalDeviceAudioSystem,
new TvSystemAudioModeSupportedCallback() {
public void onResult(boolean supported) {
mSupported = Boolean.valueOf(supported);
}
});
mSupported = null;
}
@Test
public void testSendCecCommandNotSucceed() {
mSendCecCommandSuccess = false;
mShouldDispatchFeatureAbort = false;
mHdmiCecLocalDeviceAudioSystem.addAndStartAction(mAction);
mTestLooper.dispatchAll();
assertEquals(Boolean.FALSE, mSupported);
}
@Test
public void testFeatureAbort() {
mSendCecCommandSuccess = true;
mShouldDispatchFeatureAbort = true;
mHdmiCecLocalDeviceAudioSystem.addAndStartAction(mAction);
mTestLooper.dispatchAll();
assertEquals(Boolean.FALSE, mSupported);
}
@Test
public void testSupported() {
mSendCecCommandSuccess = true;
mShouldDispatchFeatureAbort = false;
mHdmiCecLocalDeviceAudioSystem.addAndStartAction(mAction);
mTestLooper.moveTimeForward(2000);
mTestLooper.dispatchAll();
assertEquals(Boolean.TRUE, mSupported);
}
}
| {
"pile_set_name": "Github"
} |
using System.Linq;
namespace Revo.Core.Commands
{
public interface IEntityQuery<T> : IQuery<IQueryable<T>>
{
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2019 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.
#ifndef UI_OZONE_PLATFORM_WAYLAND_HOST_GTK_PRIMARY_SELECTION_DEVICE_H_
#define UI_OZONE_PLATFORM_WAYLAND_HOST_GTK_PRIMARY_SELECTION_DEVICE_H_
#include <memory>
#include <string>
#include <vector>
#include "base/callback.h"
#include "base/macros.h"
#include "ui/ozone/platform/wayland/common/wayland_object.h"
#include "ui/ozone/platform/wayland/host/wayland_data_device_base.h"
#include "ui/ozone/platform/wayland/host/wayland_data_source.h"
struct gtk_primary_selection_device;
namespace ui {
class WaylandConnection;
// This class provides access to primary selection clipboard available on GTK.
class GtkPrimarySelectionDevice : public WaylandDataDeviceBase {
public:
GtkPrimarySelectionDevice(WaylandConnection* connection,
gtk_primary_selection_device* data_device);
~GtkPrimarySelectionDevice() override;
gtk_primary_selection_device* data_device() const {
return data_device_.get();
}
void SetSelectionSource(GtkPrimarySelectionSource* source);
private:
// gtk_primary_selection_device_listener callbacks
static void OnDataOffer(void* data,
gtk_primary_selection_device* data_device,
gtk_primary_selection_offer* offer);
static void OnSelection(void* data,
gtk_primary_selection_device* data_device,
gtk_primary_selection_offer* offer);
// The Wayland object wrapped by this instance.
wl::Object<gtk_primary_selection_device> data_device_;
DISALLOW_COPY_AND_ASSIGN(GtkPrimarySelectionDevice);
};
} // namespace ui
#endif // UI_OZONE_PLATFORM_WAYLAND_HOST_GTK_PRIMARY_SELECTION_DEVICE_H_
| {
"pile_set_name": "Github"
} |
html {
background-color: #e2e2e2;
margin: 0;
padding: 0;
}
body {
background-color: #fff;
border-top: solid 10px #000;
color: #333;
font-size: .85em;
font-family: "Segoe UI", Verdana, Helvetica, Sans-Serif;
margin: 0;
padding: 0;
}
a {
color: #333;
outline: none;
padding-left: 3px;
padding-right: 3px;
text-decoration: underline;
}
a:link, a:visited,
a:active, a:hover {
color: #333;
}
a:hover {
background-color: #c7d1d6;
}
header, footer, hgroup,
nav, section {
display: block;
}
mark {
background-color: #a6dbed;
padding-left: 5px;
padding-right: 5px;
}
.float-left {
float: left;
}
.float-right {
float: right;
}
.clear-fix:after {
content: ".";
clear: both;
display: block;
height: 0;
visibility: hidden;
}
h1, h2, h3,
h4, h5, h6 {
color: #000;
margin-bottom: 0;
padding-bottom: 0;
}
h1 {
font-size: 2em;
}
h2 {
font-size: 1.75em;
}
h3 {
font-size: 1.2em;
}
h4 {
font-size: 1.1em;
}
h5, h6 {
font-size: 1em;
}
h5 a:link, h5 a:visited, h5 a:active {
padding: 0;
text-decoration: none;
}
/* main layout
----------------------------------------------------------*/
.content-wrapper {
margin: 0 auto;
max-width: 960px;
}
#body {
background-color: #efeeef;
clear: both;
padding-bottom: 35px;
}
.main-content {
background: url("../Images/accent.png") no-repeat;
padding-left: 10px;
padding-top: 30px;
}
.featured + .main-content {
background: url("../Images/heroAccent.png") no-repeat;
}
header .content-wrapper {
padding-top: 20px;
}
footer {
clear: both;
background-color: #e2e2e2;
font-size: .8em;
height: 100px;
}
/* site title
----------------------------------------------------------*/
.site-title {
color: #c8c8c8;
font-family: Rockwell, Consolas, "Courier New", Courier, monospace;
font-size: 2.3em;
margin: 0;
}
.site-title a, .site-title a:hover, .site-title a:active {
background: none;
color: #c8c8c8;
outline: none;
text-decoration: none;
}
/* login
----------------------------------------------------------*/
#login {
display: block;
font-size: .85em;
margin: 0 0 10px;
text-align: right;
}
#login a {
background-color: #d3dce0;
margin-left: 10px;
margin-right: 3px;
padding: 2px 3px;
text-decoration: none;
}
#login a.username {
background: none;
margin-left: 0px;
text-decoration: underline;
}
#login ul {
margin: 0;
}
#login li {
display: inline;
list-style: none;
}
/* menu
----------------------------------------------------------*/
ul#menu {
font-size: 1.3em;
font-weight: 600;
margin: 0 0 5px;
padding: 0;
text-align: right;
}
ul#menu li {
display: inline;
list-style: none;
padding-left: 15px;
}
ul#menu li a {
background: none;
color: #999;
text-decoration: none;
}
ul#menu li a:hover {
color: #333;
text-decoration: none;
}
/* page elements
----------------------------------------------------------*/
/* featured */
.featured {
background-color: #fff;
}
.featured .content-wrapper {
background-color: #7ac0da;
background-image: -ms-linear-gradient(left, #7ac0da 0%, #a4d4e6 100%);
background-image: -o-linear-gradient(left, #7ac0da 0%, #a4d4e6 100%);
background-image: -webkit-gradient(linear, left top, right top, color-stop(0, #7ac0da), color-stop(1, #a4d4e6));
background-image: -webkit-linear-gradient(left, #7ac0da 0%, #a4d4e6 100%);
background-image: linear-gradient(left, #7ac0da 0%, #a4d4e6 100%);
color: #3e5667;
padding: 20px 40px 30px 40px;
}
.featured hgroup.title h1, .featured hgroup.title h2 {
color: #fff;
}
.featured p {
font-size: 1.1em;
}
/* page titles */
hgroup.title {
margin-bottom: 10px;
}
hgroup.title h1, hgroup.title h2 {
display: inline;
}
hgroup.title h2 {
font-weight: normal;
margin-left: 3px;
}
/* features */
section.feature {
width: 300px;
float: left;
padding: 10px;
}
/* ordered list */
ol.round {
list-style-type: none;
padding-left: 0;
}
ol.round li {
margin: 25px 0;
padding-left: 45px;
}
ol.round li.zero {
background: url("../Images/orderedList0.png") no-repeat;
}
ol.round li.one {
background: url("../Images/orderedList1.png") no-repeat;
}
ol.round li.two {
background: url("../Images/orderedList2.png") no-repeat;
}
ol.round li.three {
background: url("../Images/orderedList3.png") no-repeat;
}
ol.round li.four {
background: url("../Images/orderedList4.png") no-repeat;
}
ol.round li.five {
background: url("../Images/orderedList5.png") no-repeat;
}
ol.round li.six {
background: url("../Images/orderedList6.png") no-repeat;
}
ol.round li.seven {
background: url("../Images/orderedList7.png") no-repeat;
}
ol.round li.eight {
background: url("../Images/orderedList8.png") no-repeat;
}
ol.round li.nine {
background: url("../Images/orderedList9.png") no-repeat;
}
/* content */
article {
float: left;
width: 70%;
}
aside {
float: right;
width: 25%;
}
aside ul {
list-style: none;
padding: 0;
}
aside ul li {
background: url("../Images/bullet.png") no-repeat 0 50%;
padding: 2px 0 2px 20px;
}
.label {
font-weight: 700;
}
/* login page */
#loginForm {
border-right: solid 2px #c8c8c8;
float: left;
width: 55%;
}
#loginForm .validation-error {
display: block;
margin-left: 15px;
}
#socialLoginForm {
margin-left: 40px;
float: left;
width: 40%;
}
#socialLoginForm h2 {
margin-bottom: 5px;
}
fieldset.open-auth-providers {
margin-top: 15px;
}
fieldset.open-auth-providers button {
margin-bottom: 12px;
}
/* contact */
.contact h3 {
font-size: 1.2em;
}
.contact p {
margin: 5px 0 0 10px;
}
.contact iframe {
border: 1px solid #333;
margin: 5px 0 0 10px;
}
/* forms */
fieldset {
border: none;
margin: 0;
padding: 0;
}
fieldset legend {
display: none;
}
fieldset ol {
padding: 0;
list-style: none;
}
fieldset ol li {
padding-bottom: 5px;
}
label {
display: block;
font-size: 1.2em;
font-weight: 600;
}
label.checkbox {
display: inline;
}
input, textarea {
border: 1px solid #e2e2e2;
background: #fff;
color: #333;
font-size: 1.2em;
margin: 5px 0 6px 0;
padding: 5px;
width: 300px;
}
textarea {
font-family: inherit;
width: 500px;
}
input:focus, textarea:focus {
border: 1px solid #7ac0da;
}
input[type="checkbox"] {
background: transparent;
border: inherit;
width: auto;
}
input[type="submit"],
input[type="button"],
button {
background-color: #d3dce0;
border: 1px solid #787878;
cursor: pointer;
font-size: 1.2em;
font-weight: 600;
padding: 7px;
margin-right: 8px;
width: auto;
}
td input[type="submit"],
td input[type="button"],
td button {
font-size: 1em;
padding: 4px;
margin-right: 4px;
}
/* info and errors */
.message-info {
border: 1px solid;
clear: both;
padding: 10px 20px;
}
.message-error {
clear: both;
color: #e80c4d;
font-size: 1.1em;
font-weight: bold;
margin: 20px 0 10px 0;
}
.message-success {
color: #7ac0da;
font-size: 1.3em;
font-weight: bold;
margin: 20px 0 10px 0;
}
.error {
color: #e80c4d;
}
/* styles for validation helpers */
.field-validation-error {
color: #e80c4d;
font-weight: bold;
}
.field-validation-valid {
display: none;
}
input.input-validation-error {
border: 1px solid #e80c4d;
}
input[type="checkbox"].input-validation-error {
border: 0 none;
}
.validation-summary-errors {
color: #e80c4d;
font-weight: bold;
font-size: 1.1em;
}
.validation-summary-valid {
display: none;
}
/* tables
----------------------------------------------------------*/
table {
border-collapse: collapse;
border-spacing: 0;
margin-top: 0.75em;
border: 0 none;
}
th {
font-size: 1.2em;
text-align: left;
border: none 0px;
padding-left: 0;
}
th a {
display: block;
position: relative;
}
th a:link, th a:visited, th a:active, th a:hover {
color: #333;
font-weight: 600;
text-decoration: none;
padding: 0;
}
th a:hover {
color: #000;
}
th.asc a, th.desc a {
margin-right: .75em;
}
th.asc a:after, th.desc a:after {
display: block;
position: absolute;
right: 0em;
top: 0;
font-size: 0.75em;
}
th.asc a:after {
content: '▲';
}
th.desc a:after {
content: '▼';
}
td {
padding: 0.25em 2em 0.25em 0em;
border: 0 none;
}
tr.pager td {
padding: 0 0.25em 0 0;
}
/********************
* Mobile Styles *
********************/
@media only screen and (max-width: 850px) {
/* header
----------------------------------------------------------*/
header .float-left,
header .float-right {
float: none;
}
/* logo */
header .site-title {
margin: 10px;
text-align: center;
}
/* login */
#login {
font-size: .85em;
margin: 0 0 12px;
text-align: center;
}
#login ul {
margin: 5px 0;
padding: 0;
}
#login li {
display: inline;
list-style: none;
margin: 0;
padding: 0;
}
#login a {
background: none;
color: #999;
font-weight: 600;
margin: 2px;
padding: 0;
}
#login a:hover {
color: #333;
}
/* menu */
nav {
margin-bottom: 5px;
}
ul#menu {
margin: 0;
padding: 0;
text-align: center;
}
ul#menu li {
margin: 0;
padding: 0;
}
/* main layout
----------------------------------------------------------*/
.main-content,
.featured + .main-content {
background-position: 10px 0;
}
.content-wrapper {
padding-right: 10px;
padding-left: 10px;
}
.featured .content-wrapper {
padding: 10px;
}
/* page content */
article, aside {
float: none;
width: 100%;
}
/* ordered list */
ol.round {
list-style-type: none;
padding-left: 0;
}
ol.round li {
padding-left: 10px;
margin: 25px 0;
}
ol.round li.zero,
ol.round li.one,
ol.round li.two,
ol.round li.three,
ol.round li.four,
ol.round li.five,
ol.round li.six,
ol.round li.seven,
ol.round li.eight,
ol.round li.nine {
background: none;
}
/* features */
section.feature {
float: none;
padding: 10px;
width: auto;
}
section.feature img {
color: #999;
content: attr(alt);
font-size: 1.5em;
font-weight: 600;
}
/* forms */
input {
width: 90%;
}
/* login page */
#loginForm {
border-right: none;
float: none;
width: auto;
}
#loginForm .validation-error {
display: block;
margin-left: 15px;
}
#socialLoginForm {
margin-left: 0;
float: none;
width: auto;
}
/* footer
----------------------------------------------------------*/
footer .float-left,
footer .float-right {
float: none;
}
footer {
text-align: center;
height: auto;
padding: 10px 0;
}
footer p {
margin: 0;
}
}
/* END: Mobile Styles */
| {
"pile_set_name": "Github"
} |
accessing
getDefaultCogCodeSize
"Answer the default number of bytes to allocate for native code at startup.
The actual value can be set via vmParameterAt: and/or a preference in the ini file.
Subclasses may this default override to arrange that the code zone has about
the same number of methods as the x86 back-end at a similar point in execution."
<inline: true>
^1024 * 1024 | {
"pile_set_name": "Github"
} |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u09aa\u09c2\u09f0\u09cd\u09ac\u09be\u09b9\u09cd\u09a3",
"\u0985\u09aa\u09f0\u09be\u09b9\u09cd\u09a3"
],
"DAY": [
"\u09a6\u09c7\u0993\u09ac\u09be\u09f0",
"\u09b8\u09cb\u09ae\u09ac\u09be\u09f0",
"\u09ae\u0999\u09cd\u0997\u09b2\u09ac\u09be\u09f0",
"\u09ac\u09c1\u09a7\u09ac\u09be\u09f0",
"\u09ac\u09c3\u09b9\u09b7\u09cd\u09aa\u09a4\u09bf\u09ac\u09be\u09f0",
"\u09b6\u09c1\u0995\u09cd\u09f0\u09ac\u09be\u09f0",
"\u09b6\u09a8\u09bf\u09ac\u09be\u09f0"
],
"ERANAMES": [
"BCE",
"CE"
],
"ERAS": [
"BCE",
"CE"
],
"FIRSTDAYOFWEEK": 6,
"MONTH": [
"\u099c\u09be\u09a8\u09c1\u09f1\u09be\u09f0\u09c0",
"\u09ab\u09c7\u09ac\u09cd\u09f0\u09c1\u09f1\u09be\u09f0\u09c0",
"\u09ae\u09be\u09f0\u09cd\u099a",
"\u098f\u09aa\u09cd\u09f0\u09bf\u09b2",
"\u09ae\u09c7",
"\u099c\u09c1\u09a8",
"\u099c\u09c1\u09b2\u09be\u0987",
"\u0986\u0997\u09b7\u09cd\u099f",
"\u099b\u09c7\u09aa\u09cd\u09a4\u09c7\u09ae\u09cd\u09ac\u09f0",
"\u0985\u0995\u09cd\u099f\u09cb\u09ac\u09f0",
"\u09a8\u09f1\u09c7\u09ae\u09cd\u09ac\u09f0",
"\u09a1\u09bf\u099a\u09c7\u09ae\u09cd\u09ac\u09f0"
],
"SHORTDAY": [
"\u09f0\u09ac\u09bf",
"\u09b8\u09cb\u09ae",
"\u09ae\u0999\u09cd\u0997\u09b2",
"\u09ac\u09c1\u09a7",
"\u09ac\u09c3\u09b9\u09b7\u09cd\u09aa\u09a4\u09bf",
"\u09b6\u09c1\u0995\u09cd\u09f0",
"\u09b6\u09a8\u09bf"
],
"SHORTMONTH": [
"\u099c\u09be\u09a8\u09c1",
"\u09ab\u09c7\u09ac\u09cd\u09f0\u09c1",
"\u09ae\u09be\u09f0\u09cd\u099a",
"\u098f\u09aa\u09cd\u09f0\u09bf\u09b2",
"\u09ae\u09c7",
"\u099c\u09c1\u09a8",
"\u099c\u09c1\u09b2\u09be\u0987",
"\u0986\u0997",
"\u09b8\u09c7\u09aa\u09cd\u099f",
"\u0985\u0995\u09cd\u099f\u09cb",
"\u09a8\u09ad\u09c7",
"\u09a1\u09bf\u09b8\u09c7"
],
"STANDALONEMONTH": [
"\u099c\u09be\u09a8\u09c1\u09f1\u09be\u09f0\u09c0",
"\u09ab\u09c7\u09ac\u09cd\u09f0\u09c1\u09f1\u09be\u09f0\u09c0",
"\u09ae\u09be\u09f0\u09cd\u099a",
"\u098f\u09aa\u09cd\u09f0\u09bf\u09b2",
"\u09ae\u09c7",
"\u099c\u09c1\u09a8",
"\u099c\u09c1\u09b2\u09be\u0987",
"\u0986\u0997\u09b7\u09cd\u099f",
"\u099b\u09c7\u09aa\u09cd\u09a4\u09c7\u09ae\u09cd\u09ac\u09f0",
"\u0985\u0995\u09cd\u099f\u09cb\u09ac\u09f0",
"\u09a8\u09f1\u09c7\u09ae\u09cd\u09ac\u09f0",
"\u09a1\u09bf\u099a\u09c7\u09ae\u09cd\u09ac\u09f0"
],
"WEEKENDRANGE": [
6,
6
],
"fullDate": "y MMMM d, EEEE",
"longDate": "y MMMM d",
"medium": "y MMM d HH:mm:ss",
"mediumDate": "y MMM d",
"mediumTime": "HH:mm:ss",
"short": "y-MM-dd HH:mm",
"shortDate": "y-MM-dd",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20b9",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 2,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 2,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-\u00a4\u00a0",
"negSuf": "",
"posPre": "\u00a4\u00a0",
"posSuf": ""
}
]
},
"id": "as",
"localeID": "as",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
| {
"pile_set_name": "Github"
} |
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2017, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* <DESC>
* multi interface and debug callback
* </DESC>
*/
#include <stdio.h>
#include <string.h>
/* somewhat unix-specific */
#include <sys/time.h>
#include <unistd.h>
/* curl stuff */
#include <curl/curl.h>
typedef char bool;
#define TRUE 1
static
void dump(const char *text,
FILE *stream, unsigned char *ptr, size_t size,
bool nohex)
{
size_t i;
size_t c;
unsigned int width = 0x10;
if(nohex)
/* without the hex output, we can fit more on screen */
width = 0x40;
fprintf(stream, "%s, %10.10lu bytes (0x%8.8lx)\n",
text, (unsigned long)size, (unsigned long)size);
for(i = 0; i<size; i += width) {
fprintf(stream, "%4.4lx: ", (unsigned long)i);
if(!nohex) {
/* hex not disabled, show it */
for(c = 0; c < width; c++)
if(i + c < size)
fprintf(stream, "%02x ", ptr[i + c]);
else
fputs(" ", stream);
}
for(c = 0; (c < width) && (i + c < size); c++) {
/* check for 0D0A; if found, skip past and start a new line of output */
if(nohex && (i + c + 1 < size) && ptr[i + c] == 0x0D &&
ptr[i + c + 1] == 0x0A) {
i += (c + 2 - width);
break;
}
fprintf(stream, "%c",
(ptr[i + c] >= 0x20) && (ptr[i + c]<0x80)?ptr[i + c]:'.');
/* check again for 0D0A, to avoid an extra \n if it's at width */
if(nohex && (i + c + 2 < size) && ptr[i + c + 1] == 0x0D &&
ptr[i + c + 2] == 0x0A) {
i += (c + 3 - width);
break;
}
}
fputc('\n', stream); /* newline */
}
fflush(stream);
}
static
int my_trace(CURL *handle, curl_infotype type,
unsigned char *data, size_t size,
void *userp)
{
const char *text;
(void)userp;
(void)handle; /* prevent compiler warning */
switch(type) {
case CURLINFO_TEXT:
fprintf(stderr, "== Info: %s", data);
/* FALLTHROUGH */
default: /* in case a new one is introduced to shock us */
return 0;
case CURLINFO_HEADER_OUT:
text = "=> Send header";
break;
case CURLINFO_DATA_OUT:
text = "=> Send data";
break;
case CURLINFO_HEADER_IN:
text = "<= Recv header";
break;
case CURLINFO_DATA_IN:
text = "<= Recv data";
break;
}
dump(text, stderr, data, size, TRUE);
return 0;
}
/*
* Simply download a HTTP file.
*/
int main(void)
{
CURL *http_handle;
CURLM *multi_handle;
int still_running; /* keep number of running handles */
http_handle = curl_easy_init();
/* set the options (I left out a few, you'll get the point anyway) */
curl_easy_setopt(http_handle, CURLOPT_URL, "http://www.example.com/");
curl_easy_setopt(http_handle, CURLOPT_DEBUGFUNCTION, my_trace);
curl_easy_setopt(http_handle, CURLOPT_VERBOSE, 1L);
/* init a multi stack */
multi_handle = curl_multi_init();
/* add the individual transfers */
curl_multi_add_handle(multi_handle, http_handle);
/* we start some action by calling perform right away */
curl_multi_perform(multi_handle, &still_running);
do {
struct timeval timeout;
int rc; /* select() return code */
CURLMcode mc; /* curl_multi_fdset() return code */
fd_set fdread;
fd_set fdwrite;
fd_set fdexcep;
int maxfd = -1;
long curl_timeo = -1;
FD_ZERO(&fdread);
FD_ZERO(&fdwrite);
FD_ZERO(&fdexcep);
/* set a suitable timeout to play around with */
timeout.tv_sec = 1;
timeout.tv_usec = 0;
curl_multi_timeout(multi_handle, &curl_timeo);
if(curl_timeo >= 0) {
timeout.tv_sec = curl_timeo / 1000;
if(timeout.tv_sec > 1)
timeout.tv_sec = 1;
else
timeout.tv_usec = (curl_timeo % 1000) * 1000;
}
/* get file descriptors from the transfers */
mc = curl_multi_fdset(multi_handle, &fdread, &fdwrite, &fdexcep, &maxfd);
if(mc != CURLM_OK) {
fprintf(stderr, "curl_multi_fdset() failed, code %d.\n", mc);
break;
}
/* On success the value of maxfd is guaranteed to be >= -1. We call
select(maxfd + 1, ...); specially in case of (maxfd == -1) there are
no fds ready yet so we call select(0, ...) --or Sleep() on Windows--
to sleep 100ms, which is the minimum suggested value in the
curl_multi_fdset() doc. */
if(maxfd == -1) {
#ifdef _WIN32
Sleep(100);
rc = 0;
#else
/* Portable sleep for platforms other than Windows. */
struct timeval wait = { 0, 100 * 1000 }; /* 100ms */
rc = select(0, NULL, NULL, NULL, &wait);
#endif
}
else {
/* Note that on some platforms 'timeout' may be modified by select().
If you need access to the original value save a copy beforehand. */
rc = select(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout);
}
switch(rc) {
case -1:
/* select error */
still_running = 0;
printf("select() returns error, this is badness\n");
break;
case 0:
default:
/* timeout or readable/writable sockets */
curl_multi_perform(multi_handle, &still_running);
break;
}
} while(still_running);
curl_multi_cleanup(multi_handle);
curl_easy_cleanup(http_handle);
return 0;
}
| {
"pile_set_name": "Github"
} |
{
"_args": [
[
"clone@^1.0.0",
"/www/a/node_modules/vinyl"
]
],
"_from": "clone@>=1.0.0 <2.0.0",
"_id": "[email protected]",
"_inCache": true,
"_installable": true,
"_location": "/clone",
"_npmUser": {
"email": "[email protected]",
"name": "pvorb"
},
"_npmVersion": "1.4.14",
"_phantomChildren": {},
"_requested": {
"name": "clone",
"raw": "clone@^1.0.0",
"rawSpec": "^1.0.0",
"scope": null,
"spec": ">=1.0.0 <2.0.0",
"type": "range"
},
"_requiredBy": [
"/defaults",
"/vinyl"
],
"_resolved": "https://registry.npmjs.org/clone/-/clone-1.0.2.tgz",
"_shasum": "260b7a99ebb1edfe247538175f783243cb19d149",
"_shrinkwrap": null,
"_spec": "clone@^1.0.0",
"_where": "/www/a/node_modules/vinyl",
"author": {
"email": "[email protected]",
"name": "Paul Vorbach",
"url": "http://paul.vorba.ch/"
},
"bugs": {
"url": "https://github.com/pvorb/node-clone/issues"
},
"contributors": [
{
"name": "Dustin Diaz",
"url": "http://dustindiaz.com"
},
{
"name": "Blake Miner",
"email": "[email protected]",
"url": "http://www.blakeminer.com/"
},
{
"name": "George Stagas",
"email": "[email protected]",
"url": "http://stagas.com/"
},
{
"name": "Tobiasz Cudnik",
"email": "[email protected]",
"url": "https://github.com/TobiaszCudnik"
},
{
"name": "Pavel Lang",
"email": "[email protected]",
"url": "https://github.com/langpavel"
},
{
"name": "Dan MacTough",
"url": "http://yabfog.com/"
},
{
"name": "w1nk",
"url": "https://github.com/w1nk"
},
{
"name": "Hugh Kennedy",
"url": "http://twitter.com/hughskennedy"
},
{
"name": "Tian You",
"email": "[email protected]",
"url": "http://blog.axqd.net/"
},
{
"name": "Ilya Shaisultanov",
"url": "https://github.com/diversario"
},
{
"name": "Nathan MacInnes",
"email": "[email protected]",
"url": "http://macinn.es/"
},
{
"name": "Benjamin E. Coe",
"email": "[email protected]",
"url": "https://twitter.com/benjamincoe"
},
{
"name": "Nathan Zadoks",
"url": "https://github.com/nathan7"
},
{
"name": "Róbert Oroszi",
"email": "[email protected]",
"url": "https://github.com/oroce"
},
{
"name": "Aurélio A. Heckert",
"url": "http://softwarelivre.org/aurium"
},
{
"name": "Guy Ellis",
"url": "http://www.guyellisrocks.com/"
}
],
"dependencies": {},
"description": "deep cloning of objects and arrays",
"devDependencies": {
"nodeunit": "~0.9.0"
},
"directories": {},
"dist": {
"shasum": "260b7a99ebb1edfe247538175f783243cb19d149",
"tarball": "https://registry.npmjs.org/clone/-/clone-1.0.2.tgz"
},
"engines": {
"node": ">=0.8"
},
"gitHead": "0e8216efc672496b612fd7ab62159117d16ec4a0",
"homepage": "https://github.com/pvorb/node-clone",
"license": "MIT",
"main": "clone.js",
"maintainers": [
{
"name": "pvorb",
"email": "[email protected]"
}
],
"name": "clone",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/pvorb/node-clone.git"
},
"scripts": {
"test": "nodeunit test.js"
},
"tags": [
"array",
"clone",
"date",
"function",
"object"
],
"version": "1.0.2"
}
| {
"pile_set_name": "Github"
} |
//
// NamespaceStrategy.cpp
//
// Library: XML
// Package: XML
// Module: NamespaceStrategy
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/XML/NamespaceStrategy.h"
#include "Poco/SAX/AttributesImpl.h"
#include "Poco/SAX/ContentHandler.h"
#include "Poco/XML/XMLException.h"
#include "Poco/XML/Name.h"
namespace Poco {
namespace XML {
const XMLString NamespaceStrategy::NOTHING;
NamespaceStrategy::~NamespaceStrategy()
{
}
void NamespaceStrategy::splitName(const XMLChar* qname, XMLString& uri, XMLString& localName)
{
for (const XMLChar* p = qname; *p; ++p)
{
if (*p == '\t')
{
uri.assign(qname, p - qname);
localName.assign(p + 1);
return;
}
}
localName = qname;
}
void NamespaceStrategy::splitName(const XMLChar* qname, XMLString& uri, XMLString& localName, XMLString& prefix)
{
const XMLChar* p = qname;
while (*p && *p != '\t') ++p;
if (*p)
{
uri.assign(qname, p - qname);
++p;
const XMLChar* loc = p;
while (*p && *p != '\t') ++p;
localName.assign(loc, p - loc);
if (*p)
prefix.assign(++p);
else
prefix.assign(XML_LIT(""));
}
else
{
uri.assign(XML_LIT(""));
localName = qname;
prefix.assign(XML_LIT(""));
}
}
NoNamespacesStrategy::NoNamespacesStrategy()
{
_attrs.reserve(32);
}
NoNamespacesStrategy::~NoNamespacesStrategy()
{
}
void NoNamespacesStrategy::startElement(const XMLChar* name, const XMLChar** atts, int specifiedCount, ContentHandler* pContentHandler)
{
poco_assert_dbg (name && atts && pContentHandler);
_attrs.clear();
for (int i = 0; *atts; ++i)
{
AttributesImpl::Attribute& attr = _attrs.addAttribute();
attr.qname.assign(*atts++);
attr.value.assign(*atts++);
attr.specified = i < specifiedCount;
}
_name.assign(name);
pContentHandler->startElement(NOTHING, NOTHING, _name, _attrs);
}
void NoNamespacesStrategy::endElement(const XMLChar* name, ContentHandler* pContentHandler)
{
poco_assert_dbg (name && pContentHandler);
_name.assign(name);
pContentHandler->endElement(NOTHING, NOTHING, _name);
}
NoNamespacePrefixesStrategy::NoNamespacePrefixesStrategy()
{
_attrs.reserve(32);
}
NoNamespacePrefixesStrategy::~NoNamespacePrefixesStrategy()
{
}
void NoNamespacePrefixesStrategy::startElement(const XMLChar* name, const XMLChar** atts, int specifiedCount, ContentHandler* pContentHandler)
{
poco_assert_dbg (name && atts && pContentHandler);
_attrs.clear();
for (int i = 0; *atts; ++i)
{
const XMLChar* attrName = *atts++;
const XMLChar* attrValue = *atts++;
AttributesImpl::Attribute& attr = _attrs.addAttribute();
splitName(attrName, attr.namespaceURI, attr.localName);
attr.value.assign(attrValue);
attr.specified = i < specifiedCount;
}
splitName(name, _uri, _local);
pContentHandler->startElement(_uri, _local, NOTHING, _attrs);
}
void NoNamespacePrefixesStrategy::endElement(const XMLChar* name, ContentHandler* pContentHandler)
{
poco_assert_dbg (name && pContentHandler);
splitName(name, _uri, _local);
pContentHandler->endElement(_uri, _local, NOTHING);
}
NamespacePrefixesStrategy::NamespacePrefixesStrategy()
{
_attrs.reserve(32);
}
NamespacePrefixesStrategy::~NamespacePrefixesStrategy()
{
}
void NamespacePrefixesStrategy::startElement(const XMLChar* name, const XMLChar** atts, int specifiedCount, ContentHandler* pContentHandler)
{
poco_assert_dbg (name && atts && pContentHandler);
_attrs.clear();
for (int i = 0; *atts; ++i)
{
const XMLChar* attrName = *atts++;
const XMLChar* attrValue = *atts++;
AttributesImpl::Attribute& attr = _attrs.addAttribute();
splitName(attrName, attr.namespaceURI, attr.localName, attr.qname);
if (!attr.qname.empty()) attr.qname += ':';
attr.qname.append(attr.localName);
attr.value.assign(attrValue);
attr.specified = i < specifiedCount;
}
splitName(name, _uri, _local, _qname);
if (!_qname.empty()) _qname += ':';
_qname.append(_local);
pContentHandler->startElement(_uri, _local, _qname, _attrs);
}
void NamespacePrefixesStrategy::endElement(const XMLChar* name, ContentHandler* pContentHandler)
{
poco_assert_dbg (name && pContentHandler);
splitName(name, _uri, _local, _qname);
if (!_qname.empty()) _qname += ':';
_qname.append(_local);
pContentHandler->endElement(_uri, _local, _qname);
}
} } // namespace Poco::XML
| {
"pile_set_name": "Github"
} |
changelog:
- type: FIX
description: Fix an issue with consul EDS where error were sent to a closed channel.
issueLink: https://github.com/solo-io/gloo/issues/2736 | {
"pile_set_name": "Github"
} |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_PUBSUB_PUBLISHER_CONNECTION_H
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_PUBSUB_PUBLISHER_CONNECTION_H
#include "google/cloud/pubsub/backoff_policy.h"
#include "google/cloud/pubsub/connection_options.h"
#include "google/cloud/pubsub/internal/publisher_stub.h"
#include "google/cloud/pubsub/message.h"
#include "google/cloud/pubsub/publisher_options.h"
#include "google/cloud/pubsub/retry_policy.h"
#include "google/cloud/pubsub/topic.h"
#include "google/cloud/pubsub/version.h"
#include "google/cloud/future.h"
#include "google/cloud/status_or.h"
namespace google {
namespace cloud {
namespace pubsub {
inline namespace GOOGLE_CLOUD_CPP_PUBSUB_NS {
/**
* A connection to the Cloud Pub/Sub service to publish events.
*
* This interface defines pure-virtual methods for each of the user-facing
* overload sets in `Publisher`. That is, all of `Publisher`'s overloads will
* forward to the one pure-virtual method declared in this interface. This
* allows users to inject custom behavior (e.g., with a Google Mock object) in a
* `Publisher` object for use in their own tests.
*
* To create a concrete instance that connects you to the real Cloud Pub/Sub
* service, see `MakePublisherConnection()`.
*/
class PublisherConnection {
public:
virtual ~PublisherConnection() = 0;
//@{
/**
* @name The parameter wrapper types.
*
* Define the arguments for each member function.
*
* Applications may define classes derived from `PublisherConnection`, for
* example, because they want to mock the class. To avoid breaking all such
* derived classes when we change the number or type of the arguments to the
* member functions we define light weight structures to pass the arguments.
*/
/// Wrap the arguments for `Publish()`
struct PublishParams {
Message message;
};
/// Wrap the arguments for `Flush()`
struct FlushParams {};
//@}
/// Defines the interface for `Publisher::Publish()`
virtual future<StatusOr<std::string>> Publish(PublishParams p) = 0;
/// Defines the interface for `Publisher::Flush()`
virtual void Flush(FlushParams) = 0;
};
/**
* Returns a `PublisherConnection` object to work with Cloud Pub/Sub publisher
* APIs.
*
* The `PublisherConnection` class is not intended for direct use in
* applications, it is provided for applications wanting to mock the
* `PublisherClient` behavior in their tests.
*
* @see `PublisherConnection`
*
* @param topic the Cloud Pub/Sub topic used by the returned
* `PublisherConnection`.
* @param options configure the batching policy and other parameters in the
* returned connection.
* @param connection_options (optional) general configuration for this
* connection, this type is also used to configure `pubsub::Subscriber`.
* @param retry_policy (optional) configure the retry loop. This is only used
* if `retry_publish_failures()` is enabled in @p options.
* @param backoff_policy (optional) configure the backoff period between
* retries. This is only used if `retry_publish_failures()` is enabled in
* @p options.
*/
std::shared_ptr<PublisherConnection> MakePublisherConnection(
Topic topic, PublisherOptions options,
ConnectionOptions connection_options = {},
std::unique_ptr<RetryPolicy const> retry_policy = {},
std::unique_ptr<BackoffPolicy const> backoff_policy = {});
} // namespace GOOGLE_CLOUD_CPP_PUBSUB_NS
} // namespace pubsub
namespace pubsub_internal {
inline namespace GOOGLE_CLOUD_CPP_PUBSUB_NS {
std::shared_ptr<pubsub::PublisherConnection> MakePublisherConnection(
pubsub::Topic topic, pubsub::PublisherOptions options,
pubsub::ConnectionOptions connection_options,
std::shared_ptr<PublisherStub> stub,
std::unique_ptr<pubsub::RetryPolicy const> retry_policy,
std::unique_ptr<pubsub::BackoffPolicy const> backoff_policy);
} // namespace GOOGLE_CLOUD_CPP_PUBSUB_NS
} // namespace pubsub_internal
} // namespace cloud
} // namespace google
#endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_PUBSUB_PUBLISHER_CONNECTION_H
| {
"pile_set_name": "Github"
} |
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="128dp"
android:height="128dp"
android:viewportWidth="34"
android:viewportHeight="34">
<path
android:pathData="m33.87,16.93c0,9.35 -7.58,16.93 -16.93,16.93C7.58,33.87 0,26.29 0,16.93 0,7.58 7.58,0 16.93,0c9.35,0 16.93,7.58 16.93,16.93"
android:fillColor="#ffdd55"/>
<path
android:pathData="m30.69,17.46c0,7.6 -6.16,13.76 -13.76,13.76 -7.6,0 -13.76,-6.16 -13.76,-13.76 0,-7.6 6.16,-13.76 13.76,-13.76 7.6,0 13.76,6.16 13.76,13.76"
android:fillAlpha="0.2"
android:fillColor="#000"/>
<path
android:pathData="m30.16,16.4c0,7.31 -5.92,13.23 -13.23,13.23 -7.31,0 -13.23,-5.92 -13.23,-13.23 0,-7.31 5.92,-13.23 13.23,-13.23 7.31,0 13.23,5.92 13.23,13.23"
android:strokeColor="#fff"
android:fillColor="#c84747"
android:strokeWidth="1"/>
<path
android:pathData="M16.93,16.4m-9.46,0a9.46,9.46 0,1 1,18.92 0a9.46,9.46 0,1 1,-18.92 0"
android:fillColor="#fff"/>
<path
android:pathData="m16.93,9.52a2.12,2.12 0,0 0,-2.12 2.12,2.12 2.12,0 0,0 0.29,1.06h-1.34l-3.17,8.47h12.7l-3.17,-8.47h-1.35a2.12,2.12 0,0 0,0.29 -1.06,2.12 2.12,0 0,0 -2.12,-2.12zM16.93,10.58a1.06,1.06 0,0 1,1.06 1.06,1.06 1.06,0 0,1 -1.06,1.06 1.06,1.06 0,0 1,-1.06 -1.06,1.06 1.06,0 0,1 1.06,-1.06z"
android:fillColor="#444"/>
<path
android:pathData="m17.2,14.29v1.06h1.32v1.06h-1.32l-0.01,1.59c-0,0.2 0.03,0.34 0.1,0.41 0.08,0.07 0.21,0.13 0.44,0.12l0.52,-0.01v1.06l-1.05,-0.01c-0.54,-0.01 -0.84,-0.03 -1.06,-0.25 -0.22,-0.22 -0.26,-0.78 -0.26,-1.32l-0,-1.59h-0.79v-1.06h0.79v-1.06z"
android:fillColor="#fff"/>
</vector>
| {
"pile_set_name": "Github"
} |
Spring Data - Redis Twitter Example
===================================
An improved Java implementation of the [Redis Twitter Clone](https://redis.io/topics/twitter-clone) using Spring Data. Tutorial available [here](https://docs.spring.io/spring-data/data-keyvalue/examples/retwisj/current/)
Build
-----
The project creates a WAR file suitable for deployment in a Servlet 2.5 container (such as Tomcat). It uses [Gradle](https://gradle.org/) as a build system.
Simply type:
gradlew build
or if you have gradle installed on your machine and in your classpath:
gradle build
Start up an instance of the redis server, deploy your WAR and point your browser to (for the typical setup) [http://localhost:8080/retwisj](http://localhost:8080/retwisj) | {
"pile_set_name": "Github"
} |
var mkdirp = require('../');
var path = require('path');
var fs = require('fs');
var test = require('tap').test;
test('woo', function (t) {
t.plan(2);
var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var file = '/tmp/' + [x,y,z].join('/');
mkdirp(file, 0755, function (err) {
if (err) t.fail(err);
else path.exists(file, function (ex) {
if (!ex) t.fail('file not created')
else fs.stat(file, function (err, stat) {
if (err) t.fail(err)
else {
t.equal(stat.mode & 0777, 0755);
t.ok(stat.isDirectory(), 'target not a directory');
t.end();
}
})
})
});
});
| {
"pile_set_name": "Github"
} |
#if !defined(BOOST_PP_IS_ITERATING)
///// header body
#ifndef BOOST_MPL_AUX_FULL_LAMBDA_HPP_INCLUDED
#define BOOST_MPL_AUX_FULL_LAMBDA_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2001-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: full_lambda.hpp 49267 2008-10-11 06:19:02Z agurtovoy $
// $Date: 2008-10-10 23:19:02 -0700 (Fri, 10 Oct 2008) $
// $Revision: 49267 $
#if !defined(BOOST_MPL_PREPROCESSING_MODE)
# include <boost/mpl/lambda_fwd.hpp>
# include <boost/mpl/bind_fwd.hpp>
# include <boost/mpl/protect.hpp>
# include <boost/mpl/quote.hpp>
# include <boost/mpl/arg.hpp>
# include <boost/mpl/bool.hpp>
# include <boost/mpl/int_fwd.hpp>
# include <boost/mpl/aux_/template_arity.hpp>
# include <boost/mpl/aux_/na_spec.hpp>
# include <boost/mpl/aux_/config/ttp.hpp>
# if defined(BOOST_MPL_CFG_EXTENDED_TEMPLATE_PARAMETERS_MATCHING)
# include <boost/mpl/if.hpp>
# endif
#endif
#include <boost/mpl/aux_/lambda_arity_param.hpp>
#include <boost/mpl/aux_/config/use_preprocessed.hpp>
#if !defined(BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS) \
&& !defined(BOOST_MPL_PREPROCESSING_MODE)
# define BOOST_MPL_PREPROCESSED_HEADER full_lambda.hpp
# include <boost/mpl/aux_/include_preprocessed.hpp>
#else
# include <boost/mpl/limits/arity.hpp>
# include <boost/mpl/aux_/preprocessor/default_params.hpp>
# include <boost/mpl/aux_/preprocessor/params.hpp>
# include <boost/mpl/aux_/preprocessor/enum.hpp>
# include <boost/mpl/aux_/preprocessor/repeat.hpp>
# include <boost/mpl/aux_/config/dmc_ambiguous_ctps.hpp>
# include <boost/preprocessor/iterate.hpp>
# include <boost/preprocessor/comma_if.hpp>
# include <boost/preprocessor/inc.hpp>
# include <boost/preprocessor/cat.hpp>
namespace boost { namespace mpl {
// local macros, #undef-ined at the end of the header
# define AUX778076_LAMBDA_PARAMS(i_, param) \
BOOST_MPL_PP_PARAMS(i_, param) \
/**/
# define AUX778076_BIND_PARAMS(param) \
BOOST_MPL_PP_PARAMS( \
BOOST_MPL_LIMIT_METAFUNCTION_ARITY \
, param \
) \
/**/
# define AUX778076_BIND_N_PARAMS(i_, param) \
BOOST_PP_COMMA_IF(i_) \
BOOST_MPL_PP_PARAMS(i_, param) \
/**/
# define AUX778076_ARITY_PARAM(param) \
BOOST_MPL_AUX_LAMBDA_ARITY_PARAM(param) \
/**/
#define n_ BOOST_MPL_LIMIT_METAFUNCTION_ARITY
namespace aux {
template<
BOOST_MPL_PP_DEFAULT_PARAMS(n_,bool C,false)
>
struct lambda_or
: true_
{
};
template<>
struct lambda_or< BOOST_MPL_PP_ENUM(n_,false) >
: false_
{
};
} // namespace aux
#undef n_
template<
typename T
, typename Tag
AUX778076_ARITY_PARAM(typename Arity)
>
struct lambda
{
typedef false_ is_le;
typedef T result_;
typedef T type;
};
template<
typename T
>
struct is_lambda_expression
: lambda<T>::is_le
{
};
template< int N, typename Tag >
struct lambda< arg<N>,Tag AUX778076_ARITY_PARAM(int_<-1>) >
{
typedef true_ is_le;
typedef mpl::arg<N> result_; // qualified for the sake of MIPSpro 7.41
typedef mpl::protect<result_> type;
};
#define BOOST_PP_ITERATION_PARAMS_1 \
(3,(0, BOOST_MPL_LIMIT_METAFUNCTION_ARITY, <boost/mpl/aux_/full_lambda.hpp>))
#include BOOST_PP_ITERATE()
/// special case for 'protect'
template< typename T, typename Tag >
struct lambda< mpl::protect<T>,Tag AUX778076_ARITY_PARAM(int_<1>) >
{
typedef false_ is_le;
typedef mpl::protect<T> result_;
typedef result_ type;
};
/// specializations for the main 'bind' form
template<
typename F, AUX778076_BIND_PARAMS(typename T)
, typename Tag
>
struct lambda<
bind<F,AUX778076_BIND_PARAMS(T)>
, Tag
AUX778076_ARITY_PARAM(int_<BOOST_PP_INC(BOOST_MPL_LIMIT_METAFUNCTION_ARITY)>)
>
{
typedef false_ is_le;
typedef bind<F, AUX778076_BIND_PARAMS(T)> result_;
typedef result_ type;
};
#if defined(BOOST_MPL_CFG_EXTENDED_TEMPLATE_PARAMETERS_MATCHING)
template<
typename F
, typename Tag1
, typename Tag2
, typename Arity
>
struct lambda<
lambda<F,Tag1,Arity>
, Tag2
, int_<3>
>
{
typedef lambda< F,Tag2 > l1;
typedef lambda< Tag1,Tag2 > l2;
typedef typename l1::is_le is_le;
typedef bind1< quote1<aux::template_arity>, typename l1::result_ > arity_;
typedef lambda< typename if_<is_le,arity_,Arity>::type,Tag2 > l3;
typedef aux::le_result3<is_le, Tag2, mpl::lambda, l1, l2, l3> le_result_;
typedef typename le_result_::result_ result_;
typedef typename le_result_::type type;
};
#elif !defined(BOOST_MPL_CFG_DMC_AMBIGUOUS_CTPS)
/// workaround for MWCW 8.3+/EDG < 303, leads to ambiguity on Digital Mars
template<
typename F, typename Tag1, typename Tag2
>
struct lambda<
lambda< F,Tag1 >
, Tag2
>
{
typedef lambda< F,Tag2 > l1;
typedef lambda< Tag1,Tag2 > l2;
typedef typename l1::is_le is_le;
typedef aux::le_result2<is_le, Tag2, mpl::lambda, l1, l2> le_result_;
typedef typename le_result_::result_ result_;
typedef typename le_result_::type type;
};
#endif
# undef AUX778076_ARITY_PARAM
# undef AUX778076_BIND_N_PARAMS
# undef AUX778076_BIND_PARAMS
# undef AUX778076_LAMBDA_PARAMS
#if !defined(BOOST_MPL_CFG_EXTENDED_TEMPLATE_PARAMETERS_MATCHING)
BOOST_MPL_AUX_NA_SPEC(2, lambda)
#else
BOOST_MPL_AUX_NA_SPEC2(2, 3, lambda)
#endif
}}
#endif // BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS
#endif // BOOST_MPL_AUX_FULL_LAMBDA_HPP_INCLUDED
///// iteration, depth == 1
// For gcc 4.4 compatability, we must include the
// BOOST_PP_ITERATION_DEPTH test inside an #else clause.
#else // BOOST_PP_IS_ITERATING
#if BOOST_PP_ITERATION_DEPTH() == 1
#define i_ BOOST_PP_FRAME_ITERATION(1)
#if i_ > 0
namespace aux {
# define AUX778076_RESULT(unused, i_, T) \
BOOST_PP_COMMA_IF(i_) \
typename BOOST_PP_CAT(T, BOOST_PP_INC(i_))::result_ \
/**/
# define AUX778076_TYPE(unused, i_, T) \
BOOST_PP_COMMA_IF(i_) \
typename BOOST_PP_CAT(T, BOOST_PP_INC(i_))::type \
/**/
template<
typename IsLE, typename Tag
, template< AUX778076_LAMBDA_PARAMS(i_, typename P) > class F
, AUX778076_LAMBDA_PARAMS(i_, typename L)
>
struct BOOST_PP_CAT(le_result,i_)
{
typedef F<
BOOST_MPL_PP_REPEAT(i_, AUX778076_TYPE, L)
> result_;
typedef result_ type;
};
template<
typename Tag
, template< AUX778076_LAMBDA_PARAMS(i_, typename P) > class F
, AUX778076_LAMBDA_PARAMS(i_, typename L)
>
struct BOOST_PP_CAT(le_result,i_)< true_,Tag,F,AUX778076_LAMBDA_PARAMS(i_, L) >
{
typedef BOOST_PP_CAT(bind,i_)<
BOOST_PP_CAT(quote,i_)<F,Tag>
, BOOST_MPL_PP_REPEAT(i_, AUX778076_RESULT, L)
> result_;
typedef mpl::protect<result_> type;
};
# undef AUX778076_TYPE
# undef AUX778076_RESULT
} // namespace aux
# define AUX778076_LAMBDA_TYPEDEF(unused, i_, T) \
typedef lambda< BOOST_PP_CAT(T, BOOST_PP_INC(i_)), Tag > \
BOOST_PP_CAT(l,BOOST_PP_INC(i_)); \
/**/
# define AUX778076_IS_LE_TYPEDEF(unused, i_, unused2) \
typedef typename BOOST_PP_CAT(l,BOOST_PP_INC(i_))::is_le \
BOOST_PP_CAT(is_le,BOOST_PP_INC(i_)); \
/**/
# define AUX778076_IS_LAMBDA_EXPR(unused, i_, unused2) \
BOOST_PP_COMMA_IF(i_) \
BOOST_PP_CAT(is_le,BOOST_PP_INC(i_))::value \
/**/
template<
template< AUX778076_LAMBDA_PARAMS(i_, typename P) > class F
, AUX778076_LAMBDA_PARAMS(i_, typename T)
, typename Tag
>
struct lambda<
F<AUX778076_LAMBDA_PARAMS(i_, T)>
, Tag
AUX778076_ARITY_PARAM(int_<i_>)
>
{
BOOST_MPL_PP_REPEAT(i_, AUX778076_LAMBDA_TYPEDEF, T)
BOOST_MPL_PP_REPEAT(i_, AUX778076_IS_LE_TYPEDEF, unused)
typedef typename aux::lambda_or<
BOOST_MPL_PP_REPEAT(i_, AUX778076_IS_LAMBDA_EXPR, unused)
>::type is_le;
typedef aux::BOOST_PP_CAT(le_result,i_)<
is_le, Tag, F, AUX778076_LAMBDA_PARAMS(i_, l)
> le_result_;
typedef typename le_result_::result_ result_;
typedef typename le_result_::type type;
};
# undef AUX778076_IS_LAMBDA_EXPR
# undef AUX778076_IS_LE_TYPEDEF
# undef AUX778076_LAMBDA_TYPEDEF
#endif // i_ > 0
template<
typename F AUX778076_BIND_N_PARAMS(i_, typename T)
, typename Tag
>
struct lambda<
BOOST_PP_CAT(bind,i_)<F AUX778076_BIND_N_PARAMS(i_, T)>
, Tag
AUX778076_ARITY_PARAM(int_<BOOST_PP_INC(i_)>)
>
{
typedef false_ is_le;
typedef BOOST_PP_CAT(bind,i_)<
F
AUX778076_BIND_N_PARAMS(i_, T)
> result_;
typedef result_ type;
};
#undef i_
#endif // BOOST_PP_ITERATION_DEPTH()
#endif // BOOST_PP_IS_ITERATING
| {
"pile_set_name": "Github"
} |
import random
import time
from threading import Thread, Lock as ThreadingLock
from traceback import format_exc
import pytest
from ..helpers import daemonize
from ..platform import get_process_id, process_alive
from ..locking import TimeoutTimer, ExclusiveLock, Lock, LockRoster, \
ADD, REMOVE, SHARED, EXCLUSIVE, LockTimeout, NotLocked, NotMyLock
ID1 = "foo", 1, 1
ID2 = "bar", 2, 2
RACE_TEST_NUM_THREADS = 40
RACE_TEST_DURATION = 0.4 # seconds
@pytest.fixture()
def free_pid():
"""Return a free PID not used by any process (naturally this is racy)"""
host, pid, tid = get_process_id()
while True:
# PIDs are often restricted to a small range. On Linux the range >32k is by default not used.
pid = random.randint(33000, 65000)
if not process_alive(host, pid, tid):
return pid
class TestTimeoutTimer:
def test_timeout(self):
timeout = 0.5
t = TimeoutTimer(timeout).start()
assert not t.timed_out()
time.sleep(timeout * 1.5)
assert t.timed_out()
def test_notimeout_sleep(self):
timeout, sleep = None, 0.5
t = TimeoutTimer(timeout, sleep).start()
assert not t.timed_out_or_sleep()
assert time.time() >= t.start_time + 1 * sleep
assert not t.timed_out_or_sleep()
assert time.time() >= t.start_time + 2 * sleep
@pytest.fixture()
def lockpath(tmpdir):
return str(tmpdir.join('lock'))
class TestExclusiveLock:
def test_checks(self, lockpath):
with ExclusiveLock(lockpath, timeout=1) as lock:
assert lock.is_locked() and lock.by_me()
def test_acquire_break_reacquire(self, lockpath):
lock = ExclusiveLock(lockpath, id=ID1).acquire()
lock.break_lock()
with ExclusiveLock(lockpath, id=ID2):
pass
def test_timeout(self, lockpath):
with ExclusiveLock(lockpath, id=ID1):
with pytest.raises(LockTimeout):
ExclusiveLock(lockpath, id=ID2, timeout=0.1).acquire()
def test_kill_stale(self, lockpath, free_pid):
host, pid, tid = our_id = get_process_id()
dead_id = host, free_pid, tid
cant_know_if_dead_id = 'foo.bar.example.net', 1, 2
dead_lock = ExclusiveLock(lockpath, id=dead_id).acquire()
with ExclusiveLock(lockpath, id=our_id):
with pytest.raises(NotMyLock):
dead_lock.release()
with pytest.raises(NotLocked):
dead_lock.release()
with ExclusiveLock(lockpath, id=cant_know_if_dead_id):
with pytest.raises(LockTimeout):
ExclusiveLock(lockpath, id=our_id, timeout=0.1).acquire()
def test_migrate_lock(self, lockpath):
old_id, new_id = ID1, ID2
assert old_id[1] != new_id[1] # different PIDs (like when doing daemonize())
lock = ExclusiveLock(lockpath, id=old_id).acquire()
assert lock.id == old_id # lock is for old id / PID
old_unique_name = lock.unique_name
assert lock.by_me() # we have the lock
lock.migrate_lock(old_id, new_id) # fix the lock
assert lock.id == new_id # lock corresponds to the new id / PID
new_unique_name = lock.unique_name
assert lock.by_me() # we still have the lock
assert old_unique_name != new_unique_name # locking filename is different now
def test_race_condition(self, lockpath):
class SynchronizedCounter:
def __init__(self, count=0):
self.lock = ThreadingLock()
self.count = count
self.maxcount = count
def value(self):
with self.lock:
return self.count
def maxvalue(self):
with self.lock:
return self.maxcount
def incr(self):
with self.lock:
self.count += 1
if self.count > self.maxcount:
self.maxcount = self.count
return self.count
def decr(self):
with self.lock:
self.count -= 1
return self.count
def print_locked(msg):
with print_lock:
print(msg)
def acquire_release_loop(id, timeout, thread_id, lock_owner_counter, exception_counter, print_lock, last_thread=None):
print_locked("Thread %2d: Starting acquire_release_loop(id=%s, timeout=%d); lockpath=%s" % (thread_id, id, timeout, lockpath))
timer = TimeoutTimer(timeout, -1).start()
cycle = 0
while not timer.timed_out():
cycle += 1
try:
with ExclusiveLock(lockpath, id=id, timeout=timeout/20, sleep=-1): # This timeout is only for not exceeding the given timeout by more than 5%. With sleep<0 it's constantly polling anyway.
lock_owner_count = lock_owner_counter.incr()
print_locked("Thread %2d: Acquired the lock. It's my %d. loop cycle. I am the %d. who has the lock concurrently." % (thread_id, cycle, lock_owner_count))
time.sleep(0.005)
lock_owner_count = lock_owner_counter.decr()
print_locked("Thread %2d: Releasing the lock, finishing my %d. loop cycle. Currently, %d colleagues still have the lock." % (thread_id, cycle, lock_owner_count))
except LockTimeout:
print_locked("Thread %2d: Got LockTimeout, finishing my %d. loop cycle." % (thread_id, cycle))
except:
exception_count = exception_counter.incr()
e = format_exc()
print_locked("Thread %2d: Exception thrown, finishing my %d. loop cycle. It's the %d. exception seen until now: %s" % (thread_id, cycle, exception_count, e))
print_locked("Thread %2d: Loop timed out--terminating after %d loop cycles." % (thread_id, cycle))
if last_thread is not None: # joining its predecessor, if any
last_thread.join()
print('')
lock_owner_counter = SynchronizedCounter()
exception_counter = SynchronizedCounter()
print_lock = ThreadingLock()
thread = None
for thread_id in range(RACE_TEST_NUM_THREADS):
thread = Thread(target=acquire_release_loop, args=(('foo', thread_id, 0), RACE_TEST_DURATION, thread_id, lock_owner_counter, exception_counter, print_lock, thread))
thread.start()
thread.join() # joining the last thread
assert lock_owner_counter.maxvalue() > 0, 'Never gained the lock? Something went wrong here...'
assert lock_owner_counter.maxvalue() <= 1, "Maximal number of concurrent lock holders was %d. So exclusivity is broken." % (lock_owner_counter.maxvalue())
assert exception_counter.value() == 0, "ExclusiveLock threw %d exceptions due to unclean concurrency handling." % (exception_counter.value())
class TestLock:
def test_shared(self, lockpath):
lock1 = Lock(lockpath, exclusive=False, id=ID1).acquire()
lock2 = Lock(lockpath, exclusive=False, id=ID2).acquire()
assert len(lock1._roster.get(SHARED)) == 2
assert len(lock1._roster.get(EXCLUSIVE)) == 0
assert not lock1._roster.empty(SHARED, EXCLUSIVE)
assert lock1._roster.empty(EXCLUSIVE)
lock1.release()
lock2.release()
def test_exclusive(self, lockpath):
with Lock(lockpath, exclusive=True, id=ID1) as lock:
assert len(lock._roster.get(SHARED)) == 0
assert len(lock._roster.get(EXCLUSIVE)) == 1
assert not lock._roster.empty(SHARED, EXCLUSIVE)
def test_upgrade(self, lockpath):
with Lock(lockpath, exclusive=False) as lock:
lock.upgrade()
lock.upgrade() # NOP
assert len(lock._roster.get(SHARED)) == 0
assert len(lock._roster.get(EXCLUSIVE)) == 1
assert not lock._roster.empty(SHARED, EXCLUSIVE)
def test_downgrade(self, lockpath):
with Lock(lockpath, exclusive=True) as lock:
lock.downgrade()
lock.downgrade() # NOP
assert len(lock._roster.get(SHARED)) == 1
assert len(lock._roster.get(EXCLUSIVE)) == 0
def test_got_exclusive_lock(self, lockpath):
lock = Lock(lockpath, exclusive=True, id=ID1)
assert not lock.got_exclusive_lock()
lock.acquire()
assert lock.got_exclusive_lock()
lock.release()
assert not lock.got_exclusive_lock()
def test_break(self, lockpath):
lock = Lock(lockpath, exclusive=True, id=ID1).acquire()
lock.break_lock()
assert len(lock._roster.get(SHARED)) == 0
assert len(lock._roster.get(EXCLUSIVE)) == 0
with Lock(lockpath, exclusive=True, id=ID2):
pass
def test_timeout(self, lockpath):
with Lock(lockpath, exclusive=False, id=ID1):
with pytest.raises(LockTimeout):
Lock(lockpath, exclusive=True, id=ID2, timeout=0.1).acquire()
with Lock(lockpath, exclusive=True, id=ID1):
with pytest.raises(LockTimeout):
Lock(lockpath, exclusive=False, id=ID2, timeout=0.1).acquire()
with Lock(lockpath, exclusive=True, id=ID1):
with pytest.raises(LockTimeout):
Lock(lockpath, exclusive=True, id=ID2, timeout=0.1).acquire()
def test_kill_stale(self, lockpath, free_pid):
host, pid, tid = our_id = get_process_id()
dead_id = host, free_pid, tid
cant_know_if_dead_id = 'foo.bar.example.net', 1, 2
dead_lock = Lock(lockpath, id=dead_id, exclusive=True).acquire()
roster = dead_lock._roster
with Lock(lockpath, id=our_id):
assert roster.get(EXCLUSIVE) == set()
assert roster.get(SHARED) == {our_id}
assert roster.get(EXCLUSIVE) == set()
assert roster.get(SHARED) == set()
with pytest.raises(KeyError):
dead_lock.release()
with Lock(lockpath, id=cant_know_if_dead_id, exclusive=True):
with pytest.raises(LockTimeout):
Lock(lockpath, id=our_id, timeout=0.1).acquire()
def test_migrate_lock(self, lockpath):
old_id, new_id = ID1, ID2
assert old_id[1] != new_id[1] # different PIDs (like when doing daemonize())
lock = Lock(lockpath, id=old_id, exclusive=True).acquire()
assert lock.id == old_id
lock.migrate_lock(old_id, new_id) # fix the lock
assert lock.id == new_id
lock.release()
lock = Lock(lockpath, id=old_id, exclusive=False).acquire()
assert lock.id == old_id
lock.migrate_lock(old_id, new_id) # fix the lock
assert lock.id == new_id
lock.release()
@pytest.fixture()
def rosterpath(tmpdir):
return str(tmpdir.join('roster'))
class TestLockRoster:
def test_empty(self, rosterpath):
roster = LockRoster(rosterpath)
empty = roster.load()
roster.save(empty)
assert empty == {}
def test_modify_get(self, rosterpath):
roster1 = LockRoster(rosterpath, id=ID1)
assert roster1.get(SHARED) == set()
roster1.modify(SHARED, ADD)
assert roster1.get(SHARED) == {ID1, }
roster2 = LockRoster(rosterpath, id=ID2)
roster2.modify(SHARED, ADD)
assert roster2.get(SHARED) == {ID1, ID2, }
roster1 = LockRoster(rosterpath, id=ID1)
roster1.modify(SHARED, REMOVE)
assert roster1.get(SHARED) == {ID2, }
roster2 = LockRoster(rosterpath, id=ID2)
roster2.modify(SHARED, REMOVE)
assert roster2.get(SHARED) == set()
def test_kill_stale(self, rosterpath, free_pid):
host, pid, tid = our_id = get_process_id()
dead_id = host, free_pid, tid
# put a dead local process lock into roster
roster1 = LockRoster(rosterpath, id=dead_id)
roster1.kill_stale_locks = False
assert roster1.get(SHARED) == set()
roster1.modify(SHARED, ADD)
assert roster1.get(SHARED) == {dead_id}
# put a unknown-state remote process lock into roster
cant_know_if_dead_id = 'foo.bar.example.net', 1, 2
roster1 = LockRoster(rosterpath, id=cant_know_if_dead_id)
roster1.kill_stale_locks = False
assert roster1.get(SHARED) == {dead_id}
roster1.modify(SHARED, ADD)
assert roster1.get(SHARED) == {dead_id, cant_know_if_dead_id}
killer_roster = LockRoster(rosterpath)
# Active kill_stale_locks here - does it kill the dead_id lock?
assert killer_roster.get(SHARED) == {cant_know_if_dead_id}
killer_roster.modify(SHARED, ADD)
assert killer_roster.get(SHARED) == {our_id, cant_know_if_dead_id}
other_killer_roster = LockRoster(rosterpath)
# Active kill_stale_locks here - must not kill our_id lock since we're alive.
assert other_killer_roster.get(SHARED) == {our_id, cant_know_if_dead_id}
def test_migrate_lock(self, rosterpath):
old_id, new_id = ID1, ID2
assert old_id[1] != new_id[1] # different PIDs (like when doing daemonize())
roster = LockRoster(rosterpath, id=old_id)
assert roster.id == old_id
roster.modify(SHARED, ADD)
assert roster.get(SHARED) == {old_id}
roster.migrate_lock(SHARED, old_id, new_id) # fix the lock
assert roster.id == new_id
assert roster.get(SHARED) == {new_id}
| {
"pile_set_name": "Github"
} |
/*
* Socket.h
*
* Created on: Apr 22, 2012
* Author: lion
*/
#include "ifs/Socket.h"
#include "inetAddr.h"
#include "AsyncIO.h"
#include "Timer.h"
#ifndef SOCKET_H_
#define SOCKET_H_
namespace fibjs {
class Socket : public Socket_base {
FIBER_FREE();
public:
Socket()
: m_aio(INVALID_SOCKET, net_base::_AF_INET, net_base::_SOCK_STREAM)
, m_timeout(0)
#ifdef _WIN32
, m_bBind(FALSE)
#endif
{
}
Socket(SOCKET s, int32_t family, int32_t type)
: m_aio(s, family, type)
, m_timeout(0)
#ifdef _WIN32
, m_bBind(FALSE)
#endif
{
}
virtual ~Socket();
public:
// object_base
virtual result_t unbind(obj_ptr<object_base>& retVal);
public:
// Stream_base
virtual result_t read(int32_t bytes, obj_ptr<Buffer_base>& retVal,
AsyncEvent* ac);
virtual result_t write(Buffer_base* data, AsyncEvent* ac);
virtual result_t flush(AsyncEvent* ac);
virtual result_t close(AsyncEvent* ac);
virtual result_t copyTo(Stream_base* stm, int64_t bytes, int64_t& retVal, AsyncEvent* ac);
public:
// Socket_base
virtual result_t get_family(int32_t& retVal);
virtual result_t get_type(int32_t& retVal);
virtual result_t get_remoteAddress(exlib::string& retVal);
virtual result_t get_remotePort(int32_t& retVal);
virtual result_t get_localAddress(exlib::string& retVal);
virtual result_t get_localPort(int32_t& retVal);
virtual result_t get_timeout(int32_t& retVal);
virtual result_t set_timeout(int32_t newVal);
virtual result_t connect(exlib::string host, int32_t port, AsyncEvent* ac);
virtual result_t bind(exlib::string addr, int32_t port, bool allowIPv4);
virtual result_t bind(int32_t port, bool allowIPv4);
virtual result_t listen(int32_t backlog);
virtual result_t accept(obj_ptr<Socket_base>& retVal, AsyncEvent* ac);
virtual result_t recv(int32_t bytes, obj_ptr<Buffer_base>& retVal, AsyncEvent* ac);
virtual result_t recvfrom(int32_t bytes, obj_ptr<NObject>& retVal, AsyncEvent* ac);
virtual result_t send(Buffer_base* data, AsyncEvent* ac);
virtual result_t sendto(Buffer_base* data, exlib::string host, int32_t port, AsyncEvent* ac);
public:
result_t create(int32_t family, int32_t type);
private:
class IOTimer : public Timer {
public:
IOTimer(int32_t timeout, Socket_base* sock)
: Timer(timeout)
, m_sock(sock)
{
}
public:
virtual void on_timer()
{
m_sock->cc_close();
}
private:
obj_ptr<Socket_base> m_sock;
};
private:
AsyncIO m_aio;
int32_t m_timeout;
#ifdef _WIN32
BOOL m_bBind;
#endif
friend class AsyncIO;
};
}
#endif /* SOCKET_H_ */
| {
"pile_set_name": "Github"
} |
neg_byref_8.fs(2,31,2,35): typecheck error FS0412: A type instantiation involves a byref type. This is not permitted by the rules of Common IL.
neg_byref_8.fs(2,31,2,35): typecheck error FS0412: A type instantiation involves a byref type. This is not permitted by the rules of Common IL.
neg_byref_8.fs(2,38,2,43): typecheck error FS0412: A type instantiation involves a byref type. This is not permitted by the rules of Common IL.
neg_byref_8.fs(2,38,2,43): typecheck error FS0412: A type instantiation involves a byref type. This is not permitted by the rules of Common IL.
neg_byref_8.fs(2,39,2,40): typecheck error FS0418: The byref typed value 'v' cannot be used at this point
neg_byref_8.fs(2,42,2,43): typecheck error FS0418: The byref typed value 'v' cannot be used at this point
neg_byref_8.fs(2,47,2,60): typecheck error FS0412: A type instantiation involves a byref type. This is not permitted by the rules of Common IL.
neg_byref_8.fs(2,47,2,60): typecheck error FS0412: A type instantiation involves a byref type. This is not permitted by the rules of Common IL.
neg_byref_8.fs(2,47,2,53): typecheck error FS0412: A type instantiation involves a byref type. This is not permitted by the rules of Common IL.
neg_byref_8.fs(2,47,2,53): typecheck error FS0412: A type instantiation involves a byref type. This is not permitted by the rules of Common IL.
neg_byref_8.fs(2,47,2,53): typecheck error FS0412: A type instantiation involves a byref type. This is not permitted by the rules of Common IL.
neg_byref_8.fs(2,47,2,53): typecheck error FS0412: A type instantiation involves a byref type. This is not permitted by the rules of Common IL.
| {
"pile_set_name": "Github"
} |
# Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers!
| {
"pile_set_name": "Github"
} |
// Copyright 2017 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#ifdef _WIN32
#include <winsock2.h>
#else
#include <arpa/inet.h>
#endif
#include <cstring>
#include <string>
#include "network/packet.h"
namespace Network {
#ifndef htonll
u64 htonll(u64 x) {
return ((1 == htonl(1)) ? (x) : ((uint64_t)htonl((x)&0xFFFFFFFF) << 32) | htonl((x) >> 32));
}
#endif
#ifndef ntohll
u64 ntohll(u64 x) {
return ((1 == ntohl(1)) ? (x) : ((uint64_t)ntohl((x)&0xFFFFFFFF) << 32) | ntohl((x) >> 32));
}
#endif
void Packet::Append(const void* in_data, std::size_t size_in_bytes) {
if (in_data && (size_in_bytes > 0)) {
std::size_t start = data.size();
data.resize(start + size_in_bytes);
std::memcpy(&data[start], in_data, size_in_bytes);
}
}
void Packet::Read(void* out_data, std::size_t size_in_bytes) {
if (out_data && CheckSize(size_in_bytes)) {
std::memcpy(out_data, &data[read_pos], size_in_bytes);
read_pos += size_in_bytes;
}
}
void Packet::Clear() {
data.clear();
read_pos = 0;
is_valid = true;
}
const void* Packet::GetData() const {
return !data.empty() ? &data[0] : nullptr;
}
void Packet::IgnoreBytes(u32 length) {
read_pos += length;
}
std::size_t Packet::GetDataSize() const {
return data.size();
}
bool Packet::EndOfPacket() const {
return read_pos >= data.size();
}
Packet::operator bool() const {
return is_valid;
}
Packet& Packet::operator>>(bool& out_data) {
u8 value;
if (*this >> value) {
out_data = (value != 0);
}
return *this;
}
Packet& Packet::operator>>(s8& out_data) {
Read(&out_data, sizeof(out_data));
return *this;
}
Packet& Packet::operator>>(u8& out_data) {
Read(&out_data, sizeof(out_data));
return *this;
}
Packet& Packet::operator>>(s16& out_data) {
s16 value;
Read(&value, sizeof(value));
out_data = ntohs(value);
return *this;
}
Packet& Packet::operator>>(u16& out_data) {
u16 value;
Read(&value, sizeof(value));
out_data = ntohs(value);
return *this;
}
Packet& Packet::operator>>(s32& out_data) {
s32 value;
Read(&value, sizeof(value));
out_data = ntohl(value);
return *this;
}
Packet& Packet::operator>>(u32& out_data) {
u32 value;
Read(&value, sizeof(value));
out_data = ntohl(value);
return *this;
}
Packet& Packet::operator>>(s64& out_data) {
s64 value;
Read(&value, sizeof(value));
out_data = ntohll(value);
return *this;
}
Packet& Packet::operator>>(u64& out_data) {
u64 value;
Read(&value, sizeof(value));
out_data = ntohll(value);
return *this;
}
Packet& Packet::operator>>(float& out_data) {
Read(&out_data, sizeof(out_data));
return *this;
}
Packet& Packet::operator>>(double& out_data) {
Read(&out_data, sizeof(out_data));
return *this;
}
Packet& Packet::operator>>(char* out_data) {
// First extract string length
u32 length = 0;
*this >> length;
if ((length > 0) && CheckSize(length)) {
// Then extract characters
std::memcpy(out_data, &data[read_pos], length);
out_data[length] = '\0';
// Update reading position
read_pos += length;
}
return *this;
}
Packet& Packet::operator>>(std::string& out_data) {
// First extract string length
u32 length = 0;
*this >> length;
out_data.clear();
if ((length > 0) && CheckSize(length)) {
// Then extract characters
out_data.assign(&data[read_pos], length);
// Update reading position
read_pos += length;
}
return *this;
}
Packet& Packet::operator<<(bool in_data) {
*this << static_cast<u8>(in_data);
return *this;
}
Packet& Packet::operator<<(s8 in_data) {
Append(&in_data, sizeof(in_data));
return *this;
}
Packet& Packet::operator<<(u8 in_data) {
Append(&in_data, sizeof(in_data));
return *this;
}
Packet& Packet::operator<<(s16 in_data) {
s16 toWrite = htons(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::operator<<(u16 in_data) {
u16 toWrite = htons(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::operator<<(s32 in_data) {
s32 toWrite = htonl(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::operator<<(u32 in_data) {
u32 toWrite = htonl(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::operator<<(s64 in_data) {
s64 toWrite = htonll(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::operator<<(u64 in_data) {
u64 toWrite = htonll(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::operator<<(float in_data) {
Append(&in_data, sizeof(in_data));
return *this;
}
Packet& Packet::operator<<(double in_data) {
Append(&in_data, sizeof(in_data));
return *this;
}
Packet& Packet::operator<<(const char* in_data) {
// First insert string length
u32 length = static_cast<u32>(std::strlen(in_data));
*this << length;
// Then insert characters
Append(in_data, length * sizeof(char));
return *this;
}
Packet& Packet::operator<<(const std::string& in_data) {
// First insert string length
u32 length = static_cast<u32>(in_data.size());
*this << length;
// Then insert characters
if (length > 0)
Append(in_data.c_str(), length * sizeof(std::string::value_type));
return *this;
}
bool Packet::CheckSize(std::size_t size) {
is_valid = is_valid && (read_pos + size <= data.size());
return is_valid;
}
} // namespace Network
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <Foundation/NSHashTable.h>
#import <Foundation/NSSecureCoding-Protocol.h>
__attribute__((visibility("hidden")))
@interface NSConcreteHashTable : NSHashTable <NSSecureCoding>
{
struct NSSlice slice;
unsigned long long count;
unsigned long long capacity;
unsigned long long options;
unsigned long long mutations;
}
+ (BOOL)supportsSecureCoding;
- (id)objectEnumerator;
- (id)description;
- (void)dealloc;
- (void)getKeys:(const void **)arg1 count:(unsigned long long *)arg2;
- (id)allObjects;
- (void)removeAllItems;
- (void)removeItem:(const void *)arg1;
- (void)insertKnownAbsentItem:(const void *)arg1;
- (void)addObject:(id)arg1;
- (void)insertItem:(const void *)arg1;
- (void *)getItem:(const void *)arg1;
- (void)rehash;
- (void)assign:(unsigned long long)arg1 key:(const void *)arg2;
- (void)hashGrow;
- (unsigned long long)rehashAround:(unsigned long long)arg1;
- (void)raiseCountUnderflowException;
- (BOOL)isEqual:(id)arg1;
- (unsigned long long)hash;
- (unsigned long long)count;
- (unsigned long long)countByEnumeratingWithState:(CDStruct_70511ce9 *)arg1 objects:(id *)arg2 count:(unsigned long long)arg3;
- (id)pointerFunctions;
- (void)encodeWithCoder:(id)arg1;
- (id)initWithCoder:(id)arg1;
- (id)initWithPointerFunctions:(id)arg1 capacity:(unsigned long long)arg2;
- (id)initWithOptions:(unsigned long long)arg1 capacity:(unsigned long long)arg2;
- (id)copy;
- (id)init;
@end
| {
"pile_set_name": "Github"
} |
#!/bin/bash
function t0011 {
FUSE_MD5=$(md5sum $TMP_FILE | cut -d\ -f1)
}
function t0011-check {
[ "$FUSE_MD5" = "$FILE_MD5" ]
}
set -e
source `dirname $0`/lib.sh
e4test_make_LOGFILE
e4test_make_FS 1024
e4test_make_MOUNTPOINT
e4test_mount
TMP_FILE=$MOUNTPOINT/bigfile
dd if=/dev/urandom of=$TMP_FILE.0 bs=1024 count=1024 &> /dev/null
for i in `seq 1 9` ; do
cat $TMP_FILE.$(($i - 1)) $TMP_FILE.$(($i - 1)) >> $TMP_FILE.$i
rm $TMP_FILE.$(($i - 1))
done
mv $TMP_FILE.9 $TMP_FILE
FILE_MD5=`md5sum $TMP_FILE | cut -d\ -f1`
e4test_umount
# Check the md5 after mount using fuse
e4test_fuse_mount
e4test_run t0011
e4test_fuse_umount
rm $FS
e4test_end t0011-check
| {
"pile_set_name": "Github"
} |
var inherits = require('inherits');
var Buffer = require('buffer').Buffer;
var DERDecoder = require('./der');
function PEMDecoder(entity) {
DERDecoder.call(this, entity);
this.enc = 'pem';
};
inherits(PEMDecoder, DERDecoder);
module.exports = PEMDecoder;
PEMDecoder.prototype.decode = function decode(data, options) {
var lines = data.toString().split(/[\r\n]+/g);
var label = options.label.toUpperCase();
var re = /^-----(BEGIN|END) ([^-]+)-----$/;
var start = -1;
var end = -1;
for (var i = 0; i < lines.length; i++) {
var match = lines[i].match(re);
if (match === null)
continue;
if (match[2] !== label)
continue;
if (start === -1) {
if (match[1] !== 'BEGIN')
break;
start = i;
} else {
if (match[1] !== 'END')
break;
end = i;
break;
}
}
if (start === -1 || end === -1)
throw new Error('PEM section not found for: ' + label);
var base64 = lines.slice(start + 1, end).join('');
// Remove excessive symbols
base64.replace(/[^a-z0-9\+\/=]+/gi, '');
var input = new Buffer(base64, 'base64');
return DERDecoder.prototype.decode.call(this, input, options);
};
| {
"pile_set_name": "Github"
} |
<?php
namespace GuzzleHttp\Promise;
/**
* A promise represents the eventual result of an asynchronous operation.
*
* The primary way of interacting with a promise is through its then method,
* which registers callbacks to receive either a promise’s eventual value or
* the reason why the promise cannot be fulfilled.
*
* @link https://promisesaplus.com/
*/
interface PromiseInterface
{
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
/**
* Appends fulfillment and rejection handlers to the promise, and returns
* a new promise resolving to the return value of the called handler.
*
* @param callable $onFulfilled Invoked when the promise fulfills.
* @param callable $onRejected Invoked when the promise is rejected.
*
* @return PromiseInterface
*/
public function then(
callable $onFulfilled = null,
callable $onRejected = null
);
/**
* Appends a rejection handler callback to the promise, and returns a new
* promise resolving to the return value of the callback if it is called,
* or to its original fulfillment value if the promise is instead
* fulfilled.
*
* @param callable $onRejected Invoked when the promise is rejected.
*
* @return PromiseInterface
*/
public function otherwise(callable $onRejected);
/**
* Get the state of the promise ("pending", "rejected", or "fulfilled").
*
* The three states can be checked against the constants defined on
* PromiseInterface: PENDING, FULFILLED, and REJECTED.
*
* @return string
*/
public function getState();
/**
* Resolve the promise with the given value.
*
* @param mixed $value
* @throws \RuntimeException if the promise is already resolved.
*/
public function resolve($value);
/**
* Reject the promise with the given reason.
*
* @param mixed $reason
* @throws \RuntimeException if the promise is already resolved.
*/
public function reject($reason);
/**
* Cancels the promise if possible.
*
* @link https://github.com/promises-aplus/cancellation-spec/issues/7
*/
public function cancel();
/**
* Waits until the promise completes if possible.
*
* Pass $unwrap as true to unwrap the result of the promise, either
* returning the resolved value or throwing the rejected exception.
*
* If the promise cannot be waited on, then the promise will be rejected.
*
* @param bool $unwrap
*
* @return mixed
* @throws \LogicException if the promise has no wait function or if the
* promise does not settle after waiting.
*/
public function wait($unwrap = true);
}
| {
"pile_set_name": "Github"
} |
package org.getopentest.selenium;
import java.util.regex.Pattern;
import org.getopentest.selenium.core.CustomConditions;
import org.getopentest.selenium.core.SeleniumTestAction;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
public class AssertAttributeValue extends SeleniumTestAction {
@Override
public void run() {
super.run();
By locator = this.readLocatorArgument("locator");
String attribute = this.readStringArgument("attribute");
String attributeValue = this.readStringArgument("value", null);
String valueContains = this.readStringArgument("valueContains", null);
Pattern valueMatches = this.readRegexArgument("valueMatches", null);
boolean caseInsensitive = this.readBooleanArgument("caseInsensitive", false);
this.waitForAsyncCallsToFinish();
WebElement element = this.getElement(locator);
WebDriverWait wait = new WebDriverWait(this.driver, this.getExplicitWaitSec());
try {
if (attributeValue != null) {
wait.until(CustomConditions.elementAttributeToBe(element, attribute, attributeValue, caseInsensitive));
} else if (valueContains != null) {
wait.until(CustomConditions.elementAttributeToContain(element, attribute, valueContains, caseInsensitive));
} else if (valueMatches != null) {
wait.until(CustomConditions.elementAttributeToMatch(element, attribute, valueMatches));
} else {
throw new RuntimeException(
"You must provide at least one of the following arguments: "
+ "text, textContains, textMatches.");
}
} catch (Exception ex) {
throw new RuntimeException(String.format(
"Failed to validate the value of attribute \"%s\". The attribute's value was \"%s\".",
attribute,
element.getAttribute(attribute)), ex);
}
}
}
| {
"pile_set_name": "Github"
} |
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "[email protected]",
"scale" : "2x"
},
{
"idiom" : "universal",
"filename" : "[email protected]",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
} | {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2002 - 2003
* NetGroup, Politecnico di Torino (Italy)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Politecnico di Torino nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef __RPCAPD_H__
#define __RPCAPD_H__
#define PROGRAM_NAME "rpcapd"
#define SOCKET_MAXCONN 10 /* Maximum number of connections queued into the accept() */
#ifdef _WIN32
void send_shutdown_notification(void); // Send notification to shut down the daemon
void send_reread_configuration_notification(void); // Send notification to re-read the configuration file
#endif
void main_startup(void);
#endif
| {
"pile_set_name": "Github"
} |
/*
* cb_pcidas.c
* Developed by Ivan Martinez and Frank Mori Hess, with valuable help from
* David Schleef and the rest of the Comedi developers comunity.
*
* Copyright (C) 2001-2003 Ivan Martinez <[email protected]>
* Copyright (C) 2001,2002 Frank Mori Hess <[email protected]>
*
* COMEDI - Linux Control and Measurement Device Interface
* Copyright (C) 1997-8 David A. Schleef <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
/*
* Driver: cb_pcidas
* Description: MeasurementComputing PCI-DAS series
* with the AMCC S5933 PCI controller
* Devices: [Measurement Computing] PCI-DAS1602/16 (cb_pcidas),
* PCI-DAS1602/16jr, PCI-DAS1602/12, PCI-DAS1200, PCI-DAS1200jr,
* PCI-DAS1000, PCI-DAS1001, PCI_DAS1002
* Author: Ivan Martinez <[email protected]>,
* Frank Mori Hess <[email protected]>
* Updated: 2003-3-11
*
* Status:
* There are many reports of the driver being used with most of the
* supported cards. Despite no detailed log is maintained, it can
* be said that the driver is quite tested and stable.
*
* The boards may be autocalibrated using the comedi_calibrate
* utility.
*
* Configuration options: not applicable, uses PCI auto config
*
* For commands, the scanned channels must be consecutive
* (i.e. 4-5-6-7, 2-3-4,...), and must all have the same
* range and aref.
*
* AI Triggering:
* For start_src == TRIG_EXT, the A/D EXTERNAL TRIGGER IN (pin 45) is used.
* For 1602 series, the start_arg is interpreted as follows:
* start_arg == 0 => gated trigger (level high)
* start_arg == CR_INVERT => gated trigger (level low)
* start_arg == CR_EDGE => Rising edge
* start_arg == CR_EDGE | CR_INVERT => Falling edge
* For the other boards the trigger will be done on rising edge
*/
/*
* TODO:
* analog triggering on 1602 series
*/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include "../comedi_pci.h"
#include "comedi_8254.h"
#include "8255.h"
#include "amcc_s5933.h"
#define AI_BUFFER_SIZE 1024 /* max ai fifo size */
#define AO_BUFFER_SIZE 1024 /* max ao fifo size */
/*
* PCI BAR1 Register map (devpriv->pcibar1)
*/
#define PCIDAS_CTRL_REG 0x00 /* INTERRUPT / ADC FIFO register */
#define PCIDAS_CTRL_INT(x) (((x) & 0x3) << 0)
#define PCIDAS_CTRL_INT_NONE PCIDAS_CTRL_INT(0) /* no int selected */
#define PCIDAS_CTRL_INT_EOS PCIDAS_CTRL_INT(1) /* int on end of scan */
#define PCIDAS_CTRL_INT_FHF PCIDAS_CTRL_INT(2) /* int on fifo half full */
#define PCIDAS_CTRL_INT_FNE PCIDAS_CTRL_INT(3) /* int on fifo not empty */
#define PCIDAS_CTRL_INT_MASK PCIDAS_CTRL_INT(3) /* mask of int select bits */
#define PCIDAS_CTRL_INTE BIT(2) /* int enable */
#define PCIDAS_CTRL_DAHFIE BIT(3) /* dac half full int enable */
#define PCIDAS_CTRL_EOAIE BIT(4) /* end of acq. int enable */
#define PCIDAS_CTRL_DAHFI BIT(5) /* dac half full status / clear */
#define PCIDAS_CTRL_EOAI BIT(6) /* end of acq. int status / clear */
#define PCIDAS_CTRL_INT_CLR BIT(7) /* int status / clear */
#define PCIDAS_CTRL_EOBI BIT(9) /* end of burst int status */
#define PCIDAS_CTRL_ADHFI BIT(10) /* half-full int status */
#define PCIDAS_CTRL_ADNEI BIT(11) /* fifo not empty int status (latch) */
#define PCIDAS_CTRL_ADNE BIT(12) /* fifo not empty status (realtime) */
#define PCIDAS_CTRL_DAEMIE BIT(12) /* dac empty int enable */
#define PCIDAS_CTRL_LADFUL BIT(13) /* fifo overflow / clear */
#define PCIDAS_CTRL_DAEMI BIT(14) /* dac fifo empty int status / clear */
#define PCIDAS_CTRL_AI_INT (PCIDAS_CTRL_EOAI | PCIDAS_CTRL_EOBI | \
PCIDAS_CTRL_ADHFI | PCIDAS_CTRL_ADNEI | \
PCIDAS_CTRL_LADFUL)
#define PCIDAS_CTRL_AO_INT (PCIDAS_CTRL_DAHFI | PCIDAS_CTRL_DAEMI)
#define PCIDAS_AI_REG 0x02 /* ADC CHANNEL MUX AND CONTROL reg */
#define PCIDAS_AI_FIRST(x) ((x) & 0xf)
#define PCIDAS_AI_LAST(x) (((x) & 0xf) << 4)
#define PCIDAS_AI_CHAN(x) (PCIDAS_AI_FIRST(x) | PCIDAS_AI_LAST(x))
#define PCIDAS_AI_GAIN(x) (((x) & 0x3) << 8)
#define PCIDAS_AI_SE BIT(10) /* Inputs in single-ended mode */
#define PCIDAS_AI_UNIP BIT(11) /* Analog front-end unipolar mode */
#define PCIDAS_AI_PACER(x) (((x) & 0x3) << 12)
#define PCIDAS_AI_PACER_SW PCIDAS_AI_PACER(0) /* software pacer */
#define PCIDAS_AI_PACER_INT PCIDAS_AI_PACER(1) /* int. pacer */
#define PCIDAS_AI_PACER_EXTN PCIDAS_AI_PACER(2) /* ext. falling edge */
#define PCIDAS_AI_PACER_EXTP PCIDAS_AI_PACER(3) /* ext. rising edge */
#define PCIDAS_AI_PACER_MASK PCIDAS_AI_PACER(3) /* pacer source bits */
#define PCIDAS_AI_EOC BIT(14) /* adc not busy */
#define PCIDAS_TRIG_REG 0x04 /* TRIGGER CONTROL/STATUS register */
#define PCIDAS_TRIG_SEL(x) (((x) & 0x3) << 0)
#define PCIDAS_TRIG_SEL_NONE PCIDAS_TRIG_SEL(0) /* no start trigger */
#define PCIDAS_TRIG_SEL_SW PCIDAS_TRIG_SEL(1) /* software start trigger */
#define PCIDAS_TRIG_SEL_EXT PCIDAS_TRIG_SEL(2) /* ext. start trigger */
#define PCIDAS_TRIG_SEL_ANALOG PCIDAS_TRIG_SEL(3) /* ext. analog trigger */
#define PCIDAS_TRIG_SEL_MASK PCIDAS_TRIG_SEL(3) /* start trigger mask */
#define PCIDAS_TRIG_POL BIT(2) /* invert trigger (1602 only) */
#define PCIDAS_TRIG_MODE BIT(3) /* edge/level trigerred (1602 only) */
#define PCIDAS_TRIG_EN BIT(4) /* enable external start trigger */
#define PCIDAS_TRIG_BURSTE BIT(5) /* burst mode enable */
#define PCIDAS_TRIG_CLR BIT(7) /* clear external trigger */
#define PCIDAS_CALIB_REG 0x06 /* CALIBRATION register */
#define PCIDAS_CALIB_8800_SEL BIT(8) /* select 8800 caldac */
#define PCIDAS_CALIB_TRIM_SEL BIT(9) /* select ad7376 trim pot */
#define PCIDAS_CALIB_DAC08_SEL BIT(10) /* select dac08 caldac */
#define PCIDAS_CALIB_SRC(x) (((x) & 0x7) << 11)
#define PCIDAS_CALIB_EN BIT(14) /* calibration source enable */
#define PCIDAS_CALIB_DATA BIT(15) /* serial data bit going to caldac */
#define PCIDAS_AO_REG 0x08 /* dac control and status register */
#define PCIDAS_AO_EMPTY BIT(0) /* fifo empty, write clear (1602) */
#define PCIDAS_AO_DACEN BIT(1) /* dac enable */
#define PCIDAS_AO_START BIT(2) /* start/arm fifo (1602) */
#define PCIDAS_AO_PACER(x) (((x) & 0x3) << 3) /* (1602) */
#define PCIDAS_AO_PACER_SW PCIDAS_AO_PACER(0) /* software pacer */
#define PCIDAS_AO_PACER_INT PCIDAS_AO_PACER(1) /* int. pacer */
#define PCIDAS_AO_PACER_EXTN PCIDAS_AO_PACER(2) /* ext. falling edge */
#define PCIDAS_AO_PACER_EXTP PCIDAS_AO_PACER(3) /* ext. rising edge */
#define PCIDAS_AO_PACER_MASK PCIDAS_AO_PACER(3) /* pacer source bits */
#define PCIDAS_AO_CHAN_EN(c) BIT(5 + ((c) & 0x1))
#define PCIDAS_AO_CHAN_MASK (PCIDAS_AO_CHAN_EN(0) | PCIDAS_AO_CHAN_EN(1))
#define PCIDAS_AO_UPDATE_BOTH BIT(7) /* update both dacs */
#define PCIDAS_AO_RANGE(c, r) (((r) & 0x3) << (8 + 2 * ((c) & 0x1)))
#define PCIDAS_AO_RANGE_MASK(c) PCIDAS_AO_RANGE((c), 0x3)
/*
* PCI BAR2 Register map (devpriv->pcibar2)
*/
#define PCIDAS_AI_DATA_REG 0x00
#define PCIDAS_AI_FIFO_CLR_REG 0x02
/*
* PCI BAR3 Register map (dev->iobase)
*/
#define PCIDAS_AI_8254_BASE 0x00
#define PCIDAS_8255_BASE 0x04
#define PCIDAS_AO_8254_BASE 0x08
/*
* PCI BAR4 Register map (devpriv->pcibar4)
*/
#define PCIDAS_AO_DATA_REG(x) (0x00 + ((x) * 2))
#define PCIDAS_AO_FIFO_REG 0x00
#define PCIDAS_AO_FIFO_CLR_REG 0x02
/* analog input ranges for most boards */
static const struct comedi_lrange cb_pcidas_ranges = {
8, {
BIP_RANGE(10),
BIP_RANGE(5),
BIP_RANGE(2.5),
BIP_RANGE(1.25),
UNI_RANGE(10),
UNI_RANGE(5),
UNI_RANGE(2.5),
UNI_RANGE(1.25)
}
};
/* pci-das1001 input ranges */
static const struct comedi_lrange cb_pcidas_alt_ranges = {
8, {
BIP_RANGE(10),
BIP_RANGE(1),
BIP_RANGE(0.1),
BIP_RANGE(0.01),
UNI_RANGE(10),
UNI_RANGE(1),
UNI_RANGE(0.1),
UNI_RANGE(0.01)
}
};
/* analog output ranges */
static const struct comedi_lrange cb_pcidas_ao_ranges = {
4, {
BIP_RANGE(5),
BIP_RANGE(10),
UNI_RANGE(5),
UNI_RANGE(10)
}
};
enum cb_pcidas_boardid {
BOARD_PCIDAS1602_16,
BOARD_PCIDAS1200,
BOARD_PCIDAS1602_12,
BOARD_PCIDAS1200_JR,
BOARD_PCIDAS1602_16_JR,
BOARD_PCIDAS1000,
BOARD_PCIDAS1001,
BOARD_PCIDAS1002,
};
struct cb_pcidas_board {
const char *name;
int ai_speed; /* fastest conversion period in ns */
int ao_scan_speed; /* analog output scan speed for 1602 series */
int fifo_size; /* number of samples fifo can hold */
unsigned int is_16bit; /* ai/ao is 1=16-bit; 0=12-bit */
unsigned int use_alt_range:1; /* use alternate ai range table */
unsigned int has_ao:1; /* has 2 analog output channels */
unsigned int has_ao_fifo:1; /* analog output has fifo */
unsigned int has_ad8402:1; /* trimpot type 1=AD8402; 0=AD7376 */
unsigned int has_dac08:1;
unsigned int is_1602:1;
};
static const struct cb_pcidas_board cb_pcidas_boards[] = {
[BOARD_PCIDAS1602_16] = {
.name = "pci-das1602/16",
.ai_speed = 5000,
.ao_scan_speed = 10000,
.fifo_size = 512,
.is_16bit = 1,
.has_ao = 1,
.has_ao_fifo = 1,
.has_ad8402 = 1,
.has_dac08 = 1,
.is_1602 = 1,
},
[BOARD_PCIDAS1200] = {
.name = "pci-das1200",
.ai_speed = 3200,
.fifo_size = 1024,
.has_ao = 1,
},
[BOARD_PCIDAS1602_12] = {
.name = "pci-das1602/12",
.ai_speed = 3200,
.ao_scan_speed = 4000,
.fifo_size = 1024,
.has_ao = 1,
.has_ao_fifo = 1,
.is_1602 = 1,
},
[BOARD_PCIDAS1200_JR] = {
.name = "pci-das1200/jr",
.ai_speed = 3200,
.fifo_size = 1024,
},
[BOARD_PCIDAS1602_16_JR] = {
.name = "pci-das1602/16/jr",
.ai_speed = 5000,
.fifo_size = 512,
.is_16bit = 1,
.has_ad8402 = 1,
.has_dac08 = 1,
.is_1602 = 1,
},
[BOARD_PCIDAS1000] = {
.name = "pci-das1000",
.ai_speed = 4000,
.fifo_size = 1024,
},
[BOARD_PCIDAS1001] = {
.name = "pci-das1001",
.ai_speed = 6800,
.fifo_size = 1024,
.use_alt_range = 1,
.has_ao = 1,
},
[BOARD_PCIDAS1002] = {
.name = "pci-das1002",
.ai_speed = 6800,
.fifo_size = 1024,
.has_ao = 1,
},
};
struct cb_pcidas_private {
struct comedi_8254 *ao_pacer;
/* base addresses */
unsigned long amcc; /* pcibar0 */
unsigned long pcibar1;
unsigned long pcibar2;
unsigned long pcibar4;
/* bits to write to registers */
unsigned int ctrl;
unsigned int amcc_intcsr;
unsigned int ao_ctrl;
/* fifo buffers */
unsigned short ai_buffer[AI_BUFFER_SIZE];
unsigned short ao_buffer[AO_BUFFER_SIZE];
unsigned int calib_src;
};
static int cb_pcidas_ai_eoc(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned long context)
{
struct cb_pcidas_private *devpriv = dev->private;
unsigned int status;
status = inw(devpriv->pcibar1 + PCIDAS_AI_REG);
if (status & PCIDAS_AI_EOC)
return 0;
return -EBUSY;
}
static int cb_pcidas_ai_insn_read(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
struct cb_pcidas_private *devpriv = dev->private;
unsigned int chan = CR_CHAN(insn->chanspec);
unsigned int range = CR_RANGE(insn->chanspec);
unsigned int aref = CR_AREF(insn->chanspec);
unsigned int bits;
int ret;
int n;
/* enable calibration input if appropriate */
if (insn->chanspec & CR_ALT_SOURCE) {
outw(PCIDAS_CALIB_EN | PCIDAS_CALIB_SRC(devpriv->calib_src),
devpriv->pcibar1 + PCIDAS_CALIB_REG);
chan = 0;
} else {
outw(0, devpriv->pcibar1 + PCIDAS_CALIB_REG);
}
/* set mux limits and gain */
bits = PCIDAS_AI_CHAN(chan) | PCIDAS_AI_GAIN(range);
/* set unipolar/bipolar */
if (comedi_range_is_unipolar(s, range))
bits |= PCIDAS_AI_UNIP;
/* set single-ended/differential */
if (aref != AREF_DIFF)
bits |= PCIDAS_AI_SE;
outw(bits, devpriv->pcibar1 + PCIDAS_AI_REG);
/* clear fifo */
outw(0, devpriv->pcibar2 + PCIDAS_AI_FIFO_CLR_REG);
/* convert n samples */
for (n = 0; n < insn->n; n++) {
/* trigger conversion */
outw(0, devpriv->pcibar2 + PCIDAS_AI_DATA_REG);
/* wait for conversion to end */
ret = comedi_timeout(dev, s, insn, cb_pcidas_ai_eoc, 0);
if (ret)
return ret;
/* read data */
data[n] = inw(devpriv->pcibar2 + PCIDAS_AI_DATA_REG);
}
/* return the number of samples read/written */
return n;
}
static int cb_pcidas_ai_insn_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
struct cb_pcidas_private *devpriv = dev->private;
int id = data[0];
unsigned int source = data[1];
switch (id) {
case INSN_CONFIG_ALT_SOURCE:
if (source >= 8) {
dev_err(dev->class_dev,
"invalid calibration source: %i\n",
source);
return -EINVAL;
}
devpriv->calib_src = source;
break;
default:
return -EINVAL;
}
return insn->n;
}
/* analog output insn for pcidas-1000 and 1200 series */
static int cb_pcidas_ao_nofifo_insn_write(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
struct cb_pcidas_private *devpriv = dev->private;
unsigned int chan = CR_CHAN(insn->chanspec);
unsigned int range = CR_RANGE(insn->chanspec);
unsigned int val = s->readback[chan];
unsigned long flags;
int i;
/* set channel and range */
spin_lock_irqsave(&dev->spinlock, flags);
devpriv->ao_ctrl &= ~(PCIDAS_AO_UPDATE_BOTH |
PCIDAS_AO_RANGE_MASK(chan));
devpriv->ao_ctrl |= PCIDAS_AO_DACEN | PCIDAS_AO_RANGE(chan, range);
outw(devpriv->ao_ctrl, devpriv->pcibar1 + PCIDAS_AO_REG);
spin_unlock_irqrestore(&dev->spinlock, flags);
for (i = 0; i < insn->n; i++) {
val = data[i];
outw(val, devpriv->pcibar4 + PCIDAS_AO_DATA_REG(chan));
}
s->readback[chan] = val;
return insn->n;
}
/* analog output insn for pcidas-1602 series */
static int cb_pcidas_ao_fifo_insn_write(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
struct cb_pcidas_private *devpriv = dev->private;
unsigned int chan = CR_CHAN(insn->chanspec);
unsigned int range = CR_RANGE(insn->chanspec);
unsigned int val = s->readback[chan];
unsigned long flags;
int i;
/* clear dac fifo */
outw(0, devpriv->pcibar4 + PCIDAS_AO_FIFO_CLR_REG);
/* set channel and range */
spin_lock_irqsave(&dev->spinlock, flags);
devpriv->ao_ctrl &= ~(PCIDAS_AO_CHAN_MASK | PCIDAS_AO_RANGE_MASK(chan) |
PCIDAS_AO_PACER_MASK);
devpriv->ao_ctrl |= PCIDAS_AO_DACEN | PCIDAS_AO_RANGE(chan, range) |
PCIDAS_AO_CHAN_EN(chan) | PCIDAS_AO_START;
outw(devpriv->ao_ctrl, devpriv->pcibar1 + PCIDAS_AO_REG);
spin_unlock_irqrestore(&dev->spinlock, flags);
for (i = 0; i < insn->n; i++) {
val = data[i];
outw(val, devpriv->pcibar4 + PCIDAS_AO_FIFO_REG);
}
s->readback[chan] = val;
return insn->n;
}
static int cb_pcidas_eeprom_ready(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned long context)
{
struct cb_pcidas_private *devpriv = dev->private;
unsigned int status;
status = inb(devpriv->amcc + AMCC_OP_REG_MCSR_NVCMD);
if ((status & MCSR_NV_BUSY) == 0)
return 0;
return -EBUSY;
}
static int cb_pcidas_eeprom_insn_read(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
struct cb_pcidas_private *devpriv = dev->private;
unsigned int chan = CR_CHAN(insn->chanspec);
int ret;
int i;
for (i = 0; i < insn->n; i++) {
/* make sure eeprom is ready */
ret = comedi_timeout(dev, s, insn, cb_pcidas_eeprom_ready, 0);
if (ret)
return ret;
/* set address (chan) and read operation */
outb(MCSR_NV_ENABLE | MCSR_NV_LOAD_LOW_ADDR,
devpriv->amcc + AMCC_OP_REG_MCSR_NVCMD);
outb(chan & 0xff, devpriv->amcc + AMCC_OP_REG_MCSR_NVDATA);
outb(MCSR_NV_ENABLE | MCSR_NV_LOAD_HIGH_ADDR,
devpriv->amcc + AMCC_OP_REG_MCSR_NVCMD);
outb((chan >> 8) & 0xff,
devpriv->amcc + AMCC_OP_REG_MCSR_NVDATA);
outb(MCSR_NV_ENABLE | MCSR_NV_READ,
devpriv->amcc + AMCC_OP_REG_MCSR_NVCMD);
/* wait for data to be returned */
ret = comedi_timeout(dev, s, insn, cb_pcidas_eeprom_ready, 0);
if (ret)
return ret;
data[i] = inb(devpriv->amcc + AMCC_OP_REG_MCSR_NVDATA);
}
return insn->n;
}
static void cb_pcidas_calib_write(struct comedi_device *dev,
unsigned int val, unsigned int len,
bool trimpot)
{
struct cb_pcidas_private *devpriv = dev->private;
unsigned int calib_bits;
unsigned int bit;
calib_bits = PCIDAS_CALIB_EN | PCIDAS_CALIB_SRC(devpriv->calib_src);
if (trimpot) {
/* select trimpot */
calib_bits |= PCIDAS_CALIB_TRIM_SEL;
outw(calib_bits, devpriv->pcibar1 + PCIDAS_CALIB_REG);
}
/* write bitstream to calibration device */
for (bit = 1 << (len - 1); bit; bit >>= 1) {
if (val & bit)
calib_bits |= PCIDAS_CALIB_DATA;
else
calib_bits &= ~PCIDAS_CALIB_DATA;
udelay(1);
outw(calib_bits, devpriv->pcibar1 + PCIDAS_CALIB_REG);
}
udelay(1);
calib_bits = PCIDAS_CALIB_EN | PCIDAS_CALIB_SRC(devpriv->calib_src);
if (!trimpot) {
/* select caldac */
outw(calib_bits | PCIDAS_CALIB_8800_SEL,
devpriv->pcibar1 + PCIDAS_CALIB_REG);
udelay(1);
}
/* latch value to trimpot/caldac */
outw(calib_bits, devpriv->pcibar1 + PCIDAS_CALIB_REG);
}
static int cb_pcidas_caldac_insn_write(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
unsigned int chan = CR_CHAN(insn->chanspec);
if (insn->n) {
unsigned int val = data[insn->n - 1];
if (s->readback[chan] != val) {
/* write 11-bit channel/value to caldac */
cb_pcidas_calib_write(dev, (chan << 8) | val, 11,
false);
s->readback[chan] = val;
}
}
return insn->n;
}
static void cb_pcidas_dac08_write(struct comedi_device *dev, unsigned int val)
{
struct cb_pcidas_private *devpriv = dev->private;
val |= PCIDAS_CALIB_EN | PCIDAS_CALIB_SRC(devpriv->calib_src);
/* latch the new value into the caldac */
outw(val, devpriv->pcibar1 + PCIDAS_CALIB_REG);
udelay(1);
outw(val | PCIDAS_CALIB_DAC08_SEL,
devpriv->pcibar1 + PCIDAS_CALIB_REG);
udelay(1);
outw(val, devpriv->pcibar1 + PCIDAS_CALIB_REG);
udelay(1);
}
static int cb_pcidas_dac08_insn_write(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
unsigned int chan = CR_CHAN(insn->chanspec);
if (insn->n) {
unsigned int val = data[insn->n - 1];
if (s->readback[chan] != val) {
cb_pcidas_dac08_write(dev, val);
s->readback[chan] = val;
}
}
return insn->n;
}
static void cb_pcidas_trimpot_write(struct comedi_device *dev,
unsigned int chan, unsigned int val)
{
const struct cb_pcidas_board *board = dev->board_ptr;
if (board->has_ad8402) {
/* write 10-bit channel/value to AD8402 trimpot */
cb_pcidas_calib_write(dev, (chan << 8) | val, 10, true);
} else {
/* write 7-bit value to AD7376 trimpot */
cb_pcidas_calib_write(dev, val, 7, true);
}
}
static int cb_pcidas_trimpot_insn_write(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
unsigned int chan = CR_CHAN(insn->chanspec);
if (insn->n) {
unsigned int val = data[insn->n - 1];
if (s->readback[chan] != val) {
cb_pcidas_trimpot_write(dev, chan, val);
s->readback[chan] = val;
}
}
return insn->n;
}
static int cb_pcidas_ai_check_chanlist(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_cmd *cmd)
{
unsigned int chan0 = CR_CHAN(cmd->chanlist[0]);
unsigned int range0 = CR_RANGE(cmd->chanlist[0]);
int i;
for (i = 1; i < cmd->chanlist_len; i++) {
unsigned int chan = CR_CHAN(cmd->chanlist[i]);
unsigned int range = CR_RANGE(cmd->chanlist[i]);
if (chan != (chan0 + i) % s->n_chan) {
dev_dbg(dev->class_dev,
"entries in chanlist must be consecutive channels, counting upwards\n");
return -EINVAL;
}
if (range != range0) {
dev_dbg(dev->class_dev,
"entries in chanlist must all have the same gain\n");
return -EINVAL;
}
}
return 0;
}
static int cb_pcidas_ai_cmdtest(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_cmd *cmd)
{
const struct cb_pcidas_board *board = dev->board_ptr;
int err = 0;
unsigned int arg;
/* Step 1 : check if triggers are trivially valid */
err |= comedi_check_trigger_src(&cmd->start_src, TRIG_NOW | TRIG_EXT);
err |= comedi_check_trigger_src(&cmd->scan_begin_src,
TRIG_FOLLOW | TRIG_TIMER | TRIG_EXT);
err |= comedi_check_trigger_src(&cmd->convert_src,
TRIG_TIMER | TRIG_NOW | TRIG_EXT);
err |= comedi_check_trigger_src(&cmd->scan_end_src, TRIG_COUNT);
err |= comedi_check_trigger_src(&cmd->stop_src, TRIG_COUNT | TRIG_NONE);
if (err)
return 1;
/* Step 2a : make sure trigger sources are unique */
err |= comedi_check_trigger_is_unique(cmd->start_src);
err |= comedi_check_trigger_is_unique(cmd->scan_begin_src);
err |= comedi_check_trigger_is_unique(cmd->convert_src);
err |= comedi_check_trigger_is_unique(cmd->stop_src);
/* Step 2b : and mutually compatible */
if (cmd->scan_begin_src == TRIG_FOLLOW && cmd->convert_src == TRIG_NOW)
err |= -EINVAL;
if (cmd->scan_begin_src != TRIG_FOLLOW && cmd->convert_src != TRIG_NOW)
err |= -EINVAL;
if (cmd->start_src == TRIG_EXT &&
(cmd->convert_src == TRIG_EXT || cmd->scan_begin_src == TRIG_EXT))
err |= -EINVAL;
if (err)
return 2;
/* Step 3: check if arguments are trivially valid */
switch (cmd->start_src) {
case TRIG_NOW:
err |= comedi_check_trigger_arg_is(&cmd->start_arg, 0);
break;
case TRIG_EXT:
/* External trigger, only CR_EDGE and CR_INVERT flags allowed */
if ((cmd->start_arg
& (CR_FLAGS_MASK & ~(CR_EDGE | CR_INVERT))) != 0) {
cmd->start_arg &= ~(CR_FLAGS_MASK &
~(CR_EDGE | CR_INVERT));
err |= -EINVAL;
}
if (!board->is_1602 && (cmd->start_arg & CR_INVERT)) {
cmd->start_arg &= (CR_FLAGS_MASK & ~CR_INVERT);
err |= -EINVAL;
}
break;
}
if (cmd->scan_begin_src == TRIG_TIMER) {
err |= comedi_check_trigger_arg_min(&cmd->scan_begin_arg,
board->ai_speed *
cmd->chanlist_len);
}
if (cmd->convert_src == TRIG_TIMER) {
err |= comedi_check_trigger_arg_min(&cmd->convert_arg,
board->ai_speed);
}
err |= comedi_check_trigger_arg_is(&cmd->scan_end_arg,
cmd->chanlist_len);
if (cmd->stop_src == TRIG_COUNT)
err |= comedi_check_trigger_arg_min(&cmd->stop_arg, 1);
else /* TRIG_NONE */
err |= comedi_check_trigger_arg_is(&cmd->stop_arg, 0);
if (err)
return 3;
/* step 4: fix up any arguments */
if (cmd->scan_begin_src == TRIG_TIMER) {
arg = cmd->scan_begin_arg;
comedi_8254_cascade_ns_to_timer(dev->pacer, &arg, cmd->flags);
err |= comedi_check_trigger_arg_is(&cmd->scan_begin_arg, arg);
}
if (cmd->convert_src == TRIG_TIMER) {
arg = cmd->convert_arg;
comedi_8254_cascade_ns_to_timer(dev->pacer, &arg, cmd->flags);
err |= comedi_check_trigger_arg_is(&cmd->convert_arg, arg);
}
if (err)
return 4;
/* Step 5: check channel list if it exists */
if (cmd->chanlist && cmd->chanlist_len > 0)
err |= cb_pcidas_ai_check_chanlist(dev, s, cmd);
if (err)
return 5;
return 0;
}
static int cb_pcidas_ai_cmd(struct comedi_device *dev,
struct comedi_subdevice *s)
{
const struct cb_pcidas_board *board = dev->board_ptr;
struct cb_pcidas_private *devpriv = dev->private;
struct comedi_async *async = s->async;
struct comedi_cmd *cmd = &async->cmd;
unsigned int range0 = CR_RANGE(cmd->chanlist[0]);
unsigned int bits;
unsigned long flags;
/* make sure PCIDAS_CALIB_EN is disabled */
outw(0, devpriv->pcibar1 + PCIDAS_CALIB_REG);
/* initialize before settings pacer source and count values */
outw(PCIDAS_TRIG_SEL_NONE, devpriv->pcibar1 + PCIDAS_TRIG_REG);
/* clear fifo */
outw(0, devpriv->pcibar2 + PCIDAS_AI_FIFO_CLR_REG);
/* set mux limits, gain and pacer source */
bits = PCIDAS_AI_FIRST(CR_CHAN(cmd->chanlist[0])) |
PCIDAS_AI_LAST(CR_CHAN(cmd->chanlist[cmd->chanlist_len - 1])) |
PCIDAS_AI_GAIN(range0);
/* set unipolar/bipolar */
if (comedi_range_is_unipolar(s, range0))
bits |= PCIDAS_AI_UNIP;
/* set singleended/differential */
if (CR_AREF(cmd->chanlist[0]) != AREF_DIFF)
bits |= PCIDAS_AI_SE;
/* set pacer source */
if (cmd->convert_src == TRIG_EXT || cmd->scan_begin_src == TRIG_EXT)
bits |= PCIDAS_AI_PACER_EXTP;
else
bits |= PCIDAS_AI_PACER_INT;
outw(bits, devpriv->pcibar1 + PCIDAS_AI_REG);
/* load counters */
if (cmd->scan_begin_src == TRIG_TIMER ||
cmd->convert_src == TRIG_TIMER) {
comedi_8254_update_divisors(dev->pacer);
comedi_8254_pacer_enable(dev->pacer, 1, 2, true);
}
/* enable interrupts */
spin_lock_irqsave(&dev->spinlock, flags);
devpriv->ctrl |= PCIDAS_CTRL_INTE;
devpriv->ctrl &= ~PCIDAS_CTRL_INT_MASK;
if (cmd->flags & CMDF_WAKE_EOS) {
if (cmd->convert_src == TRIG_NOW && cmd->chanlist_len > 1) {
/* interrupt end of burst */
devpriv->ctrl |= PCIDAS_CTRL_INT_EOS;
} else {
/* interrupt fifo not empty */
devpriv->ctrl |= PCIDAS_CTRL_INT_FNE;
}
} else {
/* interrupt fifo half full */
devpriv->ctrl |= PCIDAS_CTRL_INT_FHF;
}
/* enable (and clear) interrupts */
outw(devpriv->ctrl |
PCIDAS_CTRL_EOAI | PCIDAS_CTRL_INT_CLR | PCIDAS_CTRL_LADFUL,
devpriv->pcibar1 + PCIDAS_CTRL_REG);
spin_unlock_irqrestore(&dev->spinlock, flags);
/* set start trigger and burst mode */
bits = 0;
if (cmd->start_src == TRIG_NOW) {
bits |= PCIDAS_TRIG_SEL_SW;
} else { /* TRIG_EXT */
bits |= PCIDAS_TRIG_SEL_EXT | PCIDAS_TRIG_EN | PCIDAS_TRIG_CLR;
if (board->is_1602) {
if (cmd->start_arg & CR_INVERT)
bits |= PCIDAS_TRIG_POL;
if (cmd->start_arg & CR_EDGE)
bits |= PCIDAS_TRIG_MODE;
}
}
if (cmd->convert_src == TRIG_NOW && cmd->chanlist_len > 1)
bits |= PCIDAS_TRIG_BURSTE;
outw(bits, devpriv->pcibar1 + PCIDAS_TRIG_REG);
return 0;
}
static int cb_pcidas_ao_check_chanlist(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_cmd *cmd)
{
unsigned int chan0 = CR_CHAN(cmd->chanlist[0]);
if (cmd->chanlist_len > 1) {
unsigned int chan1 = CR_CHAN(cmd->chanlist[1]);
if (chan0 != 0 || chan1 != 1) {
dev_dbg(dev->class_dev,
"channels must be ordered channel 0, channel 1 in chanlist\n");
return -EINVAL;
}
}
return 0;
}
static int cb_pcidas_ao_cmdtest(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_cmd *cmd)
{
const struct cb_pcidas_board *board = dev->board_ptr;
struct cb_pcidas_private *devpriv = dev->private;
int err = 0;
/* Step 1 : check if triggers are trivially valid */
err |= comedi_check_trigger_src(&cmd->start_src, TRIG_INT);
err |= comedi_check_trigger_src(&cmd->scan_begin_src,
TRIG_TIMER | TRIG_EXT);
err |= comedi_check_trigger_src(&cmd->convert_src, TRIG_NOW);
err |= comedi_check_trigger_src(&cmd->scan_end_src, TRIG_COUNT);
err |= comedi_check_trigger_src(&cmd->stop_src, TRIG_COUNT | TRIG_NONE);
if (err)
return 1;
/* Step 2a : make sure trigger sources are unique */
err |= comedi_check_trigger_is_unique(cmd->scan_begin_src);
err |= comedi_check_trigger_is_unique(cmd->stop_src);
/* Step 2b : and mutually compatible */
if (err)
return 2;
/* Step 3: check if arguments are trivially valid */
err |= comedi_check_trigger_arg_is(&cmd->start_arg, 0);
if (cmd->scan_begin_src == TRIG_TIMER) {
err |= comedi_check_trigger_arg_min(&cmd->scan_begin_arg,
board->ao_scan_speed);
}
err |= comedi_check_trigger_arg_is(&cmd->scan_end_arg,
cmd->chanlist_len);
if (cmd->stop_src == TRIG_COUNT)
err |= comedi_check_trigger_arg_min(&cmd->stop_arg, 1);
else /* TRIG_NONE */
err |= comedi_check_trigger_arg_is(&cmd->stop_arg, 0);
if (err)
return 3;
/* step 4: fix up any arguments */
if (cmd->scan_begin_src == TRIG_TIMER) {
unsigned int arg = cmd->scan_begin_arg;
comedi_8254_cascade_ns_to_timer(devpriv->ao_pacer,
&arg, cmd->flags);
err |= comedi_check_trigger_arg_is(&cmd->scan_begin_arg, arg);
}
if (err)
return 4;
/* Step 5: check channel list if it exists */
if (cmd->chanlist && cmd->chanlist_len > 0)
err |= cb_pcidas_ao_check_chanlist(dev, s, cmd);
if (err)
return 5;
return 0;
}
static int cb_pcidas_ai_cancel(struct comedi_device *dev,
struct comedi_subdevice *s)
{
struct cb_pcidas_private *devpriv = dev->private;
unsigned long flags;
spin_lock_irqsave(&dev->spinlock, flags);
/* disable interrupts */
devpriv->ctrl &= ~(PCIDAS_CTRL_INTE | PCIDAS_CTRL_EOAIE);
outw(devpriv->ctrl, devpriv->pcibar1 + PCIDAS_CTRL_REG);
spin_unlock_irqrestore(&dev->spinlock, flags);
/* disable start trigger source and burst mode */
outw(PCIDAS_TRIG_SEL_NONE, devpriv->pcibar1 + PCIDAS_TRIG_REG);
outw(PCIDAS_AI_PACER_SW, devpriv->pcibar1 + PCIDAS_AI_REG);
return 0;
}
static void cb_pcidas_ao_load_fifo(struct comedi_device *dev,
struct comedi_subdevice *s,
unsigned int nsamples)
{
struct cb_pcidas_private *devpriv = dev->private;
unsigned int nbytes;
nsamples = comedi_nsamples_left(s, nsamples);
nbytes = comedi_buf_read_samples(s, devpriv->ao_buffer, nsamples);
nsamples = comedi_bytes_to_samples(s, nbytes);
outsw(devpriv->pcibar4 + PCIDAS_AO_FIFO_REG,
devpriv->ao_buffer, nsamples);
}
static int cb_pcidas_ao_inttrig(struct comedi_device *dev,
struct comedi_subdevice *s,
unsigned int trig_num)
{
const struct cb_pcidas_board *board = dev->board_ptr;
struct cb_pcidas_private *devpriv = dev->private;
struct comedi_async *async = s->async;
struct comedi_cmd *cmd = &async->cmd;
unsigned long flags;
if (trig_num != cmd->start_arg)
return -EINVAL;
cb_pcidas_ao_load_fifo(dev, s, board->fifo_size);
/* enable dac half-full and empty interrupts */
spin_lock_irqsave(&dev->spinlock, flags);
devpriv->ctrl |= PCIDAS_CTRL_DAEMIE | PCIDAS_CTRL_DAHFIE;
/* enable and clear interrupts */
outw(devpriv->ctrl | PCIDAS_CTRL_DAEMI | PCIDAS_CTRL_DAHFI,
devpriv->pcibar1 + PCIDAS_CTRL_REG);
/* start dac */
devpriv->ao_ctrl |= PCIDAS_AO_START | PCIDAS_AO_DACEN | PCIDAS_AO_EMPTY;
outw(devpriv->ao_ctrl, devpriv->pcibar1 + PCIDAS_AO_REG);
spin_unlock_irqrestore(&dev->spinlock, flags);
async->inttrig = NULL;
return 0;
}
static int cb_pcidas_ao_cmd(struct comedi_device *dev,
struct comedi_subdevice *s)
{
struct cb_pcidas_private *devpriv = dev->private;
struct comedi_async *async = s->async;
struct comedi_cmd *cmd = &async->cmd;
unsigned int i;
unsigned long flags;
/* set channel limits, gain */
spin_lock_irqsave(&dev->spinlock, flags);
for (i = 0; i < cmd->chanlist_len; i++) {
unsigned int chan = CR_CHAN(cmd->chanlist[i]);
unsigned int range = CR_RANGE(cmd->chanlist[i]);
/* enable channel */
devpriv->ao_ctrl |= PCIDAS_AO_CHAN_EN(chan);
/* set range */
devpriv->ao_ctrl |= PCIDAS_AO_RANGE(chan, range);
}
/* disable analog out before settings pacer source and count values */
outw(devpriv->ao_ctrl, devpriv->pcibar1 + PCIDAS_AO_REG);
spin_unlock_irqrestore(&dev->spinlock, flags);
/* clear fifo */
outw(0, devpriv->pcibar4 + PCIDAS_AO_FIFO_CLR_REG);
/* load counters */
if (cmd->scan_begin_src == TRIG_TIMER) {
comedi_8254_update_divisors(devpriv->ao_pacer);
comedi_8254_pacer_enable(devpriv->ao_pacer, 1, 2, true);
}
/* set pacer source */
spin_lock_irqsave(&dev->spinlock, flags);
switch (cmd->scan_begin_src) {
case TRIG_TIMER:
devpriv->ao_ctrl |= PCIDAS_AO_PACER_INT;
break;
case TRIG_EXT:
devpriv->ao_ctrl |= PCIDAS_AO_PACER_EXTP;
break;
default:
spin_unlock_irqrestore(&dev->spinlock, flags);
dev_err(dev->class_dev, "error setting dac pacer source\n");
return -1;
}
spin_unlock_irqrestore(&dev->spinlock, flags);
async->inttrig = cb_pcidas_ao_inttrig;
return 0;
}
static int cb_pcidas_ao_cancel(struct comedi_device *dev,
struct comedi_subdevice *s)
{
struct cb_pcidas_private *devpriv = dev->private;
unsigned long flags;
spin_lock_irqsave(&dev->spinlock, flags);
/* disable interrupts */
devpriv->ctrl &= ~(PCIDAS_CTRL_DAHFIE | PCIDAS_CTRL_DAEMIE);
outw(devpriv->ctrl, devpriv->pcibar1 + PCIDAS_CTRL_REG);
/* disable output */
devpriv->ao_ctrl &= ~(PCIDAS_AO_DACEN | PCIDAS_AO_PACER_MASK);
outw(devpriv->ao_ctrl, devpriv->pcibar1 + PCIDAS_AO_REG);
spin_unlock_irqrestore(&dev->spinlock, flags);
return 0;
}
static unsigned int cb_pcidas_ao_interrupt(struct comedi_device *dev,
unsigned int status)
{
const struct cb_pcidas_board *board = dev->board_ptr;
struct cb_pcidas_private *devpriv = dev->private;
struct comedi_subdevice *s = dev->write_subdev;
struct comedi_async *async = s->async;
struct comedi_cmd *cmd = &async->cmd;
unsigned int irq_clr = 0;
if (status & PCIDAS_CTRL_DAEMI) {
irq_clr |= PCIDAS_CTRL_DAEMI;
if (inw(devpriv->pcibar4 + PCIDAS_AO_REG) & PCIDAS_AO_EMPTY) {
if (cmd->stop_src == TRIG_COUNT &&
async->scans_done >= cmd->stop_arg) {
async->events |= COMEDI_CB_EOA;
} else {
dev_err(dev->class_dev, "dac fifo underflow\n");
async->events |= COMEDI_CB_ERROR;
}
}
} else if (status & PCIDAS_CTRL_DAHFI) {
irq_clr |= PCIDAS_CTRL_DAHFI;
cb_pcidas_ao_load_fifo(dev, s, board->fifo_size / 2);
}
comedi_handle_events(dev, s);
return irq_clr;
}
static unsigned int cb_pcidas_ai_interrupt(struct comedi_device *dev,
unsigned int status)
{
const struct cb_pcidas_board *board = dev->board_ptr;
struct cb_pcidas_private *devpriv = dev->private;
struct comedi_subdevice *s = dev->read_subdev;
struct comedi_async *async = s->async;
struct comedi_cmd *cmd = &async->cmd;
unsigned int irq_clr = 0;
if (status & PCIDAS_CTRL_ADHFI) {
unsigned int num_samples;
irq_clr |= PCIDAS_CTRL_INT_CLR;
/* FIFO is half-full - read data */
num_samples = comedi_nsamples_left(s, board->fifo_size / 2);
insw(devpriv->pcibar2 + PCIDAS_AI_DATA_REG,
devpriv->ai_buffer, num_samples);
comedi_buf_write_samples(s, devpriv->ai_buffer, num_samples);
if (cmd->stop_src == TRIG_COUNT &&
async->scans_done >= cmd->stop_arg)
async->events |= COMEDI_CB_EOA;
} else if (status & (PCIDAS_CTRL_ADNEI | PCIDAS_CTRL_EOBI)) {
unsigned int i;
irq_clr |= PCIDAS_CTRL_INT_CLR;
/* FIFO is not empty - read data until empty or timeoout */
for (i = 0; i < 10000; i++) {
unsigned short val;
/* break if fifo is empty */
if ((inw(devpriv->pcibar1 + PCIDAS_CTRL_REG) &
PCIDAS_CTRL_ADNE) == 0)
break;
val = inw(devpriv->pcibar2 + PCIDAS_AI_DATA_REG);
comedi_buf_write_samples(s, &val, 1);
if (cmd->stop_src == TRIG_COUNT &&
async->scans_done >= cmd->stop_arg) {
async->events |= COMEDI_CB_EOA;
break;
}
}
} else if (status & PCIDAS_CTRL_EOAI) {
irq_clr |= PCIDAS_CTRL_EOAI;
dev_err(dev->class_dev,
"bug! encountered end of acquisition interrupt?\n");
}
/* check for fifo overflow */
if (status & PCIDAS_CTRL_LADFUL) {
irq_clr |= PCIDAS_CTRL_LADFUL;
dev_err(dev->class_dev, "fifo overflow\n");
async->events |= COMEDI_CB_ERROR;
}
comedi_handle_events(dev, s);
return irq_clr;
}
static irqreturn_t cb_pcidas_interrupt(int irq, void *d)
{
struct comedi_device *dev = d;
struct cb_pcidas_private *devpriv = dev->private;
unsigned int irq_clr = 0;
unsigned int amcc_status;
unsigned int status;
if (!dev->attached)
return IRQ_NONE;
amcc_status = inl(devpriv->amcc + AMCC_OP_REG_INTCSR);
if ((INTCSR_INTR_ASSERTED & amcc_status) == 0)
return IRQ_NONE;
/* make sure mailbox 4 is empty */
inl_p(devpriv->amcc + AMCC_OP_REG_IMB4);
/* clear interrupt on amcc s5933 */
outl(devpriv->amcc_intcsr | INTCSR_INBOX_INTR_STATUS,
devpriv->amcc + AMCC_OP_REG_INTCSR);
status = inw(devpriv->pcibar1 + PCIDAS_CTRL_REG);
/* handle analog output interrupts */
if (status & PCIDAS_CTRL_AO_INT)
irq_clr |= cb_pcidas_ao_interrupt(dev, status);
/* handle analog input interrupts */
if (status & PCIDAS_CTRL_AI_INT)
irq_clr |= cb_pcidas_ai_interrupt(dev, status);
if (irq_clr) {
unsigned long flags;
spin_lock_irqsave(&dev->spinlock, flags);
outw(devpriv->ctrl | irq_clr,
devpriv->pcibar1 + PCIDAS_CTRL_REG);
spin_unlock_irqrestore(&dev->spinlock, flags);
}
return IRQ_HANDLED;
}
static int cb_pcidas_auto_attach(struct comedi_device *dev,
unsigned long context)
{
struct pci_dev *pcidev = comedi_to_pci_dev(dev);
const struct cb_pcidas_board *board = NULL;
struct cb_pcidas_private *devpriv;
struct comedi_subdevice *s;
int i;
int ret;
if (context < ARRAY_SIZE(cb_pcidas_boards))
board = &cb_pcidas_boards[context];
if (!board)
return -ENODEV;
dev->board_ptr = board;
dev->board_name = board->name;
devpriv = comedi_alloc_devpriv(dev, sizeof(*devpriv));
if (!devpriv)
return -ENOMEM;
ret = comedi_pci_enable(dev);
if (ret)
return ret;
devpriv->amcc = pci_resource_start(pcidev, 0);
devpriv->pcibar1 = pci_resource_start(pcidev, 1);
devpriv->pcibar2 = pci_resource_start(pcidev, 2);
dev->iobase = pci_resource_start(pcidev, 3);
if (board->has_ao)
devpriv->pcibar4 = pci_resource_start(pcidev, 4);
/* disable and clear interrupts on amcc s5933 */
outl(INTCSR_INBOX_INTR_STATUS,
devpriv->amcc + AMCC_OP_REG_INTCSR);
ret = request_irq(pcidev->irq, cb_pcidas_interrupt, IRQF_SHARED,
dev->board_name, dev);
if (ret) {
dev_dbg(dev->class_dev, "unable to allocate irq %d\n",
pcidev->irq);
return ret;
}
dev->irq = pcidev->irq;
dev->pacer = comedi_8254_init(dev->iobase + PCIDAS_AI_8254_BASE,
I8254_OSC_BASE_10MHZ, I8254_IO8, 0);
if (!dev->pacer)
return -ENOMEM;
devpriv->ao_pacer = comedi_8254_init(dev->iobase + PCIDAS_AO_8254_BASE,
I8254_OSC_BASE_10MHZ,
I8254_IO8, 0);
if (!devpriv->ao_pacer)
return -ENOMEM;
ret = comedi_alloc_subdevices(dev, 7);
if (ret)
return ret;
/* Analog Input subdevice */
s = &dev->subdevices[0];
s->type = COMEDI_SUBD_AI;
s->subdev_flags = SDF_READABLE | SDF_GROUND | SDF_DIFF;
s->n_chan = 16;
s->maxdata = board->is_16bit ? 0xffff : 0x0fff;
s->range_table = board->use_alt_range ? &cb_pcidas_alt_ranges
: &cb_pcidas_ranges;
s->insn_read = cb_pcidas_ai_insn_read;
s->insn_config = cb_pcidas_ai_insn_config;
if (dev->irq) {
dev->read_subdev = s;
s->subdev_flags |= SDF_CMD_READ;
s->len_chanlist = s->n_chan;
s->do_cmd = cb_pcidas_ai_cmd;
s->do_cmdtest = cb_pcidas_ai_cmdtest;
s->cancel = cb_pcidas_ai_cancel;
}
/* Analog Output subdevice */
s = &dev->subdevices[1];
if (board->has_ao) {
s->type = COMEDI_SUBD_AO;
s->subdev_flags = SDF_WRITABLE | SDF_GROUND;
s->n_chan = 2;
s->maxdata = board->is_16bit ? 0xffff : 0x0fff;
s->range_table = &cb_pcidas_ao_ranges;
s->insn_write = (board->has_ao_fifo)
? cb_pcidas_ao_fifo_insn_write
: cb_pcidas_ao_nofifo_insn_write;
ret = comedi_alloc_subdev_readback(s);
if (ret)
return ret;
if (dev->irq && board->has_ao_fifo) {
dev->write_subdev = s;
s->subdev_flags |= SDF_CMD_WRITE;
s->do_cmdtest = cb_pcidas_ao_cmdtest;
s->do_cmd = cb_pcidas_ao_cmd;
s->cancel = cb_pcidas_ao_cancel;
}
} else {
s->type = COMEDI_SUBD_UNUSED;
}
/* 8255 */
s = &dev->subdevices[2];
ret = subdev_8255_init(dev, s, NULL, PCIDAS_8255_BASE);
if (ret)
return ret;
/* Memory subdevice - serial EEPROM */
s = &dev->subdevices[3];
s->type = COMEDI_SUBD_MEMORY;
s->subdev_flags = SDF_READABLE | SDF_INTERNAL;
s->n_chan = 256;
s->maxdata = 0xff;
s->insn_read = cb_pcidas_eeprom_insn_read;
/* Calibration subdevice - 8800 caldac */
s = &dev->subdevices[4];
s->type = COMEDI_SUBD_CALIB;
s->subdev_flags = SDF_WRITABLE | SDF_INTERNAL;
s->n_chan = 8;
s->maxdata = 0xff;
s->insn_write = cb_pcidas_caldac_insn_write;
ret = comedi_alloc_subdev_readback(s);
if (ret)
return ret;
for (i = 0; i < s->n_chan; i++) {
unsigned int val = s->maxdata / 2;
/* write 11-bit channel/value to caldac */
cb_pcidas_calib_write(dev, (i << 8) | val, 11, false);
s->readback[i] = val;
}
/* Calibration subdevice - trim potentiometer */
s = &dev->subdevices[5];
s->type = COMEDI_SUBD_CALIB;
s->subdev_flags = SDF_WRITABLE | SDF_INTERNAL;
if (board->has_ad8402) {
/*
* pci-das1602/16 have an AD8402 trimpot:
* chan 0 : adc gain
* chan 1 : adc postgain offset
*/
s->n_chan = 2;
s->maxdata = 0xff;
} else {
/* all other boards have an AD7376 trimpot */
s->n_chan = 1;
s->maxdata = 0x7f;
}
s->insn_write = cb_pcidas_trimpot_insn_write;
ret = comedi_alloc_subdev_readback(s);
if (ret)
return ret;
for (i = 0; i < s->n_chan; i++) {
cb_pcidas_trimpot_write(dev, i, s->maxdata / 2);
s->readback[i] = s->maxdata / 2;
}
/* Calibration subdevice - pci-das1602/16 pregain offset (dac08) */
s = &dev->subdevices[6];
if (board->has_dac08) {
s->type = COMEDI_SUBD_CALIB;
s->subdev_flags = SDF_WRITABLE | SDF_INTERNAL;
s->n_chan = 1;
s->maxdata = 0xff;
s->insn_write = cb_pcidas_dac08_insn_write;
ret = comedi_alloc_subdev_readback(s);
if (ret)
return ret;
for (i = 0; i < s->n_chan; i++) {
cb_pcidas_dac08_write(dev, s->maxdata / 2);
s->readback[i] = s->maxdata / 2;
}
} else {
s->type = COMEDI_SUBD_UNUSED;
}
/* make sure mailbox 4 is empty */
inl(devpriv->amcc + AMCC_OP_REG_IMB4);
/* Set bits to enable incoming mailbox interrupts on amcc s5933. */
devpriv->amcc_intcsr = INTCSR_INBOX_BYTE(3) | INTCSR_INBOX_SELECT(3) |
INTCSR_INBOX_FULL_INT;
/* clear and enable interrupt on amcc s5933 */
outl(devpriv->amcc_intcsr | INTCSR_INBOX_INTR_STATUS,
devpriv->amcc + AMCC_OP_REG_INTCSR);
return 0;
}
static void cb_pcidas_detach(struct comedi_device *dev)
{
struct cb_pcidas_private *devpriv = dev->private;
if (devpriv) {
if (devpriv->amcc)
outl(INTCSR_INBOX_INTR_STATUS,
devpriv->amcc + AMCC_OP_REG_INTCSR);
kfree(devpriv->ao_pacer);
}
comedi_pci_detach(dev);
}
static struct comedi_driver cb_pcidas_driver = {
.driver_name = "cb_pcidas",
.module = THIS_MODULE,
.auto_attach = cb_pcidas_auto_attach,
.detach = cb_pcidas_detach,
};
static int cb_pcidas_pci_probe(struct pci_dev *dev,
const struct pci_device_id *id)
{
return comedi_pci_auto_config(dev, &cb_pcidas_driver,
id->driver_data);
}
static const struct pci_device_id cb_pcidas_pci_table[] = {
{ PCI_VDEVICE(CB, 0x0001), BOARD_PCIDAS1602_16 },
{ PCI_VDEVICE(CB, 0x000f), BOARD_PCIDAS1200 },
{ PCI_VDEVICE(CB, 0x0010), BOARD_PCIDAS1602_12 },
{ PCI_VDEVICE(CB, 0x0019), BOARD_PCIDAS1200_JR },
{ PCI_VDEVICE(CB, 0x001c), BOARD_PCIDAS1602_16_JR },
{ PCI_VDEVICE(CB, 0x004c), BOARD_PCIDAS1000 },
{ PCI_VDEVICE(CB, 0x001a), BOARD_PCIDAS1001 },
{ PCI_VDEVICE(CB, 0x001b), BOARD_PCIDAS1002 },
{ 0 }
};
MODULE_DEVICE_TABLE(pci, cb_pcidas_pci_table);
static struct pci_driver cb_pcidas_pci_driver = {
.name = "cb_pcidas",
.id_table = cb_pcidas_pci_table,
.probe = cb_pcidas_pci_probe,
.remove = comedi_pci_auto_unconfig,
};
module_comedi_pci_driver(cb_pcidas_driver, cb_pcidas_pci_driver);
MODULE_AUTHOR("Comedi http://www.comedi.org");
MODULE_DESCRIPTION("Comedi driver for MeasurementComputing PCI-DAS series");
MODULE_LICENSE("GPL");
| {
"pile_set_name": "Github"
} |
div.widget.project-share .title {
border: none;
}
div.widget.project-share div.left,div.widget.project-share div.right{
float:left;
}
div.widget.project-share div.left{
width:70%;
}
div.widget.project-share div.right{
width:30%;
}
div.widget.project-share h4{
font-weight:normal;
margin-top:0;
}
div.widget.project-share ul {
height: 60px;
list-style: none outside none;
margin: 0;
overflow: visible;
padding: 0;
position: relative;
}
div.widget.project-share li {
display: block;
padding-left: 30px;
float: left;
min-height: 2em;
line-height: 2em;
background: no-repeat left center;
min-width: 20%;
}
div.widget.project-share li a {
text-decoration: none;
}
div.widget.project-share li.twitter {
background-image: url('/view/css/social/twitter.png');
position:absolute;
top:0;left:0;
}
div.widget.project-share li.facebook {
background-image: url('/view/css/social/facebook.png');
position:absolute;
top:30px;left:0;
}
div.widget.project-share li.url{
position:absolute;
top:0;left:100px;
}
div.widget.project-share li.proyecto{
background-image: url("/view/css/project/widget/proyecto.jpg");
font-size: 11px;
height: 20px;
line-height: 20px;
margin-left: 5px;
width: 128px;
}
div.widget.project-share li.proyecto a{
color:#fff;
}
div.widget.project-share li.google {
background-image: url('/view/css/social/google.png');
}
div.widget.project-share li.identica {
background-image: url('/view/css/social/identica.png');
}
div.widget.project-share li.url {
background-image: url('/view/css/social/url.png');
}
div.widget.project-share li.embed {
background-image: url('/view/css/social/embed.png');
}
div.widget.project-share li.url span,
div.widget.project-share li.embed span{
display: none;
}
div.widget.project-share li.url input,
div.widget.project-share li.url input:focus,
div.widget.project-share li.embed input,
div.widget.project-share li.embed input:focus {
border: none;
font-size: inherit;
background-color: #e6e6e6 !important;
padding: .3em .4em;
border-radius: .25em;
-moz-border-radius: .2em;
font-weight: normal;
} | {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (C) 2016 BayLibre, SAS
* Author: Neil Armstrong <[email protected]>
* Copyright (C) 2015 Amlogic, Inc. All rights reserved.
* Copyright (C) 2014 Endless Mobile
*/
#include <linux/export.h>
#include <linux/bitfield.h>
#include <drm/drm_fourcc.h>
#include "meson_drv.h"
#include "meson_viu.h"
#include "meson_registers.h"
/**
* DOC: Video Input Unit
*
* VIU Handles the Pixel scanout and the basic Colorspace conversions
* We handle the following features :
*
* - OSD1 RGB565/RGB888/xRGB8888 scanout
* - RGB conversion to x/cb/cr
* - Progressive or Interlace buffer scanout
* - OSD1 Commit on Vsync
* - HDR OSD matrix for GXL/GXM
*
* What is missing :
*
* - BGR888/xBGR8888/BGRx8888/BGRx8888 modes
* - YUV4:2:2 Y0CbY1Cr scanout
* - Conversion to YUV 4:4:4 from 4:2:2 input
* - Colorkey Alpha matching
* - Big endian scanout
* - X/Y reverse scanout
* - Global alpha setup
* - OSD2 support, would need interlace switching on vsync
* - OSD1 full scaling to support TV overscan
*/
/* OSD csc defines */
enum viu_matrix_sel_e {
VIU_MATRIX_OSD_EOTF = 0,
VIU_MATRIX_OSD,
};
enum viu_lut_sel_e {
VIU_LUT_OSD_EOTF = 0,
VIU_LUT_OSD_OETF,
};
#define COEFF_NORM(a) ((int)((((a) * 2048.0) + 1) / 2))
#define MATRIX_5X3_COEF_SIZE 24
#define EOTF_COEFF_NORM(a) ((int)((((a) * 4096.0) + 1) / 2))
#define EOTF_COEFF_SIZE 10
#define EOTF_COEFF_RIGHTSHIFT 1
static int RGB709_to_YUV709l_coeff[MATRIX_5X3_COEF_SIZE] = {
0, 0, 0, /* pre offset */
COEFF_NORM(0.181873), COEFF_NORM(0.611831), COEFF_NORM(0.061765),
COEFF_NORM(-0.100251), COEFF_NORM(-0.337249), COEFF_NORM(0.437500),
COEFF_NORM(0.437500), COEFF_NORM(-0.397384), COEFF_NORM(-0.040116),
0, 0, 0, /* 10'/11'/12' */
0, 0, 0, /* 20'/21'/22' */
64, 512, 512, /* offset */
0, 0, 0 /* mode, right_shift, clip_en */
};
/* eotf matrix: bypass */
static int eotf_bypass_coeff[EOTF_COEFF_SIZE] = {
EOTF_COEFF_NORM(1.0), EOTF_COEFF_NORM(0.0), EOTF_COEFF_NORM(0.0),
EOTF_COEFF_NORM(0.0), EOTF_COEFF_NORM(1.0), EOTF_COEFF_NORM(0.0),
EOTF_COEFF_NORM(0.0), EOTF_COEFF_NORM(0.0), EOTF_COEFF_NORM(1.0),
EOTF_COEFF_RIGHTSHIFT /* right shift */
};
static void meson_viu_set_g12a_osd1_matrix(struct meson_drm *priv,
int *m, bool csc_on)
{
/* VPP WRAP OSD1 matrix */
writel(((m[0] & 0xfff) << 16) | (m[1] & 0xfff),
priv->io_base + _REG(VPP_WRAP_OSD1_MATRIX_PRE_OFFSET0_1));
writel(m[2] & 0xfff,
priv->io_base + _REG(VPP_WRAP_OSD1_MATRIX_PRE_OFFSET2));
writel(((m[3] & 0x1fff) << 16) | (m[4] & 0x1fff),
priv->io_base + _REG(VPP_WRAP_OSD1_MATRIX_COEF00_01));
writel(((m[5] & 0x1fff) << 16) | (m[6] & 0x1fff),
priv->io_base + _REG(VPP_WRAP_OSD1_MATRIX_COEF02_10));
writel(((m[7] & 0x1fff) << 16) | (m[8] & 0x1fff),
priv->io_base + _REG(VPP_WRAP_OSD1_MATRIX_COEF11_12));
writel(((m[9] & 0x1fff) << 16) | (m[10] & 0x1fff),
priv->io_base + _REG(VPP_WRAP_OSD1_MATRIX_COEF20_21));
writel((m[11] & 0x1fff) << 16,
priv->io_base + _REG(VPP_WRAP_OSD1_MATRIX_COEF22));
writel(((m[18] & 0xfff) << 16) | (m[19] & 0xfff),
priv->io_base + _REG(VPP_WRAP_OSD1_MATRIX_OFFSET0_1));
writel(m[20] & 0xfff,
priv->io_base + _REG(VPP_WRAP_OSD1_MATRIX_OFFSET2));
writel_bits_relaxed(BIT(0), csc_on ? BIT(0) : 0,
priv->io_base + _REG(VPP_WRAP_OSD1_MATRIX_EN_CTRL));
}
static void meson_viu_set_osd_matrix(struct meson_drm *priv,
enum viu_matrix_sel_e m_select,
int *m, bool csc_on)
{
if (m_select == VIU_MATRIX_OSD) {
/* osd matrix, VIU_MATRIX_0 */
writel(((m[0] & 0xfff) << 16) | (m[1] & 0xfff),
priv->io_base + _REG(VIU_OSD1_MATRIX_PRE_OFFSET0_1));
writel(m[2] & 0xfff,
priv->io_base + _REG(VIU_OSD1_MATRIX_PRE_OFFSET2));
writel(((m[3] & 0x1fff) << 16) | (m[4] & 0x1fff),
priv->io_base + _REG(VIU_OSD1_MATRIX_COEF00_01));
writel(((m[5] & 0x1fff) << 16) | (m[6] & 0x1fff),
priv->io_base + _REG(VIU_OSD1_MATRIX_COEF02_10));
writel(((m[7] & 0x1fff) << 16) | (m[8] & 0x1fff),
priv->io_base + _REG(VIU_OSD1_MATRIX_COEF11_12));
writel(((m[9] & 0x1fff) << 16) | (m[10] & 0x1fff),
priv->io_base + _REG(VIU_OSD1_MATRIX_COEF20_21));
if (m[21]) {
writel(((m[11] & 0x1fff) << 16) | (m[12] & 0x1fff),
priv->io_base +
_REG(VIU_OSD1_MATRIX_COEF22_30));
writel(((m[13] & 0x1fff) << 16) | (m[14] & 0x1fff),
priv->io_base +
_REG(VIU_OSD1_MATRIX_COEF31_32));
writel(((m[15] & 0x1fff) << 16) | (m[16] & 0x1fff),
priv->io_base +
_REG(VIU_OSD1_MATRIX_COEF40_41));
writel(m[17] & 0x1fff, priv->io_base +
_REG(VIU_OSD1_MATRIX_COLMOD_COEF42));
} else
writel((m[11] & 0x1fff) << 16, priv->io_base +
_REG(VIU_OSD1_MATRIX_COEF22_30));
writel(((m[18] & 0xfff) << 16) | (m[19] & 0xfff),
priv->io_base + _REG(VIU_OSD1_MATRIX_OFFSET0_1));
writel(m[20] & 0xfff,
priv->io_base + _REG(VIU_OSD1_MATRIX_OFFSET2));
writel_bits_relaxed(3 << 30, m[21] << 30,
priv->io_base + _REG(VIU_OSD1_MATRIX_COLMOD_COEF42));
writel_bits_relaxed(7 << 16, m[22] << 16,
priv->io_base + _REG(VIU_OSD1_MATRIX_COLMOD_COEF42));
/* 23 reserved for clipping control */
writel_bits_relaxed(BIT(0), csc_on ? BIT(0) : 0,
priv->io_base + _REG(VIU_OSD1_MATRIX_CTRL));
writel_bits_relaxed(BIT(1), 0,
priv->io_base + _REG(VIU_OSD1_MATRIX_CTRL));
} else if (m_select == VIU_MATRIX_OSD_EOTF) {
int i;
/* osd eotf matrix, VIU_MATRIX_OSD_EOTF */
for (i = 0; i < 5; i++)
writel(((m[i * 2] & 0x1fff) << 16) |
(m[i * 2 + 1] & 0x1fff), priv->io_base +
_REG(VIU_OSD1_EOTF_CTL + i + 1));
writel_bits_relaxed(BIT(30), csc_on ? BIT(30) : 0,
priv->io_base + _REG(VIU_OSD1_EOTF_CTL));
writel_bits_relaxed(BIT(31), csc_on ? BIT(31) : 0,
priv->io_base + _REG(VIU_OSD1_EOTF_CTL));
}
}
#define OSD_EOTF_LUT_SIZE 33
#define OSD_OETF_LUT_SIZE 41
static void
meson_viu_set_osd_lut(struct meson_drm *priv, enum viu_lut_sel_e lut_sel,
unsigned int *r_map, unsigned int *g_map,
unsigned int *b_map, bool csc_on)
{
unsigned int addr_port;
unsigned int data_port;
unsigned int ctrl_port;
int i;
if (lut_sel == VIU_LUT_OSD_EOTF) {
addr_port = VIU_OSD1_EOTF_LUT_ADDR_PORT;
data_port = VIU_OSD1_EOTF_LUT_DATA_PORT;
ctrl_port = VIU_OSD1_EOTF_CTL;
} else if (lut_sel == VIU_LUT_OSD_OETF) {
addr_port = VIU_OSD1_OETF_LUT_ADDR_PORT;
data_port = VIU_OSD1_OETF_LUT_DATA_PORT;
ctrl_port = VIU_OSD1_OETF_CTL;
} else
return;
if (lut_sel == VIU_LUT_OSD_OETF) {
writel(0, priv->io_base + _REG(addr_port));
for (i = 0; i < (OSD_OETF_LUT_SIZE / 2); i++)
writel(r_map[i * 2] | (r_map[i * 2 + 1] << 16),
priv->io_base + _REG(data_port));
writel(r_map[OSD_OETF_LUT_SIZE - 1] | (g_map[0] << 16),
priv->io_base + _REG(data_port));
for (i = 0; i < (OSD_OETF_LUT_SIZE / 2); i++)
writel(g_map[i * 2 + 1] | (g_map[i * 2 + 2] << 16),
priv->io_base + _REG(data_port));
for (i = 0; i < (OSD_OETF_LUT_SIZE / 2); i++)
writel(b_map[i * 2] | (b_map[i * 2 + 1] << 16),
priv->io_base + _REG(data_port));
writel(b_map[OSD_OETF_LUT_SIZE - 1],
priv->io_base + _REG(data_port));
if (csc_on)
writel_bits_relaxed(0x7 << 29, 7 << 29,
priv->io_base + _REG(ctrl_port));
else
writel_bits_relaxed(0x7 << 29, 0,
priv->io_base + _REG(ctrl_port));
} else if (lut_sel == VIU_LUT_OSD_EOTF) {
writel(0, priv->io_base + _REG(addr_port));
for (i = 0; i < (OSD_EOTF_LUT_SIZE / 2); i++)
writel(r_map[i * 2] | (r_map[i * 2 + 1] << 16),
priv->io_base + _REG(data_port));
writel(r_map[OSD_EOTF_LUT_SIZE - 1] | (g_map[0] << 16),
priv->io_base + _REG(data_port));
for (i = 0; i < (OSD_EOTF_LUT_SIZE / 2); i++)
writel(g_map[i * 2 + 1] | (g_map[i * 2 + 2] << 16),
priv->io_base + _REG(data_port));
for (i = 0; i < (OSD_EOTF_LUT_SIZE / 2); i++)
writel(b_map[i * 2] | (b_map[i * 2 + 1] << 16),
priv->io_base + _REG(data_port));
writel(b_map[OSD_EOTF_LUT_SIZE - 1],
priv->io_base + _REG(data_port));
if (csc_on)
writel_bits_relaxed(7 << 27, 7 << 27,
priv->io_base + _REG(ctrl_port));
else
writel_bits_relaxed(7 << 27, 0,
priv->io_base + _REG(ctrl_port));
writel_bits_relaxed(BIT(31), BIT(31),
priv->io_base + _REG(ctrl_port));
}
}
/* eotf lut: linear */
static unsigned int eotf_33_linear_mapping[OSD_EOTF_LUT_SIZE] = {
0x0000, 0x0200, 0x0400, 0x0600,
0x0800, 0x0a00, 0x0c00, 0x0e00,
0x1000, 0x1200, 0x1400, 0x1600,
0x1800, 0x1a00, 0x1c00, 0x1e00,
0x2000, 0x2200, 0x2400, 0x2600,
0x2800, 0x2a00, 0x2c00, 0x2e00,
0x3000, 0x3200, 0x3400, 0x3600,
0x3800, 0x3a00, 0x3c00, 0x3e00,
0x4000
};
/* osd oetf lut: linear */
static unsigned int oetf_41_linear_mapping[OSD_OETF_LUT_SIZE] = {
0, 0, 0, 0,
0, 32, 64, 96,
128, 160, 196, 224,
256, 288, 320, 352,
384, 416, 448, 480,
512, 544, 576, 608,
640, 672, 704, 736,
768, 800, 832, 864,
896, 928, 960, 992,
1023, 1023, 1023, 1023,
1023
};
static void meson_viu_load_matrix(struct meson_drm *priv)
{
/* eotf lut bypass */
meson_viu_set_osd_lut(priv, VIU_LUT_OSD_EOTF,
eotf_33_linear_mapping, /* R */
eotf_33_linear_mapping, /* G */
eotf_33_linear_mapping, /* B */
false);
/* eotf matrix bypass */
meson_viu_set_osd_matrix(priv, VIU_MATRIX_OSD_EOTF,
eotf_bypass_coeff,
false);
/* oetf lut bypass */
meson_viu_set_osd_lut(priv, VIU_LUT_OSD_OETF,
oetf_41_linear_mapping, /* R */
oetf_41_linear_mapping, /* G */
oetf_41_linear_mapping, /* B */
false);
/* osd matrix RGB709 to YUV709 limit */
meson_viu_set_osd_matrix(priv, VIU_MATRIX_OSD,
RGB709_to_YUV709l_coeff,
true);
}
/* VIU OSD1 Reset as workaround for GXL+ Alpha OSD Bug */
void meson_viu_osd1_reset(struct meson_drm *priv)
{
uint32_t osd1_fifo_ctrl_stat, osd1_ctrl_stat2;
/* Save these 2 registers state */
osd1_fifo_ctrl_stat = readl_relaxed(
priv->io_base + _REG(VIU_OSD1_FIFO_CTRL_STAT));
osd1_ctrl_stat2 = readl_relaxed(
priv->io_base + _REG(VIU_OSD1_CTRL_STAT2));
/* Reset OSD1 */
writel_bits_relaxed(VIU_SW_RESET_OSD1, VIU_SW_RESET_OSD1,
priv->io_base + _REG(VIU_SW_RESET));
writel_bits_relaxed(VIU_SW_RESET_OSD1, 0,
priv->io_base + _REG(VIU_SW_RESET));
/* Rewrite these registers state lost in the reset */
writel_relaxed(osd1_fifo_ctrl_stat,
priv->io_base + _REG(VIU_OSD1_FIFO_CTRL_STAT));
writel_relaxed(osd1_ctrl_stat2,
priv->io_base + _REG(VIU_OSD1_CTRL_STAT2));
/* Reload the conversion matrix */
meson_viu_load_matrix(priv);
}
#define OSD1_MALI_ORDER_ABGR \
(FIELD_PREP(VIU_OSD1_MALI_AFBCD_A_REORDER, \
VIU_OSD1_MALI_REORDER_A) | \
FIELD_PREP(VIU_OSD1_MALI_AFBCD_B_REORDER, \
VIU_OSD1_MALI_REORDER_B) | \
FIELD_PREP(VIU_OSD1_MALI_AFBCD_G_REORDER, \
VIU_OSD1_MALI_REORDER_G) | \
FIELD_PREP(VIU_OSD1_MALI_AFBCD_R_REORDER, \
VIU_OSD1_MALI_REORDER_R))
#define OSD1_MALI_ORDER_ARGB \
(FIELD_PREP(VIU_OSD1_MALI_AFBCD_A_REORDER, \
VIU_OSD1_MALI_REORDER_A) | \
FIELD_PREP(VIU_OSD1_MALI_AFBCD_B_REORDER, \
VIU_OSD1_MALI_REORDER_R) | \
FIELD_PREP(VIU_OSD1_MALI_AFBCD_G_REORDER, \
VIU_OSD1_MALI_REORDER_G) | \
FIELD_PREP(VIU_OSD1_MALI_AFBCD_R_REORDER, \
VIU_OSD1_MALI_REORDER_B))
void meson_viu_g12a_enable_osd1_afbc(struct meson_drm *priv)
{
u32 afbc_order = OSD1_MALI_ORDER_ARGB;
/* Enable Mali AFBC Unpack */
writel_bits_relaxed(VIU_OSD1_MALI_UNPACK_EN,
VIU_OSD1_MALI_UNPACK_EN,
priv->io_base + _REG(VIU_OSD1_MALI_UNPACK_CTRL));
switch (priv->afbcd.format) {
case DRM_FORMAT_XBGR8888:
case DRM_FORMAT_ABGR8888:
afbc_order = OSD1_MALI_ORDER_ABGR;
break;
}
/* Setup RGBA Reordering */
writel_bits_relaxed(VIU_OSD1_MALI_AFBCD_A_REORDER |
VIU_OSD1_MALI_AFBCD_B_REORDER |
VIU_OSD1_MALI_AFBCD_G_REORDER |
VIU_OSD1_MALI_AFBCD_R_REORDER,
afbc_order,
priv->io_base + _REG(VIU_OSD1_MALI_UNPACK_CTRL));
/* Select AFBCD path for OSD1 */
writel_bits_relaxed(OSD_PATH_OSD_AXI_SEL_OSD1_AFBCD,
OSD_PATH_OSD_AXI_SEL_OSD1_AFBCD,
priv->io_base + _REG(OSD_PATH_MISC_CTRL));
}
void meson_viu_g12a_disable_osd1_afbc(struct meson_drm *priv)
{
/* Disable AFBCD path for OSD1 */
writel_bits_relaxed(OSD_PATH_OSD_AXI_SEL_OSD1_AFBCD, 0,
priv->io_base + _REG(OSD_PATH_MISC_CTRL));
/* Disable AFBCD unpack */
writel_bits_relaxed(VIU_OSD1_MALI_UNPACK_EN, 0,
priv->io_base + _REG(VIU_OSD1_MALI_UNPACK_CTRL));
}
void meson_viu_gxm_enable_osd1_afbc(struct meson_drm *priv)
{
writel_bits_relaxed(MALI_AFBC_MISC, FIELD_PREP(MALI_AFBC_MISC, 0x90),
priv->io_base + _REG(VIU_MISC_CTRL1));
}
void meson_viu_gxm_disable_osd1_afbc(struct meson_drm *priv)
{
writel_bits_relaxed(MALI_AFBC_MISC, FIELD_PREP(MALI_AFBC_MISC, 0x00),
priv->io_base + _REG(VIU_MISC_CTRL1));
}
void meson_viu_init(struct meson_drm *priv)
{
uint32_t reg;
/* Disable OSDs */
writel_bits_relaxed(VIU_OSD1_OSD_BLK_ENABLE | VIU_OSD1_OSD_ENABLE, 0,
priv->io_base + _REG(VIU_OSD1_CTRL_STAT));
writel_bits_relaxed(VIU_OSD1_OSD_BLK_ENABLE | VIU_OSD1_OSD_ENABLE, 0,
priv->io_base + _REG(VIU_OSD2_CTRL_STAT));
/* On GXL/GXM, Use the 10bit HDR conversion matrix */
if (meson_vpu_is_compatible(priv, VPU_COMPATIBLE_GXM) ||
meson_vpu_is_compatible(priv, VPU_COMPATIBLE_GXL))
meson_viu_load_matrix(priv);
else if (meson_vpu_is_compatible(priv, VPU_COMPATIBLE_G12A))
meson_viu_set_g12a_osd1_matrix(priv, RGB709_to_YUV709l_coeff,
true);
/* Initialize OSD1 fifo control register */
reg = VIU_OSD_DDR_PRIORITY_URGENT |
VIU_OSD_HOLD_FIFO_LINES(31) |
VIU_OSD_FIFO_DEPTH_VAL(32) | /* fifo_depth_val: 32*8=256 */
VIU_OSD_WORDS_PER_BURST(4) | /* 4 words in 1 burst */
VIU_OSD_FIFO_LIMITS(2); /* fifo_lim: 2*16=32 */
if (meson_vpu_is_compatible(priv, VPU_COMPATIBLE_G12A))
reg |= VIU_OSD_BURST_LENGTH_32;
else
reg |= VIU_OSD_BURST_LENGTH_64;
writel_relaxed(reg, priv->io_base + _REG(VIU_OSD1_FIFO_CTRL_STAT));
writel_relaxed(reg, priv->io_base + _REG(VIU_OSD2_FIFO_CTRL_STAT));
/* Set OSD alpha replace value */
writel_bits_relaxed(0xff << OSD_REPLACE_SHIFT,
0xff << OSD_REPLACE_SHIFT,
priv->io_base + _REG(VIU_OSD1_CTRL_STAT2));
writel_bits_relaxed(0xff << OSD_REPLACE_SHIFT,
0xff << OSD_REPLACE_SHIFT,
priv->io_base + _REG(VIU_OSD2_CTRL_STAT2));
/* Disable VD1 AFBC */
/* di_mif0_en=0 mif0_to_vpp_en=0 di_mad_en=0 and afbc vd1 set=0*/
writel_bits_relaxed(VIU_CTRL0_VD1_AFBC_MASK, 0,
priv->io_base + _REG(VIU_MISC_CTRL0));
writel_relaxed(0, priv->io_base + _REG(AFBC_ENABLE));
writel_relaxed(0x00FF00C0,
priv->io_base + _REG(VD1_IF0_LUMA_FIFO_SIZE));
writel_relaxed(0x00FF00C0,
priv->io_base + _REG(VD2_IF0_LUMA_FIFO_SIZE));
if (meson_vpu_is_compatible(priv, VPU_COMPATIBLE_G12A)) {
writel_relaxed(VIU_OSD_BLEND_REORDER(0, 1) |
VIU_OSD_BLEND_REORDER(1, 0) |
VIU_OSD_BLEND_REORDER(2, 0) |
VIU_OSD_BLEND_REORDER(3, 0) |
VIU_OSD_BLEND_DIN_EN(1) |
VIU_OSD_BLEND1_DIN3_BYPASS_TO_DOUT1 |
VIU_OSD_BLEND1_DOUT_BYPASS_TO_BLEND2 |
VIU_OSD_BLEND_DIN0_BYPASS_TO_DOUT0 |
VIU_OSD_BLEND_BLEN2_PREMULT_EN(1) |
VIU_OSD_BLEND_HOLD_LINES(4),
priv->io_base + _REG(VIU_OSD_BLEND_CTRL));
writel_relaxed(OSD_BLEND_PATH_SEL_ENABLE,
priv->io_base + _REG(OSD1_BLEND_SRC_CTRL));
writel_relaxed(OSD_BLEND_PATH_SEL_ENABLE,
priv->io_base + _REG(OSD2_BLEND_SRC_CTRL));
writel_relaxed(0, priv->io_base + _REG(VD1_BLEND_SRC_CTRL));
writel_relaxed(0, priv->io_base + _REG(VD2_BLEND_SRC_CTRL));
writel_relaxed(0,
priv->io_base + _REG(VIU_OSD_BLEND_DUMMY_DATA0));
writel_relaxed(0,
priv->io_base + _REG(VIU_OSD_BLEND_DUMMY_ALPHA));
writel_bits_relaxed(DOLBY_BYPASS_EN(0xc), DOLBY_BYPASS_EN(0xc),
priv->io_base + _REG(DOLBY_PATH_CTRL));
meson_viu_g12a_disable_osd1_afbc(priv);
}
if (meson_vpu_is_compatible(priv, VPU_COMPATIBLE_GXM))
meson_viu_gxm_disable_osd1_afbc(priv);
priv->viu.osd1_enabled = false;
priv->viu.osd1_commit = false;
priv->viu.osd1_interlace = false;
}
| {
"pile_set_name": "Github"
} |
# Locate Apple QTKit (next-generation QuickTime)
# This module defines
# QTKIT_LIBRARY
# QTKIT_FOUND, if false, do not try to link to gdal
# QTKIT_INCLUDE_DIR, where to find the headers
#
# $QTKIT_DIR is an environment variable that would
# correspond to the ./configure --prefix=$QTKIT_DIR
#
# Created by Eric Wing.
# QTKit on OS X looks different than QTKit for Windows,
# so I am going to case the two.
IF(APPLE)
FIND_PATH(QTKIT_INCLUDE_DIR QTKit/QTKit.h)
FIND_LIBRARY(QTKIT_LIBRARY QTKit)
ENDIF()
SET(QTKIT_FOUND "NO")
IF(QTKIT_LIBRARY AND QTKIT_INCLUDE_DIR)
SET(QTKIT_FOUND "YES")
ENDIF()
| {
"pile_set_name": "Github"
} |
ALTER TABLE db_version CHANGE COLUMN required_s0028_10208_01_mangos_playercreateinfo required_s0038_10251_01_mangos_command bit;
DELETE FROM command WHERE name = 'wp';
| {
"pile_set_name": "Github"
} |
@interface Root
+(Class)class;
@end
__attribute__((objc_runtime_visible))
__attribute__((objc_runtime_name("MyRuntimeVisibleClass")))
@interface A : Root
@end
| {
"pile_set_name": "Github"
} |
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width initial-scale=1 user-scalable=no maximum-scale=1">
<title>Basic Scrolling</title>
<link rel="stylesheet" href="../css/pure-nr-min.css">
<link rel="stylesheet" href="../css/style.css">
<script src="scroll.js"></script>
</head>
<body>
<div id="indicator"></div>
<div class="pure-g" id="content">
<div class="pure-u-1" id="view">
<aside>#1: Basic touch-and-drag scrolling.<br/>No momentum effect.</aside>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus eget purus libero. Nulla ut pretium libero. Vestibulum adipiscing quam ac sapien scelerisque, a posuere sem dictum. Ut aliquet lectus ut nibh dapibus cursus. Donec quam libero, aliquam nec aliquam quis, feugiat quis metus. Phasellus ac orci mauris. Cras hendrerit suscipit nisi, eget varius mi condimentum vel. Donec id libero magna. Nam scelerisque nisi tellus, ut cursus ipsum imperdiet eget. Donec porttitor non lectus ut lacinia. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Ut egestas commodo facilisis. Etiam orci nibh, pellentesque sed ipsum consequat, faucibus tempus augue. Cras iaculis diam in auctor bibendum.
</p>
<p>
Nulla ornare, nisl vel condimentum bibendum, quam velit vestibulum sem, vel aliquam tellus urna vitae justo. Aenean elementum semper nulla, a mattis tellus venenatis in. Nulla rhoncus felis risus, sed convallis libero viverra at. Aenean at lobortis neque. Vivamus viverra lectus id libero congue bibendum. Curabitur id est et arcu dapibus laoreet. Duis imperdiet elit et mauris adipiscing, vehicula vulputate nisi accumsan. Nunc varius ante lorem, eget volutpat sem mollis blandit.
</p>
<p>
Donec tincidunt rutrum tincidunt. Duis viverra sem in metus sodales, sed suscipit turpis aliquet. Etiam eleifend id dolor eget hendrerit. Curabitur pulvinar lacus et sapien dictum feugiat. Praesent iaculis sagittis ipsum nec semper. Nam pellentesque tortor ac nibh egestas dignissim. Curabitur sit amet auctor velit. Fusce nisl diam, placerat eget consectetur in, congue ut sapien. In in facilisis felis. Nulla faucibus magna eget odio tincidunt rhoncus. In ac molestie lorem. Aliquam pulvinar porta nibh id pulvinar. Morbi id gravida libero. Nam consectetur, metus sit amet tincidunt varius, nibh tortor molestie nulla, non semper risus ligula non lectus.
</p>
<p>
Phasellus imperdiet tincidunt ultricies. Vivamus mi tellus, pellentesque sed venenatis et, imperdiet at tellus. Fusce ut dui lobortis, sodales libero eget, elementum lacus. Nullam nisi urna, semper eget consequat at, sollicitudin non justo. Mauris consequat velit feugiat mollis bibendum. Aliquam mi enim, porta et vestibulum at, ultrices id ante. Ut vitae est non justo hendrerit pellentesque vel nec urna. Pellentesque gravida consequat quam at scelerisque. Proin mauris purus, euismod sit amet dui et, tempor feugiat est. Maecenas sed pretium quam, vitae sagittis nisl. Donec sed augue bibendum, elementum nulla tincidunt, semper risus.
</p>
<p>
Suspendisse molestie placerat eros et posuere. Nullam tellus nisi, fermentum eu felis quis, consequat vestibulum odio. Interdum et malesuada fames ac ante ipsum primis in faucibus. Fusce congue pellentesque felis a venenatis. Morbi lacus libero, ornare id velit sit amet, gravida viverra elit. Proin id tellus nec lacus pulvinar tempor. Aliquam eu ligula nisi. Pellentesque interdum imperdiet urna at tristique. Duis nunc sapien, tincidunt nec posuere ac, scelerisque sed justo. Maecenas in ultricies arcu, eget mattis enim. Duis sollicitudin nec mauris sed interdum. Fusce et viverra dolor, vitae ullamcorper mauris. Nulla quis libero in dolor pellentesque convallis nec quis sem. Nulla quis malesuada dui. Mauris non vehicula arcu, non elementum turpis.
</p>
<p>
Praesent faucibus, ipsum et rhoncus vestibulum, lacus tortor pellentesque lorem, vel elementum nunc lectus et est. Mauris semper lacinia sapien, nec consectetur elit adipiscing consectetur. In hac habitasse platea dictumst. Maecenas velit elit, placerat et quam at, commodo commodo ante. Praesent vel nulla dui. Phasellus rutrum velit nec dui dignissim, vitae tincidunt augue ultricies. Ut tincidunt sem ut viverra gravida. Vestibulum pellentesque ligula eget orci commodo venenatis. Donec metus urna, congue et adipiscing nec, placerat ac dui. Proin vel euismod magna, in venenatis tortor. Mauris pellentesque libero eu quam hendrerit porttitor. Proin lobortis lectus sed urna consequat euismod a et nibh. Suspendisse lacinia blandit nibh, nec tincidunt odio feugiat vitae. Nulla rhoncus tellus sed risus mattis, placerat imperdiet elit gravida. Vivamus fringilla, dui quis faucibus volutpat, lorem orci tristique urna, sed convallis turpis ipsum rutrum dolor.
</p>
<p>
Aliquam turpis velit, pulvinar vitae vestibulum vel, volutpat a lorem. Aenean mattis ut felis ut egestas. Sed quis sapien quam. Fusce risus ligula, malesuada sed venenatis at, cursus nec enim. Phasellus ac dolor auctor mauris porta cursus. Proin tincidunt libero pulvinar, dapibus ligula nec, venenatis purus. Maecenas mauris nulla, faucibus ac posuere at, semper sollicitudin arcu. Fusce facilisis sem erat. Etiam vel augue sapien. Suspendisse potenti. Etiam aliquet semper nunc, in scelerisque nibh dapibus sit amet. Duis iaculis tempus magna sit amet posuere. Cras ac bibendum purus.
</p>
<p>
Fusce non risus placerat, vestibulum metus non, varius tellus. Etiam quis augue vitae lorem dignissim condimentum at ac ante. Aliquam dignissim eros orci, nec aliquet arcu euismod in. Maecenas dictum dui a tristique fringilla. Aliquam dui turpis, congue vitae metus nec, cursus ornare lectus. Pellentesque interdum erat ac placerat volutpat. Nulla feugiat, ligula a lobortis rutrum, sem libero tristique nisi, quis aliquam ligula nisl id erat. Vestibulum quam diam, gravida vitae enim eu, ornare posuere nisi. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut luctus nibh justo, luctus luctus ligula suscipit sit amet.
</p>
<p>
Proin at arcu nibh. Proin venenatis magna accumsan, bibendum augue adipiscing, facilisis lacus. Cras lectus urna, facilisis quis adipiscing non, blandit et arcu. Suspendisse sagittis adipiscing purus at convallis. Etiam consequat urna erat, at varius neque euismod quis. Pellentesque euismod urna quis sem faucibus pellentesque. Nam egestas, quam porta facilisis ultricies, velit nisi posuere sapien, quis facilisis lacus dolor id justo. Vestibulum mattis erat sed iaculis vulputate.
</p>
<p>
Vestibulum tincidunt vestibulum turpis, in scelerisque nibh. Cras nunc metus, cursus in lectus eu, mollis adipiscing erat. Vivamus venenatis nibh quam, at posuere tortor rhoncus eu. Donec nunc tortor, dictum quis sagittis nec, imperdiet a turpis. Cras sodales ante mauris, eget tincidunt mauris ultricies in. Mauris hendrerit aliquam sem, at commodo orci volutpat vel. In dolor felis, congue vitae orci ut, mollis tristique diam. Praesent diam erat, pretium in ipsum non, cursus rutrum lectus. Ut vitae arcu eu neque porta egestas. Nam id nisl semper, tristique ligula vitae, interdum diam. Phasellus et nisi non nunc posuere rutrum. Praesent eu arcu quam. Fusce sed elit urna.
</p>
<p>(END OF TEXT)</p>
</div>
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
# Rtc Streaming Cloud Server-Side Library For PHP
## Features
- Appclient
- [x] 创建房间: client->createApp()
- [x] 查看房间: client->getApp()
- [x] 删除房间: client->deleteApp()
- [x] 生成房间token: client->appToken()
## Contents
- [Installation](#installation)
- [Usage](#usage)
- [Configuration](#configuration)
- [App](#app)
- [Create a app](#create-a-app)
- [Get a app](#get-a-app)
- [Delete a app](#delete-a-app)
- [Generate a app token](#generate-a-app-token)
## Usage
### App
#### Create a app
```php
$ak = "gwd_gV4gPKZZsmEOvAuNU1AcumicmuHooTfu64q5";
$sk = "xxxx";
$auth = new Auth($ak, $sk);
$client = new Qiniu\Rtc\AppClient($auth);
$resp=$client->createApp("901","testApp");
print_r($resp);
```
#### Get an app
```php
$ak = "gwd_gV4gPKZZsmEOvAuNU1AcumicmuHooTfu64q5";
$sk = "xxxx";
$auth = new Auth($ak, $sk);
$client = new Qiniu\Rtc\AppClient($auth);
$resp=$client->getApp("deq02uhb6");
print_r($resp);
```
#### Delete an app
```php
$ak = "gwd_gV4gPKZZsmEOvAuNU1AcumicmuHooTfu64q5";
$sk = "xxxx";
$auth = new Auth($ak, $sk);
$client = new Qiniu\Rtc\AppClient($auth);
$resp=$client->deleteApp("deq02uhb6");
print_r($resp);
```
#### Generate an app token
```php
$ak = "gwd_gV4gPKZZsmEOvAuNU1AcumicmuHooTfu64q5";
$sk = "xxxx";
$auth = new Auth($ak, $sk);
$client = new Qiniu\Rtc\AppClient($auth);
$resp=$client->appToken("deq02uhb6", "lfx", '1111', (time()+3600), 'user');
print_r($resp);
``` | {
"pile_set_name": "Github"
} |
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace EffectsDemo
{
public class App : Application
{
public App()
{
MainPage = new HomePage();
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
| {
"pile_set_name": "Github"
} |
/*
* Unit Tests
*
*/
// Dependencies
var helpers = require('./../lib/helpers.js');
var logs = require('./../lib/logs.js');
var exampleDebuggingProblem = require('./../lib/exampleDebuggingProblem.js');
var assert = require('assert');
// Holder for Tests
var unit = {};
// Assert that the getANumber function is returning a number
unit['helpers.getANumber should return a number'] = function(done){
var val = helpers.getANumber();
assert.equal(typeof(val), 'number');
done();
};
// Assert that the getANumber function is returning 1
unit['helpers.getANumber should return 1'] = function(done){
var val = helpers.getANumber();
assert.equal(val, 1);
done();
};
// Assert that the getANumber function is returning 2
unit['helpers.getNumberOne should return 2'] = function(done){
var val = helpers.getANumber();
assert.equal(val, 2);
done();
};
// Logs.list should callback an array and a false error
unit['logs.list should callback a false error and an array of log names'] = function(done){
logs.list(true,function(err,logFileNames){
assert.equal(err, false);
assert.ok(logFileNames instanceof Array);
assert.ok(logFileNames.length > 1);
done();
});
};
// Logs.truncate should not throw if the logId doesnt exist
unit['logs.truncate should not throw if the logId does not exist, should callback an error instead'] = function(done){
assert.doesNotThrow(function(){
logs.truncate('I do not exist',function(err){
assert.ok(err);
done();
})
},TypeError);
};
// exampleDebuggingProblem.init should not throw (but it does)
unit['exampleDebuggingProblem.init should not throw when called'] = function(done){
assert.doesNotThrow(function(){
exampleDebuggingProblem.init();
done();
},TypeError);
};
// Export the tests to the runner
module.exports = unit;
| {
"pile_set_name": "Github"
} |
# Welcome!
The Carbon team is committed to maintaining consistent, quality guidelines. We welcome all feedback, designs, or ideas in order to produce the best possible experience for our users.
If you're interested in contributing please follow the guidelines below.
If you have any questions, reach out to us at [email protected].
## Contributing process
### 1. Submit an issue
The easiest way for us to get an understanding of your needs is to open an issue. Follow our issue template (you'll see this when you go to open an issue) to ensure you are meeting the issue writing requirements. Screenshots are required when submitting a new pattern or component. A member of the Carbon team will respond to your issue with next steps or a follow up.
**Not sure where to open an issue?**
The [carbon-design-kit repo](https://github.com/carbon-design-system/carbon-design-kit) is for Sketch and Craft bugs, as well as feedback on the Design Kit and component design.
The [design-system-website repo](https://github.com/carbon-design-system/design-system-website) is for Carbon website specific feedback or bugs.
**Not sure how to submit an issue?**
It's not so bad, we promise! You can read a [tutorial](https://help.github.com/articles/creating-an-issue/) on GitHub to get familiar with best practices.
### 2. Design review and sync
The easiest way to move forward in the design process is to set up an in-person or remote call with the Carbon team to go over your design work. We'll provide you with feedback on your proposal and what, if any, changes are needed before bringing them into Carbon.
**What does it take for your design to pass Carbon's design review?**
The Carbon team will look for a few major things:
### Accessible
* Is your design WCAG AA accessible?
* Does your design pass [color contrast](https://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html) ratio?
* Have you considered [keyboard tabbing](http://carbondesignsystem.com/guidelines/accessibility) and focus states?
### Componentized
Most components we accept into the global library need to work universally across products.
* Have you tested this design for multiple use cases? It needs to be a pattern that all teams can utilize, and global enough to fit use cases for other teams.
* Is there a similiar component in the library that already exists?
* What are the advantages of this pattern over alternative patterns?
### Visual style and UX patterns
* Is your design consistent with our default visual [style](http://carbondesignsystem.com/themes) we have established for the core Carbon library?
* Do your interaction patterns (hover, focus, motion, animations) match existing Carbon styles?
* Does your design follow basic UX best practices?
* Does your design promote clear language, correct grammar, and support globalization?
<hr>
_Please make sure you have run through these design guidelines prior to the initial design review meeting. The Carbon team will be looking for the points mentioned above._
### 3. Roadmap
We'll work with your team to determine when your design will be implemented into Carbon, and the logistics behind it. Development resources are greatly appreciated and welcomed. If your pattern is submitted without any code, please keep in mind it may be delayed from getting released into the Carbon component library until we can fit it into our team sprint schedule.
| {
"pile_set_name": "Github"
} |
<resources>
<string name="app_name">Modalfy</string>
</resources>
| {
"pile_set_name": "Github"
} |
//
// The MIT License (MIT)
//
// Copyright © 2016 Tag Games. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#ifndef _CHILLISOURCE_CORE_FILE_FILESTREAM_ITEXTINPUTSTREAM_H_
#define _CHILLISOURCE_CORE_FILE_FILESTREAM_ITEXTINPUTSTREAM_H_
#include <ChilliSource/ChilliSource.h>
namespace ChilliSource
{
/// Interface for classes to provide textual read functionality for a file
///
/// Implementations shoud be considered thread agnostic, but not thread-safe.
/// i.e. Instances can be used by one thread at a time. It doesn't matter
/// which thread as long as any previous threads are no longer accessing it
///
class ITextInputStream
{
public:
/// Checks the status of the stream, if this returns false then the stream
/// can no longer be accessed.
///
/// @return If the stream is valid and available for use.
///
virtual bool IsValid() const noexcept = 0;
/// @return Length of stream in bytes.
///
virtual u64 GetLength() const noexcept = 0;
/// Gets the position from which the next read operation will begin. The position
/// is always specified relative to the start of the file
///
/// @return The position from the start of the stream.
///
virtual u64 GetReadPosition() noexcept = 0;
/// Sets the position through the stream from which the next read operation will
/// begin. The position is always specified relative to the start of the file. This does
/// not affect the output of ReadAll().
///
/// @param readPosition
/// The position from the start of the stream.
///
virtual void SetReadPosition(u64 readPosition) noexcept = 0;
/// @return String containing the contents of the text file, including newlines
///
virtual std::string ReadAll() noexcept = 0;
/// Reads from the current read position until the newline character ('\n') or EOF
/// is reached. If the current read position is at the end of the file on entrance
/// then this will return false
///
/// @param line
/// String buffer that will be populated, this will not contain newline characters
///
/// @return If a line was read successfully
///
virtual bool ReadLine(std::string& line) noexcept = 0;
/// Reads in a number of characters from the current read position and puts them
/// into the passed in string. If the length of the stream is overrun, readChars
/// will contain everything up to that point.
///
/// If the current read position is at the end of the file, this function will return
/// false.
///
/// @param length
/// The number of characters to read
///
/// @param readChars
/// A string to hold the read characters, including newlines
///
/// @return If the read was successfull
///
virtual bool Read(u64 length, std::string& readLine) noexcept = 0;
/// Destructor
///
virtual ~ITextInputStream() noexcept {};
};
}
#endif | {
"pile_set_name": "Github"
} |
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_RSA_H
# define HEADER_RSA_H
# include <openssl/opensslconf.h>
# ifndef OPENSSL_NO_RSA
# include <openssl/asn1.h>
# include <openssl/bio.h>
# include <openssl/crypto.h>
# include <openssl/ossl_typ.h>
# if OPENSSL_API_COMPAT < 0x10100000L
# include <openssl/bn.h>
# endif
# ifdef __cplusplus
extern "C" {
# endif
/* The types RSA and RSA_METHOD are defined in ossl_typ.h */
# ifndef OPENSSL_RSA_MAX_MODULUS_BITS
# define OPENSSL_RSA_MAX_MODULUS_BITS 16384
# endif
# define OPENSSL_RSA_FIPS_MIN_MODULUS_BITS 1024
# ifndef OPENSSL_RSA_SMALL_MODULUS_BITS
# define OPENSSL_RSA_SMALL_MODULUS_BITS 3072
# endif
# ifndef OPENSSL_RSA_MAX_PUBEXP_BITS
/* exponent limit enforced for "large" modulus only */
# define OPENSSL_RSA_MAX_PUBEXP_BITS 64
# endif
# define RSA_3 0x3L
# define RSA_F4 0x10001L
# define RSA_METHOD_FLAG_NO_CHECK 0x0001/* don't check pub/private
* match */
# define RSA_FLAG_CACHE_PUBLIC 0x0002
# define RSA_FLAG_CACHE_PRIVATE 0x0004
# define RSA_FLAG_BLINDING 0x0008
# define RSA_FLAG_THREAD_SAFE 0x0010
/*
* This flag means the private key operations will be handled by rsa_mod_exp
* and that they do not depend on the private key components being present:
* for example a key stored in external hardware. Without this flag
* bn_mod_exp gets called when private key components are absent.
*/
# define RSA_FLAG_EXT_PKEY 0x0020
/*
* new with 0.9.6j and 0.9.7b; the built-in
* RSA implementation now uses blinding by
* default (ignoring RSA_FLAG_BLINDING),
* but other engines might not need it
*/
# define RSA_FLAG_NO_BLINDING 0x0080
# if OPENSSL_API_COMPAT < 0x10100000L
/*
* Does nothing. Previously this switched off constant time behaviour.
*/
# define RSA_FLAG_NO_CONSTTIME 0x0000
# endif
# if OPENSSL_API_COMPAT < 0x00908000L
/* deprecated name for the flag*/
/*
* new with 0.9.7h; the built-in RSA
* implementation now uses constant time
* modular exponentiation for secret exponents
* by default. This flag causes the
* faster variable sliding window method to
* be used for all exponents.
*/
# define RSA_FLAG_NO_EXP_CONSTTIME RSA_FLAG_NO_CONSTTIME
# endif
# define EVP_PKEY_CTX_set_rsa_padding(ctx, pad) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, -1, EVP_PKEY_CTRL_RSA_PADDING, \
pad, NULL)
# define EVP_PKEY_CTX_get_rsa_padding(ctx, ppad) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, -1, \
EVP_PKEY_CTRL_GET_RSA_PADDING, 0, ppad)
# define EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx, len) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, \
(EVP_PKEY_OP_SIGN|EVP_PKEY_OP_VERIFY), \
EVP_PKEY_CTRL_RSA_PSS_SALTLEN, \
len, NULL)
# define EVP_PKEY_CTX_get_rsa_pss_saltlen(ctx, plen) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, \
(EVP_PKEY_OP_SIGN|EVP_PKEY_OP_VERIFY), \
EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN, \
0, plen)
# define EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, bits) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_KEYGEN, \
EVP_PKEY_CTRL_RSA_KEYGEN_BITS, bits, NULL)
# define EVP_PKEY_CTX_set_rsa_keygen_pubexp(ctx, pubexp) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_KEYGEN, \
EVP_PKEY_CTRL_RSA_KEYGEN_PUBEXP, 0, pubexp)
# define EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, md) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, \
EVP_PKEY_OP_TYPE_SIG | EVP_PKEY_OP_TYPE_CRYPT, \
EVP_PKEY_CTRL_RSA_MGF1_MD, 0, (void *)md)
# define EVP_PKEY_CTX_set_rsa_oaep_md(ctx, md) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT, \
EVP_PKEY_CTRL_RSA_OAEP_MD, 0, (void *)md)
# define EVP_PKEY_CTX_get_rsa_mgf1_md(ctx, pmd) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, \
EVP_PKEY_OP_TYPE_SIG | EVP_PKEY_OP_TYPE_CRYPT, \
EVP_PKEY_CTRL_GET_RSA_MGF1_MD, 0, (void *)pmd)
# define EVP_PKEY_CTX_get_rsa_oaep_md(ctx, pmd) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT, \
EVP_PKEY_CTRL_GET_RSA_OAEP_MD, 0, (void *)pmd)
# define EVP_PKEY_CTX_set0_rsa_oaep_label(ctx, l, llen) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT, \
EVP_PKEY_CTRL_RSA_OAEP_LABEL, llen, (void *)l)
# define EVP_PKEY_CTX_get0_rsa_oaep_label(ctx, l) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT, \
EVP_PKEY_CTRL_GET_RSA_OAEP_LABEL, 0, (void *)l)
# define EVP_PKEY_CTRL_RSA_PADDING (EVP_PKEY_ALG_CTRL + 1)
# define EVP_PKEY_CTRL_RSA_PSS_SALTLEN (EVP_PKEY_ALG_CTRL + 2)
# define EVP_PKEY_CTRL_RSA_KEYGEN_BITS (EVP_PKEY_ALG_CTRL + 3)
# define EVP_PKEY_CTRL_RSA_KEYGEN_PUBEXP (EVP_PKEY_ALG_CTRL + 4)
# define EVP_PKEY_CTRL_RSA_MGF1_MD (EVP_PKEY_ALG_CTRL + 5)
# define EVP_PKEY_CTRL_GET_RSA_PADDING (EVP_PKEY_ALG_CTRL + 6)
# define EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN (EVP_PKEY_ALG_CTRL + 7)
# define EVP_PKEY_CTRL_GET_RSA_MGF1_MD (EVP_PKEY_ALG_CTRL + 8)
# define EVP_PKEY_CTRL_RSA_OAEP_MD (EVP_PKEY_ALG_CTRL + 9)
# define EVP_PKEY_CTRL_RSA_OAEP_LABEL (EVP_PKEY_ALG_CTRL + 10)
# define EVP_PKEY_CTRL_GET_RSA_OAEP_MD (EVP_PKEY_ALG_CTRL + 11)
# define EVP_PKEY_CTRL_GET_RSA_OAEP_LABEL (EVP_PKEY_ALG_CTRL + 12)
# define RSA_PKCS1_PADDING 1
# define RSA_SSLV23_PADDING 2
# define RSA_NO_PADDING 3
# define RSA_PKCS1_OAEP_PADDING 4
# define RSA_X931_PADDING 5
/* EVP_PKEY_ only */
# define RSA_PKCS1_PSS_PADDING 6
# define RSA_PKCS1_PADDING_SIZE 11
# define RSA_set_app_data(s,arg) RSA_set_ex_data(s,0,arg)
# define RSA_get_app_data(s) RSA_get_ex_data(s,0)
RSA *RSA_new(void);
RSA *RSA_new_method(ENGINE *engine);
int RSA_bits(const RSA *rsa);
int RSA_size(const RSA *rsa);
int RSA_security_bits(const RSA *rsa);
int RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d);
int RSA_set0_factors(RSA *r, BIGNUM *p, BIGNUM *q);
int RSA_set0_crt_params(RSA *r,BIGNUM *dmp1, BIGNUM *dmq1, BIGNUM *iqmp);
void RSA_get0_key(const RSA *r,
const BIGNUM **n, const BIGNUM **e, const BIGNUM **d);
void RSA_get0_factors(const RSA *r, const BIGNUM **p, const BIGNUM **q);
void RSA_get0_crt_params(const RSA *r,
const BIGNUM **dmp1, const BIGNUM **dmq1,
const BIGNUM **iqmp);
void RSA_clear_flags(RSA *r, int flags);
int RSA_test_flags(const RSA *r, int flags);
void RSA_set_flags(RSA *r, int flags);
ENGINE *RSA_get0_engine(const RSA *r);
/* Deprecated version */
DEPRECATEDIN_0_9_8(RSA *RSA_generate_key(int bits, unsigned long e, void
(*callback) (int, int, void *),
void *cb_arg))
/* New version */
int RSA_generate_key_ex(RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb);
int RSA_X931_derive_ex(RSA *rsa, BIGNUM *p1, BIGNUM *p2, BIGNUM *q1,
BIGNUM *q2, const BIGNUM *Xp1, const BIGNUM *Xp2,
const BIGNUM *Xp, const BIGNUM *Xq1, const BIGNUM *Xq2,
const BIGNUM *Xq, const BIGNUM *e, BN_GENCB *cb);
int RSA_X931_generate_key_ex(RSA *rsa, int bits, const BIGNUM *e,
BN_GENCB *cb);
int RSA_check_key(const RSA *);
int RSA_check_key_ex(const RSA *, BN_GENCB *cb);
/* next 4 return -1 on error */
int RSA_public_encrypt(int flen, const unsigned char *from,
unsigned char *to, RSA *rsa, int padding);
int RSA_private_encrypt(int flen, const unsigned char *from,
unsigned char *to, RSA *rsa, int padding);
int RSA_public_decrypt(int flen, const unsigned char *from,
unsigned char *to, RSA *rsa, int padding);
int RSA_private_decrypt(int flen, const unsigned char *from,
unsigned char *to, RSA *rsa, int padding);
void RSA_free(RSA *r);
/* "up" the RSA object's reference count */
int RSA_up_ref(RSA *r);
int RSA_flags(const RSA *r);
void RSA_set_default_method(const RSA_METHOD *meth);
const RSA_METHOD *RSA_get_default_method(void);
const RSA_METHOD *RSA_get_method(const RSA *rsa);
int RSA_set_method(RSA *rsa, const RSA_METHOD *meth);
/* these are the actual RSA functions */
const RSA_METHOD *RSA_PKCS1_OpenSSL(void);
const RSA_METHOD *RSA_null_method(void);
DECLARE_ASN1_ENCODE_FUNCTIONS_const(RSA, RSAPublicKey)
DECLARE_ASN1_ENCODE_FUNCTIONS_const(RSA, RSAPrivateKey)
typedef struct rsa_pss_params_st {
X509_ALGOR *hashAlgorithm;
X509_ALGOR *maskGenAlgorithm;
ASN1_INTEGER *saltLength;
ASN1_INTEGER *trailerField;
} RSA_PSS_PARAMS;
DECLARE_ASN1_FUNCTIONS(RSA_PSS_PARAMS)
typedef struct rsa_oaep_params_st {
X509_ALGOR *hashFunc;
X509_ALGOR *maskGenFunc;
X509_ALGOR *pSourceFunc;
} RSA_OAEP_PARAMS;
DECLARE_ASN1_FUNCTIONS(RSA_OAEP_PARAMS)
# ifndef OPENSSL_NO_STDIO
int RSA_print_fp(FILE *fp, const RSA *r, int offset);
# endif
int RSA_print(BIO *bp, const RSA *r, int offset);
/*
* The following 2 functions sign and verify a X509_SIG ASN1 object inside
* PKCS#1 padded RSA encryption
*/
int RSA_sign(int type, const unsigned char *m, unsigned int m_length,
unsigned char *sigret, unsigned int *siglen, RSA *rsa);
int RSA_verify(int type, const unsigned char *m, unsigned int m_length,
const unsigned char *sigbuf, unsigned int siglen, RSA *rsa);
/*
* The following 2 function sign and verify a ASN1_OCTET_STRING object inside
* PKCS#1 padded RSA encryption
*/
int RSA_sign_ASN1_OCTET_STRING(int type,
const unsigned char *m, unsigned int m_length,
unsigned char *sigret, unsigned int *siglen,
RSA *rsa);
int RSA_verify_ASN1_OCTET_STRING(int type, const unsigned char *m,
unsigned int m_length, unsigned char *sigbuf,
unsigned int siglen, RSA *rsa);
int RSA_blinding_on(RSA *rsa, BN_CTX *ctx);
void RSA_blinding_off(RSA *rsa);
BN_BLINDING *RSA_setup_blinding(RSA *rsa, BN_CTX *ctx);
int RSA_padding_add_PKCS1_type_1(unsigned char *to, int tlen,
const unsigned char *f, int fl);
int RSA_padding_check_PKCS1_type_1(unsigned char *to, int tlen,
const unsigned char *f, int fl,
int rsa_len);
int RSA_padding_add_PKCS1_type_2(unsigned char *to, int tlen,
const unsigned char *f, int fl);
int RSA_padding_check_PKCS1_type_2(unsigned char *to, int tlen,
const unsigned char *f, int fl,
int rsa_len);
int PKCS1_MGF1(unsigned char *mask, long len, const unsigned char *seed,
long seedlen, const EVP_MD *dgst);
int RSA_padding_add_PKCS1_OAEP(unsigned char *to, int tlen,
const unsigned char *f, int fl,
const unsigned char *p, int pl);
int RSA_padding_check_PKCS1_OAEP(unsigned char *to, int tlen,
const unsigned char *f, int fl, int rsa_len,
const unsigned char *p, int pl);
int RSA_padding_add_PKCS1_OAEP_mgf1(unsigned char *to, int tlen,
const unsigned char *from, int flen,
const unsigned char *param, int plen,
const EVP_MD *md, const EVP_MD *mgf1md);
int RSA_padding_check_PKCS1_OAEP_mgf1(unsigned char *to, int tlen,
const unsigned char *from, int flen,
int num, const unsigned char *param,
int plen, const EVP_MD *md,
const EVP_MD *mgf1md);
int RSA_padding_add_SSLv23(unsigned char *to, int tlen,
const unsigned char *f, int fl);
int RSA_padding_check_SSLv23(unsigned char *to, int tlen,
const unsigned char *f, int fl, int rsa_len);
int RSA_padding_add_none(unsigned char *to, int tlen, const unsigned char *f,
int fl);
int RSA_padding_check_none(unsigned char *to, int tlen,
const unsigned char *f, int fl, int rsa_len);
int RSA_padding_add_X931(unsigned char *to, int tlen, const unsigned char *f,
int fl);
int RSA_padding_check_X931(unsigned char *to, int tlen,
const unsigned char *f, int fl, int rsa_len);
int RSA_X931_hash_id(int nid);
int RSA_verify_PKCS1_PSS(RSA *rsa, const unsigned char *mHash,
const EVP_MD *Hash, const unsigned char *EM,
int sLen);
int RSA_padding_add_PKCS1_PSS(RSA *rsa, unsigned char *EM,
const unsigned char *mHash, const EVP_MD *Hash,
int sLen);
int RSA_verify_PKCS1_PSS_mgf1(RSA *rsa, const unsigned char *mHash,
const EVP_MD *Hash, const EVP_MD *mgf1Hash,
const unsigned char *EM, int sLen);
int RSA_padding_add_PKCS1_PSS_mgf1(RSA *rsa, unsigned char *EM,
const unsigned char *mHash,
const EVP_MD *Hash, const EVP_MD *mgf1Hash,
int sLen);
#define RSA_get_ex_new_index(l, p, newf, dupf, freef) \
CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_RSA, l, p, newf, dupf, freef)
int RSA_set_ex_data(RSA *r, int idx, void *arg);
void *RSA_get_ex_data(const RSA *r, int idx);
RSA *RSAPublicKey_dup(RSA *rsa);
RSA *RSAPrivateKey_dup(RSA *rsa);
/*
* If this flag is set the RSA method is FIPS compliant and can be used in
* FIPS mode. This is set in the validated module method. If an application
* sets this flag in its own methods it is its responsibility to ensure the
* result is compliant.
*/
# define RSA_FLAG_FIPS_METHOD 0x0400
/*
* If this flag is set the operations normally disabled in FIPS mode are
* permitted it is then the applications responsibility to ensure that the
* usage is compliant.
*/
# define RSA_FLAG_NON_FIPS_ALLOW 0x0400
/*
* Application has decided PRNG is good enough to generate a key: don't
* check.
*/
# define RSA_FLAG_CHECKED 0x0800
RSA_METHOD *RSA_meth_new(const char *name, int flags);
void RSA_meth_free(RSA_METHOD *meth);
RSA_METHOD *RSA_meth_dup(const RSA_METHOD *meth);
const char *RSA_meth_get0_name(const RSA_METHOD *meth);
int RSA_meth_set1_name(RSA_METHOD *meth, const char *name);
int RSA_meth_get_flags(RSA_METHOD *meth);
int RSA_meth_set_flags(RSA_METHOD *meth, int flags);
void *RSA_meth_get0_app_data(const RSA_METHOD *meth);
int RSA_meth_set0_app_data(RSA_METHOD *meth, void *app_data);
int (*RSA_meth_get_pub_enc(const RSA_METHOD *meth))
(int flen, const unsigned char *from,
unsigned char *to, RSA *rsa, int padding);
int RSA_meth_set_pub_enc(RSA_METHOD *rsa,
int (*pub_enc) (int flen, const unsigned char *from,
unsigned char *to, RSA *rsa,
int padding));
int (*RSA_meth_get_pub_dec(const RSA_METHOD *meth))
(int flen, const unsigned char *from,
unsigned char *to, RSA *rsa, int padding);
int RSA_meth_set_pub_dec(RSA_METHOD *rsa,
int (*pub_dec) (int flen, const unsigned char *from,
unsigned char *to, RSA *rsa,
int padding));
int (*RSA_meth_get_priv_enc(const RSA_METHOD *meth))
(int flen, const unsigned char *from,
unsigned char *to, RSA *rsa, int padding);
int RSA_meth_set_priv_enc(RSA_METHOD *rsa,
int (*priv_enc) (int flen, const unsigned char *from,
unsigned char *to, RSA *rsa,
int padding));
int (*RSA_meth_get_priv_dec(const RSA_METHOD *meth))
(int flen, const unsigned char *from,
unsigned char *to, RSA *rsa, int padding);
int RSA_meth_set_priv_dec(RSA_METHOD *rsa,
int (*priv_dec) (int flen, const unsigned char *from,
unsigned char *to, RSA *rsa,
int padding));
int (*RSA_meth_get_mod_exp(const RSA_METHOD *meth))
(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx);
int RSA_meth_set_mod_exp(RSA_METHOD *rsa,
int (*mod_exp) (BIGNUM *r0, const BIGNUM *I, RSA *rsa,
BN_CTX *ctx));
int (*RSA_meth_get_bn_mod_exp(const RSA_METHOD *meth))
(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
int RSA_meth_set_bn_mod_exp(RSA_METHOD *rsa,
int (*bn_mod_exp) (BIGNUM *r,
const BIGNUM *a,
const BIGNUM *p,
const BIGNUM *m,
BN_CTX *ctx,
BN_MONT_CTX *m_ctx));
int (*RSA_meth_get_init(const RSA_METHOD *meth)) (RSA *rsa);
int RSA_meth_set_init(RSA_METHOD *rsa, int (*init) (RSA *rsa));
int (*RSA_meth_get_finish(const RSA_METHOD *meth)) (RSA *rsa);
int RSA_meth_set_finish(RSA_METHOD *rsa, int (*finish) (RSA *rsa));
int (*RSA_meth_get_sign(const RSA_METHOD *meth))
(int type,
const unsigned char *m, unsigned int m_length,
unsigned char *sigret, unsigned int *siglen,
const RSA *rsa);
int RSA_meth_set_sign(RSA_METHOD *rsa,
int (*sign) (int type, const unsigned char *m,
unsigned int m_length,
unsigned char *sigret, unsigned int *siglen,
const RSA *rsa));
int (*RSA_meth_get_verify(const RSA_METHOD *meth))
(int dtype, const unsigned char *m,
unsigned int m_length, const unsigned char *sigbuf,
unsigned int siglen, const RSA *rsa);
int RSA_meth_set_verify(RSA_METHOD *rsa,
int (*verify) (int dtype, const unsigned char *m,
unsigned int m_length,
const unsigned char *sigbuf,
unsigned int siglen, const RSA *rsa));
int (*RSA_meth_get_keygen(const RSA_METHOD *meth))
(RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb);
int RSA_meth_set_keygen(RSA_METHOD *rsa,
int (*keygen) (RSA *rsa, int bits, BIGNUM *e,
BN_GENCB *cb));
/* BEGIN ERROR CODES */
/*
* The following lines are auto generated by the script mkerr.pl. Any changes
* made after this point may be overwritten when the script is next run.
*/
int ERR_load_RSA_strings(void);
/* Error codes for the RSA functions. */
/* Function codes. */
# define RSA_F_CHECK_PADDING_MD 140
# define RSA_F_ENCODE_PKCS1 146
# define RSA_F_INT_RSA_VERIFY 145
# define RSA_F_OLD_RSA_PRIV_DECODE 147
# define RSA_F_PKEY_RSA_CTRL 143
# define RSA_F_PKEY_RSA_CTRL_STR 144
# define RSA_F_PKEY_RSA_SIGN 142
# define RSA_F_PKEY_RSA_VERIFY 149
# define RSA_F_PKEY_RSA_VERIFYRECOVER 141
# define RSA_F_RSA_ALGOR_TO_MD 156
# define RSA_F_RSA_BUILTIN_KEYGEN 129
# define RSA_F_RSA_CHECK_KEY 123
# define RSA_F_RSA_CHECK_KEY_EX 160
# define RSA_F_RSA_CMS_DECRYPT 159
# define RSA_F_RSA_ITEM_VERIFY 148
# define RSA_F_RSA_METH_DUP 161
# define RSA_F_RSA_METH_NEW 162
# define RSA_F_RSA_METH_SET1_NAME 163
# define RSA_F_RSA_MGF1_TO_MD 157
# define RSA_F_RSA_NEW_METHOD 106
# define RSA_F_RSA_NULL 124
# define RSA_F_RSA_NULL_PRIVATE_DECRYPT 132
# define RSA_F_RSA_NULL_PRIVATE_ENCRYPT 133
# define RSA_F_RSA_NULL_PUBLIC_DECRYPT 134
# define RSA_F_RSA_NULL_PUBLIC_ENCRYPT 135
# define RSA_F_RSA_OSSL_PRIVATE_DECRYPT 101
# define RSA_F_RSA_OSSL_PRIVATE_ENCRYPT 102
# define RSA_F_RSA_OSSL_PUBLIC_DECRYPT 103
# define RSA_F_RSA_OSSL_PUBLIC_ENCRYPT 104
# define RSA_F_RSA_PADDING_ADD_NONE 107
# define RSA_F_RSA_PADDING_ADD_PKCS1_OAEP 121
# define RSA_F_RSA_PADDING_ADD_PKCS1_OAEP_MGF1 154
# define RSA_F_RSA_PADDING_ADD_PKCS1_PSS 125
# define RSA_F_RSA_PADDING_ADD_PKCS1_PSS_MGF1 152
# define RSA_F_RSA_PADDING_ADD_PKCS1_TYPE_1 108
# define RSA_F_RSA_PADDING_ADD_PKCS1_TYPE_2 109
# define RSA_F_RSA_PADDING_ADD_SSLV23 110
# define RSA_F_RSA_PADDING_ADD_X931 127
# define RSA_F_RSA_PADDING_CHECK_NONE 111
# define RSA_F_RSA_PADDING_CHECK_PKCS1_OAEP 122
# define RSA_F_RSA_PADDING_CHECK_PKCS1_OAEP_MGF1 153
# define RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_1 112
# define RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_2 113
# define RSA_F_RSA_PADDING_CHECK_SSLV23 114
# define RSA_F_RSA_PADDING_CHECK_X931 128
# define RSA_F_RSA_PRINT 115
# define RSA_F_RSA_PRINT_FP 116
# define RSA_F_RSA_PRIV_ENCODE 138
# define RSA_F_RSA_PSS_TO_CTX 155
# define RSA_F_RSA_PUB_DECODE 139
# define RSA_F_RSA_SETUP_BLINDING 136
# define RSA_F_RSA_SIGN 117
# define RSA_F_RSA_SIGN_ASN1_OCTET_STRING 118
# define RSA_F_RSA_VERIFY 119
# define RSA_F_RSA_VERIFY_ASN1_OCTET_STRING 120
# define RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1 126
/* Reason codes. */
# define RSA_R_ALGORITHM_MISMATCH 100
# define RSA_R_BAD_E_VALUE 101
# define RSA_R_BAD_FIXED_HEADER_DECRYPT 102
# define RSA_R_BAD_PAD_BYTE_COUNT 103
# define RSA_R_BAD_SIGNATURE 104
# define RSA_R_BLOCK_TYPE_IS_NOT_01 106
# define RSA_R_BLOCK_TYPE_IS_NOT_02 107
# define RSA_R_DATA_GREATER_THAN_MOD_LEN 108
# define RSA_R_DATA_TOO_LARGE 109
# define RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE 110
# define RSA_R_DATA_TOO_LARGE_FOR_MODULUS 132
# define RSA_R_DATA_TOO_SMALL 111
# define RSA_R_DATA_TOO_SMALL_FOR_KEY_SIZE 122
# define RSA_R_DIGEST_DOES_NOT_MATCH 158
# define RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY 112
# define RSA_R_DMP1_NOT_CONGRUENT_TO_D 124
# define RSA_R_DMQ1_NOT_CONGRUENT_TO_D 125
# define RSA_R_D_E_NOT_CONGRUENT_TO_1 123
# define RSA_R_FIRST_OCTET_INVALID 133
# define RSA_R_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE 144
# define RSA_R_INVALID_DIGEST 157
# define RSA_R_INVALID_DIGEST_LENGTH 143
# define RSA_R_INVALID_HEADER 137
# define RSA_R_INVALID_LABEL 160
# define RSA_R_INVALID_MESSAGE_LENGTH 131
# define RSA_R_INVALID_MGF1_MD 156
# define RSA_R_INVALID_OAEP_PARAMETERS 161
# define RSA_R_INVALID_PADDING 138
# define RSA_R_INVALID_PADDING_MODE 141
# define RSA_R_INVALID_PSS_PARAMETERS 149
# define RSA_R_INVALID_PSS_SALTLEN 146
# define RSA_R_INVALID_SALT_LENGTH 150
# define RSA_R_INVALID_TRAILER 139
# define RSA_R_INVALID_X931_DIGEST 142
# define RSA_R_IQMP_NOT_INVERSE_OF_Q 126
# define RSA_R_KEY_SIZE_TOO_SMALL 120
# define RSA_R_LAST_OCTET_INVALID 134
# define RSA_R_MODULUS_TOO_LARGE 105
# define RSA_R_NO_PUBLIC_EXPONENT 140
# define RSA_R_NULL_BEFORE_BLOCK_MISSING 113
# define RSA_R_N_DOES_NOT_EQUAL_P_Q 127
# define RSA_R_OAEP_DECODING_ERROR 121
# define RSA_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE 148
# define RSA_R_PADDING_CHECK_FAILED 114
# define RSA_R_PKCS_DECODING_ERROR 159
# define RSA_R_P_NOT_PRIME 128
# define RSA_R_Q_NOT_PRIME 129
# define RSA_R_RSA_OPERATIONS_NOT_SUPPORTED 130
# define RSA_R_SLEN_CHECK_FAILED 136
# define RSA_R_SLEN_RECOVERY_FAILED 135
# define RSA_R_SSLV3_ROLLBACK_ATTACK 115
# define RSA_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD 116
# define RSA_R_UNKNOWN_ALGORITHM_TYPE 117
# define RSA_R_UNKNOWN_DIGEST 166
# define RSA_R_UNKNOWN_MASK_DIGEST 151
# define RSA_R_UNKNOWN_PADDING_TYPE 118
# define RSA_R_UNSUPPORTED_ENCRYPTION_TYPE 162
# define RSA_R_UNSUPPORTED_LABEL_SOURCE 163
# define RSA_R_UNSUPPORTED_MASK_ALGORITHM 153
# define RSA_R_UNSUPPORTED_MASK_PARAMETER 154
# define RSA_R_UNSUPPORTED_SIGNATURE_TYPE 155
# define RSA_R_VALUE_MISSING 147
# define RSA_R_WRONG_SIGNATURE_LENGTH 119
# ifdef __cplusplus
}
# endif
# endif
#endif
| {
"pile_set_name": "Github"
} |
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
/**
* Unit tests for the Annotations Search.
*/
import {TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {FormsModule} from '@angular/forms';
import {CommonModule} from '@angular/common';
import {MatInputModule} from '@angular/material/input';
import {Action, Store} from '@ngrx/store';
import {provideMockStore, MockStore} from '@ngrx/store/testing';
import {State} from '../../../../../../app_state';
import * as npmiActions from '../../../../actions';
import {appStateFromNpmiState, createNpmiState} from '../../../../testing';
import {AnnotationsSearchContainer} from './annotations_search_container';
import {AnnotationsSearchComponent} from './annotations_search_component';
/** @typehack */ import * as _typeHackStore from '@ngrx/store';
import {getAnnotationsRegex} from '../../../../store';
describe('Npmi Annotations Search Container', () => {
let store: MockStore<State>;
let dispatchedActions: Action[];
const css = {
ERROR_ICON: By.css('.error-icon'),
INPUT: By.css('input'),
};
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [AnnotationsSearchComponent, AnnotationsSearchContainer],
imports: [CommonModule, FormsModule, MatInputModule],
providers: [
provideMockStore({
initialState: appStateFromNpmiState(createNpmiState()),
}),
],
}).compileComponents();
store = TestBed.inject<Store<State>>(Store) as MockStore<State>;
dispatchedActions = [];
spyOn(store, 'dispatch').and.callFake((action: Action) => {
dispatchedActions.push(action);
});
});
it('renders npmi annotations search component', () => {
const fixture = TestBed.createComponent(AnnotationsSearchContainer);
fixture.detectChanges();
const filterDiv = fixture.debugElement.query(css.INPUT);
expect(filterDiv).toBeTruthy();
expect(fixture.debugElement.query(css.ERROR_ICON)).toBeNull();
});
describe('input interaction', () => {
it('dispatches changeAnnotationsRegex when typing on input', () => {
const fixture = TestBed.createComponent(AnnotationsSearchContainer);
fixture.detectChanges();
const input = fixture.debugElement.query(css.INPUT);
input.nativeElement.focus();
fixture.detectChanges();
input.nativeElement.value = 'a';
input.nativeElement.dispatchEvent(new InputEvent('input', {data: 'a'}));
fixture.detectChanges();
expect(dispatchedActions).toEqual([
npmiActions.npmiAnnotationsRegexChanged({regex: 'a'}),
]);
});
});
it('shows error icon for an invalid regex', () => {
store.overrideSelector(getAnnotationsRegex, '*');
const fixture = TestBed.createComponent(AnnotationsSearchContainer);
fixture.detectChanges();
expect(fixture.debugElement.query(css.ERROR_ICON)).not.toBeNull();
});
});
| {
"pile_set_name": "Github"
} |
Distance from 0 to 0: 0
Distance from 0 to 1: 8
Distance from 0 to 2: 9
Distance from 0 to 3: 5
Distance from 0 to 4: 7
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.