text
stringlengths
2
1.04M
meta
dict
package http type Link struct { Rel string Link string } type ResponseEntity struct { Entity interface{} Links []Link } func MakeHateos(entity interface{}, links []Link) *ResponseEntity { return &ResponseEntity{ Entity: entity, Links: links, } }
{ "content_hash": "9a28037eb02985991ff7dd25046e0ddb", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 67, "avg_line_length": 13.631578947368421, "alnum_prop": 0.7181467181467182, "repo_name": "kevinbayes/clairs-server", "id": "4e7ce500fc7d06247ddd463cc4755ce782e82d53", "size": "847", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clairs/http/hateoas.go", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "6961" }, { "name": "Go", "bytes": "87684" }, { "name": "HTML", "bytes": "8990" }, { "name": "JavaScript", "bytes": "1996" }, { "name": "Makefile", "bytes": "579" }, { "name": "TypeScript", "bytes": "53299" } ], "symlink_target": "" }
//===--- ParseType.cpp - Swift Language Parser for Types ------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Type Parsing and AST Building // //===----------------------------------------------------------------------===// #include "swift/Parse/Parser.h" #include "swift/AST/ASTWalker.h" #include "swift/AST/Attr.h" #include "swift/AST/TypeRepr.h" #include "swift/Parse/Lexer.h" #include "swift/Parse/CodeCompletionCallbacks.h" #include "swift/Parse/SyntaxParsingContext.h" #include "swift/Parse/ParsedSyntaxBuilders.h" #include "swift/Parse/ParsedSyntaxRecorder.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/SaveAndRestore.h" using namespace swift; using namespace swift::syntax; TypeRepr *Parser::applyAttributeToType(TypeRepr *ty, const TypeAttributes &attrs, ParamDecl::Specifier specifier, SourceLoc specifierLoc) { // Apply those attributes that do apply. if (!attrs.empty()) { ty = new (Context) AttributedTypeRepr(attrs, ty); } // Apply 'inout' or '__shared' or '__owned' if (specifierLoc.isValid()) { switch (specifier) { case ParamDecl::Specifier::Owned: ty = new (Context) OwnedTypeRepr(ty, specifierLoc); break; case ParamDecl::Specifier::InOut: ty = new (Context) InOutTypeRepr(ty, specifierLoc); break; case ParamDecl::Specifier::Shared: ty = new (Context) SharedTypeRepr(ty, specifierLoc); break; case ParamDecl::Specifier::Default: break; } } return ty; } LayoutConstraint Parser::parseLayoutConstraint(Identifier LayoutConstraintID) { LayoutConstraint layoutConstraint = getLayoutConstraint(LayoutConstraintID, Context); assert(layoutConstraint->isKnownLayout() && "Expected layout constraint definition"); if (!layoutConstraint->isTrivial()) return layoutConstraint; SourceLoc LParenLoc; if (!consumeIf(tok::l_paren, LParenLoc)) { // It is a trivial without any size constraints. return LayoutConstraint::getLayoutConstraint(LayoutConstraintKind::Trivial, Context); } int size = 0; int alignment = 0; auto ParseTrivialLayoutConstraintBody = [&] () -> bool { // Parse the size and alignment. if (Tok.is(tok::integer_literal)) { if (Tok.getText().getAsInteger(10, size)) { diagnose(Tok.getLoc(), diag::layout_size_should_be_positive); return true; } consumeToken(); if (consumeIf(tok::comma)) { // parse alignment. if (Tok.is(tok::integer_literal)) { if (Tok.getText().getAsInteger(10, alignment)) { diagnose(Tok.getLoc(), diag::layout_alignment_should_be_positive); return true; } consumeToken(); } else { diagnose(Tok.getLoc(), diag::layout_alignment_should_be_positive); return true; } } } else { diagnose(Tok.getLoc(), diag::layout_size_should_be_positive); return true; } return false; }; if (ParseTrivialLayoutConstraintBody()) { // There was an error during parsing. skipUntil(tok::r_paren); consumeIf(tok::r_paren); return LayoutConstraint::getUnknownLayout(); } if (!consumeIf(tok::r_paren)) { // Expected a closing r_paren. diagnose(Tok.getLoc(), diag::expected_rparen_layout_constraint); consumeToken(); return LayoutConstraint::getUnknownLayout(); } if (size < 0) { diagnose(Tok.getLoc(), diag::layout_size_should_be_positive); return LayoutConstraint::getUnknownLayout(); } if (alignment < 0) { diagnose(Tok.getLoc(), diag::layout_alignment_should_be_positive); return LayoutConstraint::getUnknownLayout(); } // Otherwise it is a trivial layout constraint with // provided size and alignment. return LayoutConstraint::getLayoutConstraint(layoutConstraint->getKind(), size, alignment, Context); } /// parseTypeSimple /// type-simple: /// type-identifier /// type-tuple /// type-composition-deprecated /// 'Any' /// type-simple '.Type' /// type-simple '.Protocol' /// type-simple '?' /// type-simple '!' /// type-collection /// type-array ParserResult<TypeRepr> Parser::parseTypeSimple(Diag<> MessageID, bool HandleCodeCompletion) { ParserResult<TypeRepr> ty; if (Tok.is(tok::kw_inout) || (Tok.is(tok::identifier) && (Tok.getRawText().equals("__shared") || Tok.getRawText().equals("__owned")))) { // Type specifier should already be parsed before here. This only happens // for construct like 'P1 & inout P2'. diagnose(Tok.getLoc(), diag::attr_only_on_parameters, Tok.getRawText()); consumeToken(); } switch (Tok.getKind()) { case tok::kw_Self: case tok::kw_Any: case tok::identifier: { ty = parseTypeIdentifier(); break; } case tok::l_paren: ty = parseTypeTupleBody(); break; case tok::code_complete: if (!HandleCodeCompletion) break; if (CodeCompletion) CodeCompletion->completeTypeSimpleBeginning(); return makeParserCodeCompletionResult<TypeRepr>( new (Context) ErrorTypeRepr(consumeToken(tok::code_complete))); case tok::l_square: { auto Result = parseTypeCollection(); if (Result.hasSyntax()) SyntaxContext->addSyntax(Result.getSyntax()); ty = Result.getASTResult(); break; } case tok::kw_protocol: if (startsWithLess(peekToken())) { ty = parseOldStyleProtocolComposition(); break; } LLVM_FALLTHROUGH; default: { auto diag = diagnose(Tok, MessageID); // If the next token is closing or separating, the type was likely forgotten if (Tok.isAny(tok::r_paren, tok::r_brace, tok::r_square, tok::arrow, tok::equal, tok::comma, tok::semi)) diag.fixItInsert(getEndOfPreviousLoc(), " <#type#>"); } if (Tok.isKeyword() && !Tok.isAtStartOfLine()) { ty = makeParserErrorResult(new (Context) ErrorTypeRepr(Tok.getLoc())); consumeToken(); return ty; } checkForInputIncomplete(); return nullptr; } auto makeMetatypeTypeSyntax = [&]() { if (!SyntaxContext->isEnabled()) return; ParsedMetatypeTypeSyntaxBuilder Builder(*SyntaxContext); auto TypeOrProtocol = SyntaxContext->popToken(); auto Period = SyntaxContext->popToken(); auto BaseType(std::move(*SyntaxContext->popIf<ParsedTypeSyntax>())); Builder .useTypeOrProtocol(std::move(TypeOrProtocol)) .usePeriod(std::move(Period)) .useBaseType(std::move(BaseType)); SyntaxContext->addSyntax(Builder.build()); }; // '.Type', '.Protocol', '?', '!', and '[]' still leave us with type-simple. while (ty.isNonNull()) { if ((Tok.is(tok::period) || Tok.is(tok::period_prefix))) { if (peekToken().isContextualKeyword("Type")) { consumeToken(); SourceLoc metatypeLoc = consumeToken(tok::identifier); ty = makeParserResult(ty, new (Context) MetatypeTypeRepr(ty.get(), metatypeLoc)); makeMetatypeTypeSyntax(); continue; } if (peekToken().isContextualKeyword("Protocol")) { consumeToken(); SourceLoc protocolLoc = consumeToken(tok::identifier); ty = makeParserResult(ty, new (Context) ProtocolTypeRepr(ty.get(), protocolLoc)); makeMetatypeTypeSyntax(); continue; } } if (!Tok.isAtStartOfLine()) { if (isOptionalToken(Tok)) { auto Result = parseTypeOptional(ty.get()); if (Result.hasSyntax()) SyntaxContext->addSyntax(Result.getSyntax()); ty = Result.getASTResult(); continue; } if (isImplicitlyUnwrappedOptionalToken(Tok)) { auto Result = parseTypeImplicitlyUnwrappedOptional(ty.get()); if (Result.hasSyntax()) SyntaxContext->addSyntax(Result.getSyntax()); ty = Result.getASTResult(); continue; } // Parse legacy array types for migration. if (Tok.is(tok::l_square)) { ty = parseTypeArray(ty.get()); continue; } } break; } return ty; } ParserResult<TypeRepr> Parser::parseType() { return parseType(diag::expected_type); } ParserResult<TypeRepr> Parser::parseSILBoxType(GenericParamList *generics, const TypeAttributes &attrs, Optional<Scope> &GenericsScope) { auto LBraceLoc = consumeToken(tok::l_brace); SmallVector<SILBoxTypeRepr::Field, 4> Fields; if (!Tok.is(tok::r_brace)) { for (;;) { bool Mutable; if (Tok.is(tok::kw_var)) { Mutable = true; } else if (Tok.is(tok::kw_let)) { Mutable = false; } else { diagnose(Tok, diag::sil_box_expected_var_or_let); return makeParserError(); } SourceLoc VarOrLetLoc = consumeToken(); auto fieldTy = parseType(); if (!fieldTy.getPtrOrNull()) return makeParserError(); Fields.push_back({VarOrLetLoc, Mutable, fieldTy.get()}); if (consumeIf(tok::comma)) continue; break; } } if (!Tok.is(tok::r_brace)) { diagnose(Tok, diag::sil_box_expected_r_brace); return makeParserError(); } auto RBraceLoc = consumeToken(tok::r_brace); // The generic arguments are taken from the enclosing scope. Pop the // box layout's scope now. GenericsScope.reset(); SourceLoc LAngleLoc, RAngleLoc; SmallVector<TypeRepr*, 4> Args; if (startsWithLess(Tok)) { LAngleLoc = consumeStartingLess(); for (;;) { auto argTy = parseType(); if (!argTy.getPtrOrNull()) return makeParserError(); Args.push_back(argTy.get()); if (consumeIf(tok::comma)) continue; break; } if (!startsWithGreater(Tok)) { diagnose(Tok, diag::sil_box_expected_r_angle); return makeParserError(); } RAngleLoc = consumeStartingGreater(); } auto repr = SILBoxTypeRepr::create(Context, generics, LBraceLoc, Fields, RBraceLoc, LAngleLoc, Args, RAngleLoc); return makeParserResult(applyAttributeToType(repr, attrs, ParamDecl::Specifier::Owned, SourceLoc())); } /// parseType /// type: /// attribute-list type-composition /// attribute-list type-function /// /// type-function: /// type-composition 'async'? 'throws'? '->' type /// ParserResult<TypeRepr> Parser::parseType(Diag<> MessageID, bool HandleCodeCompletion, bool IsSILFuncDecl) { // Start a context for creating type syntax. SyntaxParsingContext TypeParsingContext(SyntaxContext, SyntaxContextKind::Type); // Parse attributes. ParamDecl::Specifier specifier; SourceLoc specifierLoc; TypeAttributes attrs; parseTypeAttributeList(specifier, specifierLoc, attrs); Optional<Scope> GenericsScope; Optional<Scope> patternGenericsScope; // Parse generic parameters in SIL mode. GenericParamList *generics = nullptr; SourceLoc substitutedLoc; GenericParamList *patternGenerics = nullptr; if (isInSILMode()) { // If this is part of a sil function decl, generic parameters are visible in // the function body; otherwise, they are visible when parsing the type. if (!IsSILFuncDecl) GenericsScope.emplace(this, ScopeKind::Generics); generics = maybeParseGenericParams().getPtrOrNull(); if (Tok.is(tok::at_sign) && peekToken().getText() == "substituted") { consumeToken(tok::at_sign); substitutedLoc = consumeToken(tok::identifier); patternGenericsScope.emplace(this, ScopeKind::Generics); patternGenerics = maybeParseGenericParams().getPtrOrNull(); if (!patternGenerics) { diagnose(Tok.getLoc(), diag::sil_function_subst_expected_generics); patternGenericsScope.reset(); } } } // In SIL mode, parse box types { ... }. if (isInSILMode() && Tok.is(tok::l_brace)) { if (patternGenerics) { diagnose(Tok.getLoc(), diag::sil_function_subst_expected_function); patternGenericsScope.reset(); } return parseSILBoxType(generics, attrs, GenericsScope); } ParserResult<TypeRepr> ty = parseTypeSimpleOrComposition(MessageID, HandleCodeCompletion); if (ty.isNull()) return ty; auto tyR = ty.get(); auto status = ParserStatus(ty); // Parse an async specifier. SourceLoc asyncLoc; if (Context.LangOpts.EnableExperimentalConcurrency && Tok.isContextualKeyword("async")) { asyncLoc = consumeToken(); } // Parse a throws specifier. // Don't consume 'throws', if the next token is not '->' or 'async', so we // can emit a more useful diagnostic when parsing a function decl. SourceLoc throwsLoc; if (Tok.isAny(tok::kw_throws, tok::kw_rethrows, tok::kw_throw, tok::kw_try) && (peekToken().is(tok::arrow) || (Context.LangOpts.EnableExperimentalConcurrency && peekToken().isContextualKeyword("async")))) { if (Tok.isAny(tok::kw_rethrows, tok::kw_throw, tok::kw_try)) { // 'rethrows' is only allowed on function declarations for now. // 'throw' or 'try' are probably typos for 'throws'. Diag<> DiagID = Tok.is(tok::kw_rethrows) ? diag::rethrowing_function_type : diag::throw_in_function_type; diagnose(Tok.getLoc(), DiagID) .fixItReplace(Tok.getLoc(), "throws"); } throwsLoc = consumeToken(); // 'async' must preceed 'throws'; accept this but complain. if (Context.LangOpts.EnableExperimentalConcurrency && Tok.isContextualKeyword("async")) { asyncLoc = consumeToken(); diagnose(asyncLoc, diag::async_after_throws, false) .fixItRemove(asyncLoc) .fixItInsert(throwsLoc, "async "); } } if (Tok.is(tok::arrow)) { // Handle type-function if we have an arrow. SourceLoc arrowLoc = consumeToken(); // Handle async/throws in the wrong place. parseAsyncThrows(arrowLoc, asyncLoc, throwsLoc, /*rethrows=*/nullptr); ParserResult<TypeRepr> SecondHalf = parseType(diag::expected_type_function_result); if (SecondHalf.isNull()) { status.setIsParseError(); return status; } status |= SecondHalf; if (SyntaxContext->isEnabled()) { ParsedFunctionTypeSyntaxBuilder Builder(*SyntaxContext); Builder.useReturnType(std::move(*SyntaxContext->popIf<ParsedTypeSyntax>())); Builder.useArrow(SyntaxContext->popToken()); if (asyncLoc.isValid()) Builder.useAsyncKeyword(SyntaxContext->popToken()); if (throwsLoc.isValid()) Builder.useThrowsOrRethrowsKeyword(SyntaxContext->popToken()); auto InputNode(std::move(*SyntaxContext->popIf<ParsedTypeSyntax>())); if (auto TupleTypeNode = InputNode.getAs<ParsedTupleTypeSyntax>()) { // Decompose TupleTypeSyntax and repack into FunctionType. auto LeftParen = TupleTypeNode->getDeferredLeftParen(); auto Arguments = TupleTypeNode->getDeferredElements(); auto RightParen = TupleTypeNode->getDeferredRightParen(); Builder .useLeftParen(std::move(LeftParen)) .useArguments(std::move(Arguments)) .useRightParen(std::move(RightParen)); } else { Builder.addArgumentsMember(ParsedSyntaxRecorder::makeTupleTypeElement( std::move(InputNode), /*TrailingComma=*/None, *SyntaxContext)); } SyntaxContext->addSyntax(Builder.build()); } TupleTypeRepr *argsTyR = nullptr; if (auto *TTArgs = dyn_cast<TupleTypeRepr>(tyR)) { argsTyR = TTArgs; } else { bool isVoid = false; if (const auto Void = dyn_cast<SimpleIdentTypeRepr>(tyR)) { if (Void->getNameRef().isSimpleName(Context.Id_Void)) { isVoid = true; } } if (isVoid) { diagnose(tyR->getStartLoc(), diag::function_type_no_parens) .fixItReplace(tyR->getStartLoc(), "()"); argsTyR = TupleTypeRepr::createEmpty(Context, tyR->getSourceRange()); } else { diagnose(tyR->getStartLoc(), diag::function_type_no_parens) .highlight(tyR->getSourceRange()) .fixItInsert(tyR->getStartLoc(), "(") .fixItInsertAfter(tyR->getEndLoc(), ")"); argsTyR = TupleTypeRepr::create(Context, {tyR}, tyR->getSourceRange()); } } // Parse substitutions for substituted SIL types. MutableArrayRef<TypeRepr *> invocationSubsTypes; MutableArrayRef<TypeRepr *> patternSubsTypes; if (isInSILMode()) { auto parseSubstitutions = [&](MutableArrayRef<TypeRepr*> &subs) -> Optional<bool> { if (!consumeIf(tok::kw_for)) return None; if (!startsWithLess(Tok)) { diagnose(Tok, diag::sil_function_subst_expected_l_angle); return false; } consumeStartingLess(); SmallVector<TypeRepr*, 4> SubsTypesVec; for (;;) { auto argTy = parseType(); if (!argTy.getPtrOrNull()) return false; SubsTypesVec.push_back(argTy.get()); if (consumeIf(tok::comma)) continue; break; } if (!startsWithGreater(Tok)) { diagnose(Tok, diag::sil_function_subst_expected_r_angle); return false; } consumeStartingGreater(); subs = Context.AllocateCopy(SubsTypesVec); return true; }; // Parse pattern substitutions. These must exist if we had pattern // generics above. if (patternGenerics) { // These substitutions are outside of the scope of the // pattern generics. patternGenericsScope.reset(); auto result = parseSubstitutions(patternSubsTypes); if (!result || patternSubsTypes.empty()) { diagnose(Tok, diag::sil_function_subst_expected_subs); patternGenerics = nullptr; } else if (!*result) { return makeParserError(); } } if (generics) { // These substitutions are outside of the scope of the // invocation generics. GenericsScope.reset(); if (auto result = parseSubstitutions(invocationSubsTypes)) if (!*result) return makeParserError(); } if (Tok.is(tok::kw_for)) { diagnose(Tok, diag::sil_function_subs_without_generics); return makeParserError(); } } tyR = new (Context) FunctionTypeRepr(generics, argsTyR, asyncLoc, throwsLoc, arrowLoc, SecondHalf.get(), patternGenerics, patternSubsTypes, invocationSubsTypes); } else if (auto firstGenerics = generics ? generics : patternGenerics) { // Only function types may be generic. auto brackets = firstGenerics->getSourceRange(); diagnose(brackets.Start, diag::generic_non_function); GenericsScope.reset(); patternGenericsScope.reset(); // Forget any generic parameters we saw in the type. class EraseTypeParamWalker : public ASTWalker { public: bool walkToTypeReprPre(TypeRepr *T) override { if (auto ident = dyn_cast<ComponentIdentTypeRepr>(T)) { if (auto decl = ident->getBoundDecl()) { if (auto genericParam = dyn_cast<GenericTypeParamDecl>(decl)) ident->overwriteNameRef(genericParam->createNameRef()); } } return true; } } walker; if (tyR) tyR->walk(walker); } if (specifierLoc.isValid() || !attrs.empty()) SyntaxContext->setCreateSyntax(SyntaxKind::AttributedType); return makeParserResult(status, applyAttributeToType(tyR, attrs, specifier, specifierLoc)); } ParserResult<TypeRepr> Parser::parseDeclResultType(Diag<> MessageID) { if (Tok.is(tok::code_complete)) { if (CodeCompletion) CodeCompletion->completeTypeDeclResultBeginning(); consumeToken(tok::code_complete); return makeParserCodeCompletionStatus(); } auto result = parseType(MessageID); if (!result.isParseError() && Tok.is(tok::r_square)) { auto diag = diagnose(Tok, diag::extra_rbracket); diag.fixItInsert(result.get()->getStartLoc(), getTokenText(tok::l_square)); consumeToken(); return makeParserErrorResult(new (Context) ErrorTypeRepr(getTypeErrorLoc())); } else if (!result.isParseError() && Tok.is(tok::colon)) { auto colonTok = consumeToken(); auto secondType = parseType(diag::expected_dictionary_value_type); auto diag = diagnose(colonTok, diag::extra_colon); diag.fixItInsert(result.get()->getStartLoc(), getTokenText(tok::l_square)); if (!secondType.isParseError()) { if (Tok.is(tok::r_square)) { consumeToken(); } else { diag.fixItInsertAfter(secondType.get()->getEndLoc(), getTokenText(tok::r_square)); } } return makeParserErrorResult(new (Context) ErrorTypeRepr(getTypeErrorLoc())); } return result; } SourceLoc Parser::getTypeErrorLoc() const { // Use the same location as a missing close brace, etc. return getErrorOrMissingLoc(); } ParserStatus Parser::parseGenericArguments(SmallVectorImpl<TypeRepr *> &Args, SourceLoc &LAngleLoc, SourceLoc &RAngleLoc) { SyntaxParsingContext GenericArgumentsContext( SyntaxContext, SyntaxKind::GenericArgumentClause); // Parse the opening '<'. assert(startsWithLess(Tok) && "Generic parameter list must start with '<'"); LAngleLoc = consumeStartingLess(); { SyntaxParsingContext ListContext(SyntaxContext, SyntaxKind::GenericArgumentList); while (true) { SyntaxParsingContext ElementContext(SyntaxContext, SyntaxKind::GenericArgument); ParserResult<TypeRepr> Ty = parseType(diag::expected_type); if (Ty.isNull() || Ty.hasCodeCompletion()) { // Skip until we hit the '>'. RAngleLoc = skipUntilGreaterInTypeList(); return ParserStatus(Ty); } Args.push_back(Ty.get()); // Parse the comma, if the list continues. if (!consumeIf(tok::comma)) break; } } if (!startsWithGreater(Tok)) { checkForInputIncomplete(); diagnose(Tok, diag::expected_rangle_generic_arg_list); diagnose(LAngleLoc, diag::opening_angle); // Skip until we hit the '>'. RAngleLoc = skipUntilGreaterInTypeList(); return makeParserError(); } else { RAngleLoc = consumeStartingGreater(); } return makeParserSuccess(); } /// parseTypeIdentifier /// /// type-identifier: /// identifier generic-args? ('.' identifier generic-args?)* /// ParserResult<TypeRepr> Parser::parseTypeIdentifier(bool isParsingQualifiedDeclBaseType) { // If parsing a qualified declaration name, return error if base type cannot // be parsed. if (isParsingQualifiedDeclBaseType && !canParseBaseTypeForQualifiedDeclName()) return makeParserError(); if (Tok.isNot(tok::identifier) && Tok.isNot(tok::kw_Self)) { // is this the 'Any' type if (Tok.is(tok::kw_Any)) { return parseAnyType(); } else if (Tok.is(tok::code_complete)) { if (CodeCompletion) CodeCompletion->completeTypeSimpleBeginning(); // Eat the code completion token because we handled it. consumeToken(tok::code_complete); return makeParserCodeCompletionResult<IdentTypeRepr>(); } diagnose(Tok, diag::expected_identifier_for_type); // If there is a keyword at the start of a new line, we won't want to // skip it as a recovery but rather keep it. if (Tok.isKeyword() && !Tok.isAtStartOfLine()) consumeToken(); return nullptr; } SyntaxParsingContext IdentTypeCtxt(SyntaxContext, SyntaxContextKind::Type); ParserStatus Status; SmallVector<ComponentIdentTypeRepr *, 4> ComponentsR; SourceLoc EndLoc; while (true) { DeclNameLoc Loc; DeclNameRef Name = parseDeclNameRef(Loc, diag::expected_identifier_in_dotted_type, {}); if (!Name) Status.setIsParseError(); if (Loc.isValid()) { SourceLoc LAngle, RAngle; SmallVector<TypeRepr*, 8> GenericArgs; if (startsWithLess(Tok)) { auto genericArgsStatus = parseGenericArguments(GenericArgs, LAngle, RAngle); if (genericArgsStatus.isError()) return genericArgsStatus; } EndLoc = Loc.getEndLoc(); ComponentIdentTypeRepr *CompT; if (!GenericArgs.empty()) CompT = GenericIdentTypeRepr::create(Context, Loc, Name, GenericArgs, SourceRange(LAngle, RAngle)); else CompT = new (Context) SimpleIdentTypeRepr(Loc, Name); ComponentsR.push_back(CompT); } SyntaxContext->createNodeInPlace(ComponentsR.size() == 1 ? SyntaxKind::SimpleTypeIdentifier : SyntaxKind::MemberTypeIdentifier); // Treat 'Foo.<anything>' as an attempt to write a dotted type // unless <anything> is 'Type'. if ((Tok.is(tok::period) || Tok.is(tok::period_prefix))) { if (peekToken().is(tok::code_complete)) { Status.setHasCodeCompletion(); break; } if (!peekToken().isContextualKeyword("Type") && !peekToken().isContextualKeyword("Protocol")) { // If parsing a qualified declaration name, break before parsing the // period before the final declaration name component. if (isParsingQualifiedDeclBaseType) { // If qualified name base type cannot be parsed from the current // point (i.e. the next type identifier is not followed by a '.'), // then the next identifier is the final declaration name component. BacktrackingScope backtrack(*this); consumeStartingCharacterOfCurrentToken(tok::period); if (!canParseBaseTypeForQualifiedDeclName()) break; } // Consume the period. consumeToken(); continue; } } else if (Tok.is(tok::code_complete)) { if (!Tok.isAtStartOfLine()) Status.setHasCodeCompletion(); break; } break; } IdentTypeRepr *ITR = nullptr; if (!ComponentsR.empty()) { // Lookup element #0 through our current scope chains in case it is some // thing local (this returns null if nothing is found). if (auto Entry = lookupInScope(ComponentsR[0]->getNameRef())) if (auto *TD = dyn_cast<TypeDecl>(Entry)) ComponentsR[0]->setValue(TD, nullptr); ITR = IdentTypeRepr::create(Context, ComponentsR); } if (Status.hasCodeCompletion()) { if (Tok.isNot(tok::code_complete)) { // We have a dot. consumeToken(); if (CodeCompletion) CodeCompletion->completeTypeIdentifierWithDot(ITR); } else { if (CodeCompletion) CodeCompletion->completeTypeIdentifierWithoutDot(ITR); } // Eat the code completion token because we handled it. consumeToken(tok::code_complete); } return makeParserResult(Status, ITR); } /// parseTypeSimpleOrComposition /// /// type-composition: /// 'some'? type-simple /// type-composition '&' type-simple ParserResult<TypeRepr> Parser::parseTypeSimpleOrComposition(Diag<> MessageID, bool HandleCodeCompletion) { SyntaxParsingContext SomeTypeContext(SyntaxContext, SyntaxKind::SomeType); // Check for the opaque modifier. // This is only semantically allowed in certain contexts, but we parse it // generally for diagnostics and recovery. SourceLoc opaqueLoc; if (Tok.is(tok::identifier) && Tok.getRawText() == "some") { // Treat some as a keyword. TokReceiver->registerTokenKindChange(Tok.getLoc(), tok::contextual_keyword); opaqueLoc = consumeToken(); } else { // This isn't a some type. SomeTypeContext.setTransparent(); } auto applyOpaque = [&](TypeRepr *type) -> TypeRepr* { if (opaqueLoc.isValid()) { type = new (Context) OpaqueReturnTypeRepr(opaqueLoc, type); } return type; }; SyntaxParsingContext CompositionContext(SyntaxContext, SyntaxContextKind::Type); // Parse the first type ParserResult<TypeRepr> FirstType = parseTypeSimple(MessageID, HandleCodeCompletion); if (FirstType.isNull()) return FirstType; if (!Tok.isContextualPunctuator("&")) { return makeParserResult(ParserStatus(FirstType), applyOpaque(FirstType.get())); } SmallVector<TypeRepr *, 4> Types; ParserStatus Status(FirstType); SourceLoc FirstTypeLoc = FirstType.get()->getStartLoc(); SourceLoc FirstAmpersandLoc = Tok.getLoc(); auto addType = [&](TypeRepr *T) { if (!T) return; if (auto Comp = dyn_cast<CompositionTypeRepr>(T)) { // Accept protocol<P1, P2> & P3; explode it. auto TyRs = Comp->getTypes(); if (!TyRs.empty()) // If empty, is 'Any'; ignore. Types.append(TyRs.begin(), TyRs.end()); return; } Types.push_back(T); }; addType(FirstType.get()); SyntaxContext->setCreateSyntax(SyntaxKind::CompositionType); assert(Tok.isContextualPunctuator("&")); do { if (SyntaxContext->isEnabled()) { auto Type = SyntaxContext->popIf<ParsedTypeSyntax>(); consumeToken(); // consume '&' if (Type) { ParsedCompositionTypeElementSyntaxBuilder Builder(*SyntaxContext); auto Ampersand = SyntaxContext->popToken(); Builder .useAmpersand(std::move(Ampersand)) .useType(std::move(*Type)); SyntaxContext->addSyntax(Builder.build()); } } else { consumeToken(); // consume '&' } // Diagnose invalid `some` after an ampersand. if (Tok.is(tok::identifier) && Tok.getRawText() == "some") { auto badLoc = consumeToken(); diagnose(badLoc, diag::opaque_mid_composition) .fixItRemove(badLoc) .fixItInsert(FirstTypeLoc, "some "); if (opaqueLoc.isInvalid()) opaqueLoc = badLoc; } // Parse next type. ParserResult<TypeRepr> ty = parseTypeSimple(diag::expected_identifier_for_type, HandleCodeCompletion); if (ty.hasCodeCompletion()) return makeParserCodeCompletionResult<TypeRepr>(); Status |= ty; addType(ty.getPtrOrNull()); } while (Tok.isContextualPunctuator("&")); if (SyntaxContext->isEnabled()) { if (auto synType = SyntaxContext->popIf<ParsedTypeSyntax>()) { auto LastNode = ParsedSyntaxRecorder::makeCompositionTypeElement( std::move(*synType), None, *SyntaxContext); SyntaxContext->addSyntax(std::move(LastNode)); } } SyntaxContext->collectNodesInPlace(SyntaxKind::CompositionTypeElementList); return makeParserResult(Status, applyOpaque(CompositionTypeRepr::create( Context, Types, FirstTypeLoc, {FirstAmpersandLoc, PreviousLoc}))); } ParserResult<TypeRepr> Parser::parseAnyType() { SyntaxParsingContext IdentTypeCtxt(SyntaxContext, SyntaxKind::SimpleTypeIdentifier); auto Loc = consumeToken(tok::kw_Any); auto TyR = CompositionTypeRepr::createEmptyComposition(Context, Loc); return makeParserResult(TyR); } /// parseOldStyleProtocolComposition /// type-composition-deprecated: /// 'protocol' '<' '>' /// 'protocol' '<' type-composition-list-deprecated '>' /// /// type-composition-list-deprecated: /// type-identifier /// type-composition-list-deprecated ',' type-identifier ParserResult<TypeRepr> Parser::parseOldStyleProtocolComposition() { assert(Tok.is(tok::kw_protocol) && startsWithLess(peekToken())); // Start a context for creating type syntax. SyntaxParsingContext TypeParsingContext(SyntaxContext, SyntaxContextKind::Type); SourceLoc ProtocolLoc = consumeToken(); SourceLoc LAngleLoc = consumeStartingLess(); // Parse the type-composition-list. ParserStatus Status; SmallVector<TypeRepr *, 4> Protocols; bool IsEmpty = startsWithGreater(Tok); if (!IsEmpty) { do { // Parse the type-identifier. ParserResult<TypeRepr> Protocol = parseTypeIdentifier(); Status |= Protocol; if (auto *ident = dyn_cast_or_null<IdentTypeRepr>(Protocol.getPtrOrNull())) Protocols.push_back(ident); } while (consumeIf(tok::comma)); } // Check for the terminating '>'. SourceLoc RAngleLoc = PreviousLoc; if (startsWithGreater(Tok)) { RAngleLoc = consumeStartingGreater(); } else { if (Status.isSuccess()) { diagnose(Tok, diag::expected_rangle_protocol); diagnose(LAngleLoc, diag::opening_angle); Status.setIsParseError(); } // Skip until we hit the '>'. RAngleLoc = skipUntilGreaterInTypeList(/*protocolComposition=*/true); } auto composition = CompositionTypeRepr::create( Context, Protocols, ProtocolLoc, {LAngleLoc, RAngleLoc}); if (Status.isSuccess()) { // Only if we have complete protocol<...> construct, diagnose deprecated. SmallString<32> replacement; if (Protocols.empty()) { replacement = "Any"; } else { auto extractText = [&](TypeRepr *Ty) -> StringRef { auto SourceRange = Ty->getSourceRange(); return SourceMgr.extractText( Lexer::getCharSourceRangeFromSourceRange(SourceMgr, SourceRange)); }; auto Begin = Protocols.begin(); replacement += extractText(*Begin); while (++Begin != Protocols.end()) { replacement += " & "; replacement += extractText(*Begin); } } if (Protocols.size() > 1) { // Need parenthesis if the next token looks like postfix TypeRepr. // i.e. '?', '!', '.Type', '.Protocol' bool needParen = false; needParen |= !Tok.isAtStartOfLine() && (isOptionalToken(Tok) || isImplicitlyUnwrappedOptionalToken(Tok)); needParen |= Tok.isAny(tok::period, tok::period_prefix); if (needParen) { replacement.insert(replacement.begin(), '('); replacement += ")"; } } // Copy split token after '>' to the replacement string. // FIXME: lexer should smartly separate '>' and trailing contents like '?'. StringRef TrailingContent = L->getTokenAt(RAngleLoc).getRange().str(). substr(1); if (!TrailingContent.empty()) { replacement += TrailingContent; } // Replace 'protocol<T1, T2>' with 'T1 & T2' diagnose(ProtocolLoc, IsEmpty ? diag::deprecated_any_composition : Protocols.size() > 1 ? diag::deprecated_protocol_composition : diag::deprecated_protocol_composition_single) .highlight(composition->getSourceRange()) .fixItReplace(composition->getSourceRange(), replacement); } return makeParserResult(Status, composition); } /// parseTypeTupleBody /// type-tuple: /// '(' type-tuple-body? ')' /// type-tuple-body: /// type-tuple-element (',' type-tuple-element)* '...'? /// type-tuple-element: /// identifier? identifier ':' type /// type ParserResult<TypeRepr> Parser::parseTypeTupleBody() { // Force the context to create deferred nodes, as we might need to // de-structure the tuple type to create a function type. DeferringContextRAII Deferring(*SyntaxContext); SyntaxParsingContext TypeContext(SyntaxContext, SyntaxKind::TupleType); TypeContext.setCreateSyntax(SyntaxKind::TupleType); Parser::StructureMarkerRAII ParsingTypeTuple(*this, Tok); if (ParsingTypeTuple.isFailed()) { return makeParserError(); } SourceLoc RPLoc, LPLoc = consumeToken(tok::l_paren); SourceLoc EllipsisLoc; unsigned EllipsisIdx; SmallVector<TupleTypeReprElement, 8> ElementsR; ParserStatus Status = parseList(tok::r_paren, LPLoc, RPLoc, /*AllowSepAfterLast=*/false, diag::expected_rparen_tuple_type_list, SyntaxKind::TupleTypeElementList, [&] () -> ParserStatus { TupleTypeReprElement element; // 'inout' here can be a obsoleted use of the marker in an argument list, // consume it in backtracking context so we can determine it's really a // deprecated use of it. llvm::Optional<BacktrackingScope> Backtracking; SourceLoc ObsoletedInOutLoc; if (Tok.is(tok::kw_inout)) { Backtracking.emplace(*this); ObsoletedInOutLoc = consumeToken(tok::kw_inout); } // If the label is "some", this could end up being an opaque type // description if there's `some <identifier>` without a following colon, // so we may need to backtrack as well. if (Tok.getText().equals("some")) { Backtracking.emplace(*this); } // If the tuple element starts with a potential argument label followed by a // ':' or another potential argument label, then the identifier is an // element tag, and it is followed by a type annotation. if (Tok.canBeArgumentLabel() && (peekToken().is(tok::colon) || peekToken().canBeArgumentLabel())) { // Consume a name. element.NameLoc = consumeArgumentLabel(element.Name); // If there is a second name, consume it as well. if (Tok.canBeArgumentLabel()) element.SecondNameLoc = consumeArgumentLabel(element.SecondName); // Consume the ':'. if (consumeIf(tok::colon, element.ColonLoc)) { // If we succeed, then we successfully parsed a label. if (Backtracking) Backtracking->cancelBacktrack(); // Otherwise, if we can't backtrack to parse this as a type, // this is a syntax error. } else { if (!Backtracking) { diagnose(Tok, diag::expected_parameter_colon); } element.NameLoc = SourceLoc(); element.SecondNameLoc = SourceLoc(); } } else if (Backtracking) { // If we don't have labels, 'inout' is not a obsoleted use. ObsoletedInOutLoc = SourceLoc(); } Backtracking.reset(); // Parse the type annotation. auto type = parseType(diag::expected_type); if (type.hasCodeCompletion()) return makeParserCodeCompletionStatus(); if (type.isNull()) return makeParserError(); element.Type = type.get(); // Complain obsoleted 'inout' etc. position; (inout name: Ty) if (ObsoletedInOutLoc.isValid()) { if (isa<SpecifierTypeRepr>(element.Type)) { // If the parsed type is already a inout type et al, just remove it. diagnose(Tok, diag::parameter_specifier_repeated) .fixItRemove(ObsoletedInOutLoc); } else { diagnose(ObsoletedInOutLoc, diag::parameter_specifier_as_attr_disallowed, "inout") .fixItRemove(ObsoletedInOutLoc) .fixItInsert(element.Type->getStartLoc(), "inout "); // Build inout type. Note that we bury the inout locator within the // named locator. This is weird but required by Sema apparently. element.Type = new (Context) InOutTypeRepr(element.Type, ObsoletedInOutLoc); } } // Parse optional '...'. if (Tok.isEllipsis()) { Tok.setKind(tok::ellipsis); auto ElementEllipsisLoc = consumeToken(); if (EllipsisLoc.isInvalid()) { EllipsisLoc = ElementEllipsisLoc; EllipsisIdx = ElementsR.size(); } else { diagnose(ElementEllipsisLoc, diag::multiple_ellipsis_in_tuple) .highlight(EllipsisLoc) .fixItRemove(ElementEllipsisLoc); } } // Parse '= expr' here so we can complain about it directly, rather // than dying when we see it. if (Tok.is(tok::equal)) { SyntaxParsingContext InitContext(SyntaxContext, SyntaxKind::InitializerClause); SourceLoc equalLoc = consumeToken(tok::equal); auto init = parseExpr(diag::expected_init_value); auto inFlight = diagnose(equalLoc, diag::tuple_type_init); if (init.isNonNull()) inFlight.fixItRemove(SourceRange(equalLoc, init.get()->getEndLoc())); } // Record the ',' location. if (Tok.is(tok::comma)) element.TrailingCommaLoc = Tok.getLoc(); ElementsR.push_back(element); return makeParserSuccess(); }); if (EllipsisLoc.isInvalid()) EllipsisIdx = ElementsR.size(); bool isFunctionType = Tok.isAny(tok::arrow, tok::kw_throws, tok::kw_rethrows); // If there were any labels, figure out which labels should go into the type // representation. for (auto &element : ElementsR) { // True tuples have labels. if (!isFunctionType) { // If there were two names, complain. if (element.NameLoc.isValid() && element.SecondNameLoc.isValid()) { auto diag = diagnose(element.NameLoc, diag::tuple_type_multiple_labels); if (element.Name.empty()) { diag.fixItRemoveChars(element.NameLoc, element.Type->getStartLoc()); } else { diag.fixItRemove( SourceRange(Lexer::getLocForEndOfToken(SourceMgr, element.NameLoc), element.SecondNameLoc)); } } continue; } // If there was a first name, complain; arguments in function types are // always unlabeled. if (element.NameLoc.isValid() && !element.Name.empty()) { auto diag = diagnose(element.NameLoc, diag::function_type_argument_label, element.Name); if (element.SecondNameLoc.isInvalid()) diag.fixItInsert(element.NameLoc, "_ "); else if (element.SecondName.empty()) diag.fixItRemoveChars(element.NameLoc, element.Type->getStartLoc()); else diag.fixItReplace(SourceRange(element.NameLoc), "_"); } if (element.SecondNameLoc.isValid()) { // Form the named parameter type representation. element.UnderscoreLoc = element.NameLoc; element.Name = element.SecondName; element.NameLoc = element.SecondNameLoc; } } return makeParserResult(Status, TupleTypeRepr::create(Context, ElementsR, SourceRange(LPLoc, RPLoc), EllipsisLoc, EllipsisIdx)); } /// parseTypeArray - Parse the type-array production, given that we /// are looking at the initial l_square. Note that this index /// clause is actually the outermost (first-indexed) clause. /// /// type-array: /// type-simple /// type-array '[' ']' /// type-array '[' expr ']' /// ParserResult<TypeRepr> Parser::parseTypeArray(TypeRepr *Base) { assert(Tok.isFollowingLSquare()); Parser::StructureMarkerRAII ParsingArrayBound(*this, Tok); SourceLoc lsquareLoc = consumeToken(); ArrayTypeRepr *ATR = nullptr; // Handle a postfix [] production, a common typo for a C-like array. // If we have something that might be an array size expression, parse it as // such, for better error recovery. if (Tok.isNot(tok::r_square)) { auto sizeEx = parseExprBasic(diag::expected_expr); if (sizeEx.hasCodeCompletion()) return makeParserCodeCompletionStatus(); } SourceLoc rsquareLoc; if (parseMatchingToken(tok::r_square, rsquareLoc, diag::expected_rbracket_array_type, lsquareLoc)) return makeParserErrorResult(Base); // If we parsed something valid, diagnose it with a fixit to rewrite it to // Swift syntax. diagnose(lsquareLoc, diag::new_array_syntax) .fixItInsert(Base->getStartLoc(), "[") .fixItRemove(lsquareLoc); // Build a normal array slice type for recovery. ATR = new (Context) ArrayTypeRepr(Base, SourceRange(Base->getStartLoc(), rsquareLoc)); return makeParserResult(ATR); } SyntaxParserResult<ParsedTypeSyntax, TypeRepr> Parser::parseTypeCollection() { ParserStatus Status; // Parse the leading '['. assert(Tok.is(tok::l_square)); Parser::StructureMarkerRAII parsingCollection(*this, Tok); SourceLoc lsquareLoc = consumeToken(); // Parse the element type. ParserResult<TypeRepr> firstTy = parseType(diag::expected_element_type); Status |= firstTy; // If there is a ':', this is a dictionary type. SourceLoc colonLoc; ParserResult<TypeRepr> secondTy; if (Tok.is(tok::colon)) { colonLoc = consumeToken(); // Parse the second type. secondTy = parseType(diag::expected_dictionary_value_type); Status |= secondTy; } // Parse the closing ']'. SourceLoc rsquareLoc; if (parseMatchingToken(tok::r_square, rsquareLoc, colonLoc.isValid() ? diag::expected_rbracket_dictionary_type : diag::expected_rbracket_array_type, lsquareLoc)) Status.setIsParseError(); if (Status.hasCodeCompletion()) return Status; // If we couldn't parse anything for one of the types, propagate the error. if (Status.isError()) return makeParserError(); TypeRepr *TyR; llvm::Optional<ParsedTypeSyntax> SyntaxNode; SourceRange brackets(lsquareLoc, rsquareLoc); if (colonLoc.isValid()) { // Form the dictionary type. TyR = new (Context) DictionaryTypeRepr(firstTy.get(), secondTy.get(), colonLoc, brackets); if (SyntaxContext->isEnabled()) { ParsedDictionaryTypeSyntaxBuilder Builder(*SyntaxContext); auto RightSquareBracket = SyntaxContext->popToken(); auto ValueType(std::move(*SyntaxContext->popIf<ParsedTypeSyntax>())); auto Colon = SyntaxContext->popToken(); auto KeyType(std::move(*SyntaxContext->popIf<ParsedTypeSyntax>())); auto LeftSquareBracket = SyntaxContext->popToken(); Builder .useRightSquareBracket(std::move(RightSquareBracket)) .useValueType(std::move(ValueType)) .useColon(std::move(Colon)) .useKeyType(std::move(KeyType)) .useLeftSquareBracket(std::move(LeftSquareBracket)); SyntaxNode.emplace(Builder.build()); } } else { // Form the array type. TyR = new (Context) ArrayTypeRepr(firstTy.get(), brackets); if (SyntaxContext->isEnabled()) { ParsedArrayTypeSyntaxBuilder Builder(*SyntaxContext); auto RightSquareBracket = SyntaxContext->popToken(); auto ElementType(std::move(*SyntaxContext->popIf<ParsedTypeSyntax>())); auto LeftSquareBracket = SyntaxContext->popToken(); Builder .useRightSquareBracket(std::move(RightSquareBracket)) .useElementType(std::move(ElementType)) .useLeftSquareBracket(std::move(LeftSquareBracket)); SyntaxNode.emplace(Builder.build()); } } return makeSyntaxResult(Status, std::move(SyntaxNode), TyR); } bool Parser::isOptionalToken(const Token &T) const { // A postfix '?' by itself is obviously optional. if (T.is(tok::question_postfix)) return true; // A postfix or bound infix operator token that begins with '?' can be // optional too. We'll munch off the '?', so long as it is left-bound with // the type (i.e., parsed as a postfix or unspaced binary operator). if ((T.is(tok::oper_postfix) || T.is(tok::oper_binary_unspaced)) && T.getText().startswith("?")) return true; return false; } bool Parser::isImplicitlyUnwrappedOptionalToken(const Token &T) const { // A postfix '!' by itself, or a '!' in SIL mode, is obviously implicitly // unwrapped optional. if (T.is(tok::exclaim_postfix) || T.is(tok::sil_exclamation)) return true; // A postfix or bound infix operator token that begins with '!' can be // implicitly unwrapped optional too. We'll munch off the '!', so long as it // is left-bound with the type (i.e., parsed as a postfix or unspaced binary // operator). if ((T.is(tok::oper_postfix) || T.is(tok::oper_binary_unspaced)) && T.getText().startswith("!")) return true; return false; } SourceLoc Parser::consumeOptionalToken() { assert(isOptionalToken(Tok) && "not a '?' token?!"); return consumeStartingCharacterOfCurrentToken(tok::question_postfix); } SourceLoc Parser::consumeImplicitlyUnwrappedOptionalToken() { assert(isImplicitlyUnwrappedOptionalToken(Tok) && "not a '!' token?!"); // If the text of the token is just '!', grab the next token. return consumeStartingCharacterOfCurrentToken(tok::exclaim_postfix); } /// Parse a single optional suffix, given that we are looking at the /// question mark. SyntaxParserResult<ParsedTypeSyntax, TypeRepr> Parser::parseTypeOptional(TypeRepr *base) { SourceLoc questionLoc = consumeOptionalToken(); auto TyR = new (Context) OptionalTypeRepr(base, questionLoc); llvm::Optional<ParsedTypeSyntax> SyntaxNode; if (SyntaxContext->isEnabled()) { auto QuestionMark = SyntaxContext->popToken(); if (auto WrappedType = SyntaxContext->popIf<ParsedTypeSyntax>()) { ParsedOptionalTypeSyntaxBuilder Builder(*SyntaxContext); Builder .useQuestionMark(std::move(QuestionMark)) .useWrappedType(std::move(*WrappedType)); SyntaxNode.emplace(Builder.build()); } else { // Undo the popping of the question mark SyntaxContext->addSyntax(std::move(QuestionMark)); } } return makeSyntaxResult(std::move(SyntaxNode), TyR); } /// Parse a single implicitly unwrapped optional suffix, given that we /// are looking at the exclamation mark. SyntaxParserResult<ParsedTypeSyntax, TypeRepr> Parser::parseTypeImplicitlyUnwrappedOptional(TypeRepr *base) { SourceLoc exclamationLoc = consumeImplicitlyUnwrappedOptionalToken(); auto TyR = new (Context) ImplicitlyUnwrappedOptionalTypeRepr(base, exclamationLoc); llvm::Optional<ParsedTypeSyntax> SyntaxNode; if (SyntaxContext->isEnabled()) { ParsedImplicitlyUnwrappedOptionalTypeSyntaxBuilder Builder(*SyntaxContext); auto ExclamationMark = SyntaxContext->popToken(); auto WrappedType(std::move(*SyntaxContext->popIf<ParsedTypeSyntax>())); Builder .useExclamationMark(std::move(ExclamationMark)) .useWrappedType(std::move(WrappedType)); SyntaxNode.emplace(Builder.build()); } return makeSyntaxResult(std::move(SyntaxNode), TyR); } //===----------------------------------------------------------------------===// // Speculative type list parsing //===----------------------------------------------------------------------===// static bool isGenericTypeDisambiguatingToken(Parser &P) { auto &tok = P.Tok; switch (tok.getKind()) { default: return false; case tok::r_paren: case tok::r_square: case tok::l_brace: case tok::r_brace: case tok::period: case tok::period_prefix: case tok::comma: case tok::semi: case tok::eof: case tok::code_complete: case tok::exclaim_postfix: case tok::question_postfix: case tok::colon: return true; case tok::oper_binary_spaced: if (tok.getText() == "&") return true; LLVM_FALLTHROUGH; case tok::oper_binary_unspaced: case tok::oper_postfix: // These might be '?' or '!' type modifiers. return P.isOptionalToken(tok) || P.isImplicitlyUnwrappedOptionalToken(tok); case tok::l_paren: case tok::l_square: // These only apply to the generic type if they don't start a new line. return !tok.isAtStartOfLine(); } } bool Parser::canParseAsGenericArgumentList() { if (!Tok.isAnyOperator() || !Tok.getText().equals("<")) return false; BacktrackingScope backtrack(*this); if (canParseGenericArguments()) return isGenericTypeDisambiguatingToken(*this); return false; } bool Parser::canParseGenericArguments() { // Parse the opening '<'. if (!startsWithLess(Tok)) return false; consumeStartingLess(); do { if (!canParseType()) return false; // Parse the comma, if the list continues. } while (consumeIf(tok::comma)); if (!startsWithGreater(Tok)) { return false; } else { consumeStartingGreater(); return true; } } bool Parser::canParseType() { // Accept 'inout' at for better recovery. consumeIf(tok::kw_inout); switch (Tok.getKind()) { case tok::kw_Self: case tok::kw_Any: if (!canParseTypeIdentifier()) return false; break; case tok::kw_protocol: // Deprecated composition syntax case tok::identifier: if (!canParseTypeIdentifierOrTypeComposition()) return false; break; case tok::l_paren: { consumeToken(); if (!canParseTypeTupleBody()) return false; break; } case tok::at_sign: { consumeToken(); if (!canParseTypeAttribute()) return false; return canParseType(); } case tok::l_square: consumeToken(); if (!canParseType()) return false; if (consumeIf(tok::colon)) { if (!canParseType()) return false; } if (!consumeIf(tok::r_square)) return false; break; default: return false; } // '.Type', '.Protocol', '?', and '!' still leave us with type-simple. while (true) { if ((Tok.is(tok::period) || Tok.is(tok::period_prefix)) && (peekToken().isContextualKeyword("Type") || peekToken().isContextualKeyword("Protocol"))) { consumeToken(); consumeToken(tok::identifier); continue; } if (isOptionalToken(Tok)) { consumeOptionalToken(); continue; } if (isImplicitlyUnwrappedOptionalToken(Tok)) { consumeImplicitlyUnwrappedOptionalToken(); continue; } break; } // Handle type-function if we have an 'async'. if (Context.LangOpts.EnableExperimentalConcurrency && Tok.isContextualKeyword("async")) { consumeToken(); // 'async' isn't a valid type without being followed by throws/rethrows // or a return. if (!Tok.isAny(tok::kw_throws, tok::kw_rethrows, tok::arrow)) return false; } // Handle type-function if we have an arrow or 'throws'/'rethrows' modifier. if (Tok.isAny(tok::kw_throws, tok::kw_rethrows)) { consumeToken(); // Allow 'async' here even though it is ill-formed, so we can provide // a better error. if (Context.LangOpts.EnableExperimentalConcurrency && Tok.isContextualKeyword("async")) consumeToken(); // "throws" or "rethrows" isn't a valid type without being followed by // a return. We also accept 'async' here so we can provide a better // error. if (!Tok.is(tok::arrow)) return false; } if (consumeIf(tok::arrow)) { if (!canParseType()) return false; return true; } return true; } bool Parser::canParseTypeIdentifierOrTypeComposition() { if (Tok.is(tok::kw_protocol)) return canParseOldStyleProtocolComposition(); while (true) { if (!canParseTypeIdentifier()) return false; if (Tok.isContextualPunctuator("&")) { consumeToken(); continue; } else { return true; } } } bool Parser::canParseSimpleTypeIdentifier() { // Parse an identifier. if (!Tok.isAny(tok::identifier, tok::kw_Self, tok::kw_Any)) return false; consumeToken(); // Parse an optional generic argument list. if (startsWithLess(Tok)) if (!canParseGenericArguments()) return false; return true; } bool Parser::canParseTypeIdentifier() { while (true) { if (!canParseSimpleTypeIdentifier()) return false; // Treat 'Foo.<anything>' as an attempt to write a dotted type // unless <anything> is 'Type' or 'Protocol'. if ((Tok.is(tok::period) || Tok.is(tok::period_prefix)) && !peekToken().isContextualKeyword("Type") && !peekToken().isContextualKeyword("Protocol")) { consumeToken(); } else { return true; } } } bool Parser::canParseBaseTypeForQualifiedDeclName() { BacktrackingScope backtrack(*this); // Parse a simple type identifier. if (!canParseSimpleTypeIdentifier()) return false; // Qualified name base types must be followed by a period. // If the next token starts with a period, return true. return startsWithSymbol(Tok, '.'); } bool Parser::canParseOldStyleProtocolComposition() { consumeToken(tok::kw_protocol); // Check for the starting '<'. if (!startsWithLess(Tok)) { return false; } consumeStartingLess(); // Check for empty protocol composition. if (startsWithGreater(Tok)) { consumeStartingGreater(); return true; } // Parse the type-composition-list. do { if (!canParseTypeIdentifier()) { return false; } } while (consumeIf(tok::comma)); // Check for the terminating '>'. if (!startsWithGreater(Tok)) { return false; } consumeStartingGreater(); return true; } bool Parser::canParseTypeTupleBody() { if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::r_brace) && Tok.isNotEllipsis() && !isStartOfSwiftDecl()) { do { // The contextual inout marker is part of argument lists. consumeIf(tok::kw_inout); // If the tuple element starts with "ident :", then it is followed // by a type annotation. if (Tok.canBeArgumentLabel() && (peekToken().is(tok::colon) || peekToken().canBeArgumentLabel())) { consumeToken(); if (Tok.canBeArgumentLabel()) { consumeToken(); if (!Tok.is(tok::colon)) return false; } consumeToken(tok::colon); // Parse a type. if (!canParseType()) return false; // Parse default values. This aren't actually allowed, but we recover // better if we skip over them. if (consumeIf(tok::equal)) { while (Tok.isNot(tok::eof) && Tok.isNot(tok::r_paren) && Tok.isNot(tok::r_brace) && Tok.isNotEllipsis() && Tok.isNot(tok::comma) && !isStartOfSwiftDecl()) { skipSingle(); } } continue; } // Otherwise, this has to be a type. if (!canParseType()) return false; if (Tok.isEllipsis()) consumeToken(); } while (consumeIf(tok::comma)); } return consumeIf(tok::r_paren); }
{ "content_hash": "79c026a563a3d5456a1c1c44a8d60804", "timestamp": "", "source": "github", "line_count": 1765, "max_line_length": 90, "avg_line_length": 33.50084985835694, "alnum_prop": 0.6323124016979824, "repo_name": "jckarter/swift", "id": "443f572c04acb79dc75ac469fa3c4bf10511ee39", "size": "59129", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/Parse/ParseType.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "13584" }, { "name": "C", "bytes": "271996" }, { "name": "C++", "bytes": "38607436" }, { "name": "CMake", "bytes": "549408" }, { "name": "D", "bytes": "1107" }, { "name": "DTrace", "bytes": "2593" }, { "name": "Emacs Lisp", "bytes": "57338" }, { "name": "LLVM", "bytes": "70652" }, { "name": "MATLAB", "bytes": "2576" }, { "name": "Makefile", "bytes": "1841" }, { "name": "Objective-C", "bytes": "427480" }, { "name": "Objective-C++", "bytes": "243488" }, { "name": "Python", "bytes": "1789902" }, { "name": "Roff", "bytes": "3495" }, { "name": "Ruby", "bytes": "2117" }, { "name": "Shell", "bytes": "183121" }, { "name": "Swift", "bytes": "33610968" }, { "name": "Vim Script", "bytes": "19900" }, { "name": "sed", "bytes": "1050" } ], "symlink_target": "" }
#include "types.h" #include "qpid/Msg.h" #include "qpid/broker/Message.h" #include "qpid/broker/Queue.h" #include "qpid/Exception.h" #include <algorithm> #include <iostream> #include <iterator> #include <assert.h> namespace qpid { namespace ha { using namespace std; const string QPID_REPLICATE("qpid.replicate"); const string QPID_HA_UUID("qpid.ha-uuid"); const char* QPID_HA_PREFIX = "qpid.ha-"; const char* QUEUE_REPLICATOR_PREFIX = "qpid.ha-q:"; bool startsWith(const string& name, const string& prefix) { return name.compare(0, prefix.size(), prefix) == 0; } string EnumBase::str() const { assert(value < count); return names[value]; } void EnumBase::parse(const string& s) { if (!parseNoThrow(s)) throw Exception(QPID_MSG("Invalid " << name << " value: " << s)); } bool EnumBase::parseNoThrow(const string& s) { const char** i = find(names, names+count, s); value = i - names; return value < count; } template <> const char* Enum<ReplicateLevel>::NAME = "replication"; template <> const char* Enum<ReplicateLevel>::NAMES[] = { "none", "configuration", "all" }; template <> const size_t Enum<ReplicateLevel>::N = 3; template <> const char* Enum<BrokerStatus>::NAME = "HA broker status"; // NOTE: Changing status names will have an impact on qpid-ha and // the qpidd-primary init script. // Don't change them unless you are going to update all dependent code. // template <> const char* Enum<BrokerStatus>::NAMES[] = { "joining", "catchup", "ready", "recovering", "active", "standalone" }; template <> const size_t Enum<BrokerStatus>::N = 6; ostream& operator<<(ostream& o, EnumBase e) { return o << e.str(); } istream& operator>>(istream& i, EnumBase& e) { string s; i >> s; e.parse(s); return i; } ostream& operator<<(ostream& o, const UuidSet& ids) { ostream_iterator<qpid::types::Uuid> out(o, " "); o << "{ "; for (UuidSet::const_iterator i = ids.begin(); i != ids.end(); ++i) o << shortStr(*i) << " "; o << "}"; return o; } std::string logMessageId(const std::string& q, QueuePosition pos, ReplicationId id) { return Msg() << q << "[" << pos << "]" << "=" << id; } std::string logMessageId(const std::string& q, ReplicationId id) { return Msg() << q << "[]" << "=" << id; } std::string logMessageId(const std::string& q, const broker::Message& m) { return logMessageId(q, m.getSequence(), m.getReplicationId()); } std::string logMessageId(const broker::Queue& q, QueuePosition pos, ReplicationId id) { return logMessageId(q.getName(), pos, id); } std::string logMessageId(const broker::Queue& q, ReplicationId id) { return logMessageId(q.getName(), id); } std::string logMessageId(const broker::Queue& q, const broker::Message& m) { return logMessageId(q.getName(), m); } void UuidSet::encode(framing::Buffer& b) const { b.putLong(size()); for (const_iterator i = begin(); i != end(); ++i) b.putRawData(i->data(), i->size()); } void UuidSet::decode(framing::Buffer& b) { size_t n = b.getLong(); for ( ; n > 0; --n) { types::Uuid id; b.getRawData(const_cast<unsigned char*>(id.data()), id.size()); insert(id); } } size_t UuidSet::encodedSize() const { return sizeof(uint32_t) + size()*16; } }} // namespace qpid::ha
{ "content_hash": "f21d21cc471937097f1fbe5958e3b91d", "timestamp": "", "source": "github", "line_count": 119, "max_line_length": 91, "avg_line_length": 27.88235294117647, "alnum_prop": 0.6347197106690777, "repo_name": "mbroadst/debian-qpid-cpp", "id": "3088661c954598de1fa21e93a4e568376e1b2305", "size": "4131", "binary": false, "copies": "3", "ref": "refs/heads/trusty", "path": "src/qpid/ha/types.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2126" }, { "name": "C", "bytes": "67620" }, { "name": "C#", "bytes": "121990" }, { "name": "C++", "bytes": "7291355" }, { "name": "CMake", "bytes": "169753" }, { "name": "Cucumber", "bytes": "15299" }, { "name": "Emacs Lisp", "bytes": "7379" }, { "name": "HTML", "bytes": "4773" }, { "name": "Makefile", "bytes": "1261" }, { "name": "Perl", "bytes": "86022" }, { "name": "Perl6", "bytes": "2703" }, { "name": "PowerShell", "bytes": "51728" }, { "name": "Python", "bytes": "1523448" }, { "name": "Ruby", "bytes": "305919" }, { "name": "Shell", "bytes": "128410" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <OfficeApp xmlns="http://schemas.microsoft.com/office/appforoffice/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bt="http://schemas.microsoft.com/office/officeappbasictypes/1.0" xsi:type="TaskPaneApp"> <Id>25606e74-f0f5-4020-bea8-b45f8c1e8b7a</Id> <Version>1.0</Version> <ProviderName>Microsoft</ProviderName> <DefaultLocale>EN-US</DefaultLocale> <DisplayName DefaultValue="WordJS Snippet Explorer"/> <Description DefaultValue="Contains snippets for WordJS."/> <!-- Icon for your add-in. Used on installation screens and the add-ins dialog. --> <IconUrl DefaultValue="https://appcommandicons.blob.core.windows.net/images/taskpane_32x.png" /> <Hosts> <Host Name="Document"/> </Hosts> <DefaultSettings> <SourceLocation DefaultValue="https://officesnippetexplorer.azurewebsites.net/#/add-in/word"/> </DefaultSettings> <Permissions>ReadWriteDocument</Permissions> <!-- Begin Add-in Commands Mode integration. --> <VersionOverrides xmlns="http://schemas.microsoft.com/office/taskpaneappversionoverrides" xsi:type="VersionOverridesV1_0"> <!-- The Hosts node is required. --> <Hosts> <!-- Each host can have a different set of commands. --> <!-- Excel host is Workbook, Word host is Document, and PowerPoint host is Presentation. --> <!-- Make sure the hosts you override match the hosts declared in the top section of the manifest. --> <Host xsi:type="Document"> <!-- Form factor. Currently only DesktopFormFactor is supported. --> <DesktopFormFactor> <!--"This code enables a customizable message to be displayed when the add-in is loaded successfully upon individual install."--> <GetStarted> <!-- Title of the Getting Started callout. resid points to a ShortString resource --> <Title resid="Contoso.GetStarted.Title"/> <!-- Description of the Getting Started callout. resid points to a LongString resource --> <Description resid="Contoso.GetStarted.Description"/> <!-- Point to a url resource which details how the add-in should be used. --> <LearnMoreUrl resid="Contoso.GetStarted.LearnMoreUrl"/> </GetStarted> <!-- Function file is a HTML page that includes the JavaScript where functions for ExecuteAction will be called. Think of the FunctionFile as the code behind ExecuteFunction. --> <FunctionFile resid="Contoso.DesktopFunctionFile.Url" /> <!-- PrimaryCommandSurface is the main Office Ribbon. --> <ExtensionPoint xsi:type="PrimaryCommandSurface"> <!-- Use OfficeTab to extend an existing Tab. Use CustomTab to create a new tab. --> <OfficeTab id="TabHome"> <!-- Ensure you provide a unique id for the group. Recommendation for any IDs is to namespace using your company name. --> <Group id="Contoso.Group1"> <!-- Label for your group. resid must point to a ShortString resource. --> <Label resid="Contoso.Group1Label" /> <!-- Icons. Required sizes 16,32,80, optional 20, 24, 40, 48, 64. Strongly recommended to provide all sizes for great UX. --> <!-- Use PNG icons. All URLs on the resources section must use HTTPS. --> <Icon> <bt:Image size="16" resid="Contoso.tpicon_16x16" /> <bt:Image size="32" resid="Contoso.tpicon_32x32" /> <bt:Image size="80" resid="Contoso.tpicon_80x80" /> </Icon> <!-- Control. It can be of type "Button" or "Menu". --> <Control xsi:type="Button" id="Contoso.TaskpaneButton"> <Label resid="Contoso.TaskpaneButton.Label" /> <Supertip> <!-- ToolTip title. resid must point to a ShortString resource. --> <Title resid="Contoso.TaskpaneButton.Label" /> <!-- ToolTip description. resid must point to a LongString resource. --> <Description resid="Contoso.TaskpaneButton.Tooltip" /> </Supertip> <Icon> <bt:Image size="16" resid="Contoso.tpicon_16x16" /> <bt:Image size="32" resid="Contoso.tpicon_32x32" /> <bt:Image size="80" resid="Contoso.tpicon_80x80" /> </Icon> <!-- This is what happens when the command is triggered (E.g. click on the Ribbon). Supported actions are ExecuteFunction or ShowTaskpane. --> <Action xsi:type="ShowTaskpane"> <TaskpaneId>ButtonId1</TaskpaneId> <!-- Provide a url resource id for the location that will be displayed on the task pane. --> <SourceLocation resid="Contoso.Taskpane.Url" /> </Action> </Control> </Group> </OfficeTab> </ExtensionPoint> </DesktopFormFactor> </Host> </Hosts> <!-- You can use resources across hosts and form factors. --> <Resources> <bt:Images> <bt:Image id="Contoso.tpicon_16x16" DefaultValue="https://appcommandicons.blob.core.windows.net/images/taskpane_16x.png" /> <bt:Image id="Contoso.tpicon_32x32" DefaultValue="https://appcommandicons.blob.core.windows.net/images/taskpane_32x.png" /> <bt:Image id="Contoso.tpicon_80x80" DefaultValue="https://appcommandicons.blob.core.windows.net/images/taskpane_80x.png" /> </bt:Images> <bt:Urls> <bt:Url id="Contoso.DesktopFunctionFile.Url" DefaultValue="https://officesnippetexplorer.azurewebsites.net/#/add-in/word" /> <bt:Url id="Contoso.Taskpane.Url" DefaultValue="https://officesnippetexplorer.azurewebsites.net/#/add-in/word" /> <bt:Url id="Contoso.GetStarted.LearnMoreUrl" DefaultValue="https://go.microsoft.com/fwlink/?LinkId=276812" /> </bt:Urls> <!-- ShortStrings max characters==125. --> <bt:ShortStrings> <bt:String id="Contoso.TaskpaneButton.Label" DefaultValue="Open Task Pane" /> <bt:String id="Contoso.Group1Label" DefaultValue="Snippet Explorer" /> <bt:String id="Contoso.GetStarted.Title" DefaultValue="Explore Word JS snippets." /> </bt:ShortStrings> <!-- LongStrings max characters==250. --> <bt:LongStrings> <bt:String id="Contoso.TaskpaneButton.Tooltip" DefaultValue="Click to start the Snippet Explorer add-in" /> <bt:String id="Contoso.GetStarted.Description" DefaultValue="Your sample add-in loaded succesfully. Go to the HOME tab and click the 'Open Task Pane' button to get started." /> </bt:LongStrings> </Resources> </VersionOverrides> <!-- End Add-in Commands Mode integration. --> </OfficeApp>
{ "content_hash": "02e8d846e84d364bacc4c6749216f6c2", "timestamp": "", "source": "github", "line_count": 121, "max_line_length": 184, "avg_line_length": 57.900826446280995, "alnum_prop": 0.620610904938624, "repo_name": "OfficeDev/office-js-snippet-explorer", "id": "a00bcd0234c0a949ff45d2ce45c7209ae017be41", "size": "7006", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "snippet-explorer-wordJS.xml", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "5669" }, { "name": "JavaScript", "bytes": "121579" } ], "symlink_target": "" }
// Copyright (c) 2012-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <clientversion.h> #include <tinyformat.h> /** * Name of client reported in the 'version' message. Report the same name * for both bitcoind and bitcoin-qt, to make it harder for attackers to * target servers or GUI users specifically. */ const std::string CLIENT_NAME("Veni"); /** * Client version number */ #define CLIENT_VERSION_SUFFIX "-minki" /** * The following part of the code determines the CLIENT_BUILD variable. * Several mechanisms are used for this: * * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is * generated by the build environment, possibly containing the output * of git-describe in a macro called BUILD_DESC * * secondly, if this is an exported version of the code, GIT_ARCHIVE will * be defined (automatically using the export-subst git attribute), and * GIT_COMMIT will contain the commit id. * * then, three options exist for determining CLIENT_BUILD: * * if BUILD_DESC is defined, use that literally (output of git-describe) * * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] * * otherwise, use v[maj].[min].[rev].[build]-unk * finally CLIENT_VERSION_SUFFIX is added */ //! First, include build.h if requested #ifdef HAVE_BUILD_INFO #include <obj/build.h> #endif //! git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$ #ifdef GIT_ARCHIVE #define GIT_COMMIT_ID "$Format:%H$" #define GIT_COMMIT_DATE "$Format:%cD$" #endif #define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix) #define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC #ifdef BUILD_SUFFIX #define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX) #elif defined(GIT_COMMIT_ID) #define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) #else #define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) #endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); static std::string FormatVersion(int nVersion) { if (nVersion % 100 == 0) return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100); else return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100); } std::string FormatFullVersion() { return CLIENT_BUILD; } /** * Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki) */ std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments) { std::ostringstream ss; ss << "/"; ss << name << ":" << FormatVersion(nClientVersion); if (!comments.empty()) { std::vector<std::string>::const_iterator it(comments.begin()); ss << "(" << *it; for(++it; it != comments.end(); ++it) ss << "; " << *it; ss << ")"; } ss << "/"; return ss.str(); }
{ "content_hash": "6a4a9c7e6dc374346fd045ce0a54d5d2", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 147, "avg_line_length": 37.18627450980392, "alnum_prop": 0.6873187450566833, "repo_name": "gjhiggins/vcoincore", "id": "bf73599e50d1c9f2702f388125ebd8ccbb30aa02", "size": "3793", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/clientversion.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "28453" }, { "name": "C", "bytes": "751390" }, { "name": "C++", "bytes": "7015926" }, { "name": "CMake", "bytes": "28560" }, { "name": "HTML", "bytes": "21833" }, { "name": "Java", "bytes": "30291" }, { "name": "M4", "bytes": "208246" }, { "name": "Makefile", "bytes": "106414" }, { "name": "Objective-C", "bytes": "2162" }, { "name": "Objective-C++", "bytes": "5497" }, { "name": "Python", "bytes": "1742616" }, { "name": "QMake", "bytes": "798" }, { "name": "Scheme", "bytes": "6044" }, { "name": "Shell", "bytes": "138233" } ], "symlink_target": "" }
namespace Google.Cloud.Gaming.V1Beta.Snippets { // [START gameservices_v1beta_generated_GameServerConfigsService_GetGameServerConfig_async_flattened_resourceNames] using Google.Cloud.Gaming.V1Beta; using System.Threading.Tasks; public sealed partial class GeneratedGameServerConfigsServiceClientSnippets { /// <summary>Snippet for GetGameServerConfigAsync</summary> /// <remarks> /// This snippet has been automatically generated and should be regarded as a code template only. /// It will require modifications to work: /// - It may require correct/in-range values for request initialization. /// - It may require specifying regional endpoints when creating the service client as shown in /// https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint. /// </remarks> public async Task GetGameServerConfigResourceNamesAsync() { // Create client GameServerConfigsServiceClient gameServerConfigsServiceClient = await GameServerConfigsServiceClient.CreateAsync(); // Initialize request argument(s) GameServerConfigName name = GameServerConfigName.FromProjectLocationDeploymentConfig("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]", "[CONFIG]"); // Make the request GameServerConfig response = await gameServerConfigsServiceClient.GetGameServerConfigAsync(name); } } // [END gameservices_v1beta_generated_GameServerConfigsService_GetGameServerConfig_async_flattened_resourceNames] }
{ "content_hash": "4e64f7cb1fba14a3ea02c9fa112cda57", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 152, "avg_line_length": 56.714285714285715, "alnum_prop": 0.7216624685138538, "repo_name": "googleapis/google-cloud-dotnet", "id": "7bab11bfc1d504b98890d16f3815559449b46627", "size": "2210", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "apis/Google.Cloud.Gaming.V1Beta/Google.Cloud.Gaming.V1Beta.GeneratedSnippets/GameServerConfigsServiceClient.GetGameServerConfigResourceNamesAsyncSnippet.g.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "767" }, { "name": "C#", "bytes": "319820004" }, { "name": "Dockerfile", "bytes": "3415" }, { "name": "PowerShell", "bytes": "3303" }, { "name": "Python", "bytes": "2744" }, { "name": "Shell", "bytes": "65881" } ], "symlink_target": "" }
import * as Enums from '../enums/index'; import * as Models from './index'; /** * TextCase info for input address * @export * @interface AddressValidationInfo */ export interface AddressValidationInfo { /** * @type {string} * @memberof AddressValidationInfo */ line1?: string; /** * @type {Enums.TextCase} * @memberof AddressValidationInfo */ textCase?: Enums.TextCase; /** * @type {string} * @memberof AddressValidationInfo */ line2?: string; /** * @type {string} * @memberof AddressValidationInfo */ line3?: string; /** * @type {string} * @memberof AddressValidationInfo */ city?: string; /** * @type {string} * @memberof AddressValidationInfo */ region?: string; /** * @type {string} * @memberof AddressValidationInfo */ country?: string; /** * @type {string} * @memberof AddressValidationInfo */ postalCode?: string; /** * @type {number} * @memberof AddressValidationInfo */ latitude?: number; /** * @type {number} * @memberof AddressValidationInfo */ longitude?: number; }
{ "content_hash": "6ddfb33d581c621cc3481a5293d21a57", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 41, "avg_line_length": 20.258064516129032, "alnum_prop": 0.5414012738853503, "repo_name": "avadev/AvaTax-REST-V2-JS-SDK", "id": "8512163e8c25d62b01e499df4996233d7210f4e3", "size": "1781", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/models/AddressValidationInfo.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "20379" }, { "name": "TypeScript", "bytes": "1421873" } ], "symlink_target": "" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Diagnostics.Runtime.DacInterface; using Microsoft.Diagnostics.Runtime.Implementation; namespace Microsoft.Diagnostics.Runtime.Builders { internal class AppDomainBuilder : IAppDomainData { private readonly SOSDac _sos; private readonly AppDomainStoreData _appDomainStore; private AppDomainData _appDomainData; public ulong SharedDomain => _appDomainStore.SharedDomain; public ulong SystemDomain => _appDomainStore.SystemDomain; public int AppDomainCount => _appDomainStore.AppDomainCount; public IAppDomainHelpers Helpers { get; } public string? Name { get { if (SharedDomain == Address) return "Shared Domain"; if (SystemDomain == Address) return "System Domain"; return _sos.GetAppDomainName(Address); } } public int Id => _appDomainData.Id; public ulong Address { get; private set; } public AppDomainBuilder(SOSDac sos, IAppDomainHelpers helpers) { _sos = sos; Helpers = helpers; _sos.GetAppDomainStoreData(out _appDomainStore); } public bool Init(ulong address) { Address = address; return _sos.GetAppDomainData(Address, out _appDomainData); } } }
{ "content_hash": "f299d9537018d20ba1e7c8316741778f", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 71, "avg_line_length": 31.173076923076923, "alnum_prop": 0.6224552745219001, "repo_name": "Microsoft/clrmd", "id": "3f3808267d94450de333687c8daabbd1beb654d0", "size": "1623", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Microsoft.Diagnostics.Runtime/src/Builders/AppDomainBuilder.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "783" }, { "name": "C#", "bytes": "2061500" }, { "name": "CMake", "bytes": "9697" }, { "name": "PowerShell", "bytes": "161311" }, { "name": "Shell", "bytes": "92907" } ], "symlink_target": "" }
# grunt-dss2json > Runs [DSS](https://github.com/darcyclarke/dss) over a set of files and builds a JSON file as output. Use [grunt-dss](https://github.com/darcyclarke/grunt-dss) if you want a built in templating option to build documentation. This plugin is inteneded to be used with any templating option you'd like. See [jekyll-dss](https://github.com/ericponto/jekyll-dss) for any example using Jekyll. ## Getting Started This plugin requires Grunt `~0.4.5` If you haven't used [Grunt](http://gruntjs.com/) before, be sure to check out the [Getting Started](http://gruntjs.com/getting-started) guide, as it explains how to create a [Gruntfile](http://gruntjs.com/sample-gruntfile) as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command: ```shell npm install grunt-dss2json --save-dev ``` Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript: ```js grunt.loadNpmTasks('grunt-dss2json'); ``` ## The "dss2json" task ### Overview In your project's Gruntfile, add a section named `dss2json` to the data object passed into `grunt.initConfig()`. Add JSDoc style comments to your CSS (or Sass or Less or Stylus) files to document style blocks. Then run `grunt dss2json` to generate a JSON file with all of the parsed data. #### Example ``` /** * @name Test * @description This is a test * @markup * <div>Test</div> */ body { color: #c0ffee; } ``` ## Settings #### files Type: `Array` or `Object` Default value: `[]` Files to parse. Using Grunt default `files` syntax. [More about that on Gruntjs wiki](https://github.com/gruntjs/grunt/wiki/Configuring-tasks#files). ### Usage Examples ```js grunt.initConfig({ dss2json: { files: { "path/to/output.json": ["css/**.{css,scss,less,stylus}"] } } }); ``` ## Contributing In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/).
{ "content_hash": "f344e425531ce698f95b3fdc1d2fe192", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 351, "avg_line_length": 32.87301587301587, "alnum_prop": 0.7213906325446644, "repo_name": "ericponto/grunt-dss2json", "id": "1dfd372c893a27dec17bbf246d8fce572a4065b9", "size": "2071", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "3415" } ], "symlink_target": "" }
{% extends 'base.html' %} {% load i18n %} {% block title %}{% trans "Signup almost done!" %}{% endblock %} {% block content_title %}<h2>{% trans "Signup" %}</h2>{% endblock %} {% block content_main %} <p>{% trans "Thank you for signing up with us!" %}</p> {% if userena_activation_required %} <p>{% blocktrans %}You have been send an e-mail with an activation link to the supplied email.{% endblocktrans %}</p> <p>{% blocktrans %}We will store your signup information for {{ userena_activation_days }} days on our server. {% endblocktrans %}</p> {% else %} <p>{% blocktrans %}You can now use the supplied credentials to signin.{% endblocktrans %}</p> {% endif %} {% endblock %}
{ "content_hash": "ca97f7d03e86914e7f4b3ace9c7fe04e", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 134, "avg_line_length": 40.1764705882353, "alnum_prop": 0.6486090775988287, "repo_name": "rvanlaar/easy-transifex", "id": "a10c9db686a59054344c6dfdb1b9b4d74613d233", "size": "683", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/transifex/transifex/templates/userena/signup_complete.html", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "105585" }, { "name": "HTML", "bytes": "365175" }, { "name": "JavaScript", "bytes": "187021" }, { "name": "Python", "bytes": "2303001" }, { "name": "Shell", "bytes": "1358" } ], "symlink_target": "" }
RSpec.describe RuboCop::CLI, :isolated_environment do include_context 'cli spec behavior' subject(:cli) { described_class.new } before do RuboCop::ConfigLoader.default_configuration = nil end it 'does not correct ExtraSpacing in a hash that would be changed back' do create_file('.rubocop.yml', <<~YAML) Layout/AlignHash: EnforcedColonStyle: table Style/FrozenStringLiteralComment: Enabled: false YAML source = <<~RUBY hash = { alice: { age: 23, role: 'Director' }, bob: { age: 25, role: 'Consultant' } } RUBY create_file('example.rb', source) expect(cli.run(['--auto-correct'])).to eq(1) expect(IO.read('example.rb')).to eq(source) end it 'does not correct SpaceAroundOperators in a hash that would be ' \ 'changed back' do create_file('.rubocop.yml', <<~YAML) Style/HashSyntax: EnforcedStyle: hash_rockets Layout/AlignHash: EnforcedHashRocketStyle: table YAML source = <<~RUBY a = { 1=>2, a => b } hash = { :alice => { :age => 23, :role => 'Director' }, :bob => { :age => 25, :role => 'Consultant' } } RUBY create_file('example.rb', source) expect(cli.run(['--auto-correct'])).to eq(1) # 1=>2 is changed to 1 => 2. The rest is unchanged. # SpaceAroundOperators leaves it to AlignHash when the style is table. expect(IO.read('example.rb')).to eq(<<~RUBY) # frozen_string_literal: true a = { 1 => 2, a => b } hash = { :alice => { :age => 23, :role => 'Director' }, :bob => { :age => 25, :role => 'Consultant' } } RUBY end describe 'trailing comma cops' do let(:source) do <<~RUBY func({ @abc => 0, @xyz => 1 }) func( { abc: 0 } ) func( {}, { xyz: 1 } ) RUBY end let(:config) do { 'Style/TrailingCommaInArguments' => { 'EnforcedStyleForMultiline' => comma_style }, 'Style/TrailingCommaInArrayLiteral' => { 'EnforcedStyleForMultiline' => comma_style }, 'Style/TrailingCommaInHashLiteral' => { 'EnforcedStyleForMultiline' => comma_style }, 'Style/BracesAroundHashParameters' => braces_around_hash_parameters_config } end before do create_file('example.rb', source) create_file('.rubocop.yml', YAML.dump(config)) end shared_examples 'corrects offenses without producing a double comma' do it 'corrects TrailingCommaInLiteral and TrailingCommaInArguments ' \ 'without producing a double comma' do cli.run(['--auto-correct']) expect(IO.read('example.rb')) .to eq(expected_corrected_source) expect($stderr.string).to eq('') end end context 'when the style is `comma`' do let(:comma_style) do 'comma' end context 'and Style/BracesAroundHashParameters is disabled' do let(:braces_around_hash_parameters_config) do { 'Enabled' => false, 'AutoCorrect' => false, 'EnforcedStyle' => 'braces' } end let(:expected_corrected_source) do <<~RUBY # frozen_string_literal: true func({ @abc => 0, @xyz => 1, }) func( { abc: 0, }, ) func( {}, { xyz: 1, }, ) RUBY end include_examples 'corrects offenses without producing a double comma' end context 'and BracesAroundHashParameters style is `no_braces`' do let(:braces_around_hash_parameters_config) do { 'EnforcedStyle' => 'no_braces' } end let(:expected_corrected_source) do <<~RUBY # frozen_string_literal: true func( @abc => 0, @xyz => 1, ) func( abc: 0, ) func( {}, xyz: 1, ) RUBY end include_examples 'corrects offenses without producing a double comma' end context 'and BracesAroundHashParameters style is `context_dependent`' do let(:braces_around_hash_parameters_config) do { 'EnforcedStyle' => 'context_dependent' } end let(:expected_corrected_source) do <<~RUBY # frozen_string_literal: true func( @abc => 0, @xyz => 1, ) func( abc: 0, ) func( {}, { xyz: 1, }, ) RUBY end include_examples 'corrects offenses without producing a double comma' end end context 'when the style is `consistent_comma`' do let(:comma_style) do 'consistent_comma' end context 'and Style/BracesAroundHashParameters is disabled' do let(:braces_around_hash_parameters_config) do { 'Enabled' => false, 'AutoCorrect' => false, 'EnforcedStyle' => 'braces' } end let(:expected_corrected_source) do <<~RUBY # frozen_string_literal: true func({ @abc => 0, @xyz => 1, }) func( { abc: 0, }, ) func( {}, { xyz: 1, }, ) RUBY end include_examples 'corrects offenses without producing a double comma' end context 'and BracesAroundHashParameters style is `no_braces`' do let(:braces_around_hash_parameters_config) do { 'EnforcedStyle' => 'no_braces' } end let(:expected_corrected_source) do <<~RUBY # frozen_string_literal: true func( @abc => 0, @xyz => 1, ) func( abc: 0, ) func( {}, xyz: 1, ) RUBY end include_examples 'corrects offenses without producing a double comma' end context 'and BracesAroundHashParameters style is `context_dependent`' do let(:braces_around_hash_parameters_config) do { 'EnforcedStyle' => 'context_dependent' } end let(:expected_corrected_source) do <<~RUBY # frozen_string_literal: true func( @abc => 0, @xyz => 1, ) func( abc: 0, ) func( {}, { xyz: 1, }, ) RUBY end include_examples 'corrects offenses without producing a double comma' end end end context 'space_inside_bracket cops' do let(:source) do <<~RUBY [ a[b], c[ d ], [1, 2] ] foo[[ 3, 4 ], [5, 6] ] RUBY end let(:config) do { 'Layout/SpaceInsideArrayLiteralBrackets' => { 'EnforcedStyle' => array_style }, 'Layout/SpaceInsideReferenceBrackets' => { 'EnforcedStyle' => reference_style } } end before do create_file('example.rb', source) create_file('.rubocop.yml', YAML.dump(config)) end shared_examples 'corrects offenses' do it 'corrects SpaceInsideArrayLiteralBrackets and ' \ 'SpaceInsideReferenceBrackets' do cli.run(['--auto-correct']) expect(IO.read('example.rb')) .to eq(corrected_source) expect($stderr.string).to eq('') end end context 'when array style is space & reference style is no space' do let(:array_style) { 'space' } let(:reference_style) { 'no_space' } let(:corrected_source) do <<~RUBY # frozen_string_literal: true [ a[b], c[d], [ 1, 2 ] ] foo[[ 3, 4 ], [ 5, 6 ]] RUBY end include_examples 'corrects offenses' end context 'when array style is no_space & reference style is space' do let(:array_style) { 'no_space' } let(:reference_style) { 'space' } let(:corrected_source) do <<~RUBY # frozen_string_literal: true [a[ b ], c[ d ], [1, 2]] foo[ [3, 4], [5, 6] ] RUBY end include_examples 'corrects offenses' end context 'when array style is compact & reference style is no_space' do let(:array_style) { 'compact' } let(:reference_style) { 'no_space' } let(:corrected_source) do <<~RUBY # frozen_string_literal: true [ a[b], c[d], [ 1, 2 ]] foo[[ 3, 4 ], [ 5, 6 ]] RUBY end include_examples 'corrects offenses' end context 'when array style is compact & reference style is space' do let(:array_style) { 'compact' } let(:reference_style) { 'space' } let(:corrected_source) do <<~RUBY # frozen_string_literal: true [ a[ b ], c[ d ], [ 1, 2 ]] foo[ [ 3, 4 ], [ 5, 6 ] ] RUBY end include_examples 'corrects offenses' end end it 'corrects IndentationWidth, RedundantBegin, and ' \ 'RescueEnsureAlignment offenses' do source = <<~RUBY def verify_section begin scroll_down_until_element_exists rescue StandardError scroll_down_until_element_exists end end RUBY create_file('example.rb', source) expect(cli.run(['--auto-correct'])).to eq(0) corrected = <<~RUBY # frozen_string_literal: true def verify_section scroll_down_until_element_exists rescue StandardError scroll_down_until_element_exists end RUBY expect(IO.read('example.rb')).to eq(corrected) end it 'corrects LineEndConcatenation offenses leaving the ' \ 'UnneededInterpolation offense unchanged' do # If we change string concatenation from plus to backslash, the string # literal that follows must remain a string literal. source = <<-'RUBY'.strip_indent puts 'foo' + "#{bar}" puts 'a' + 'b' "#{c}" RUBY create_file('example.rb', source) expect(cli.run(['--auto-correct'])).to eq(0) corrected = ['# frozen_string_literal: true', '', "puts 'foo' \\", ' "#{bar}"', # Expressions that need correction from only one of these cops # are corrected as expected. "puts 'a' \\", " 'b'", 'c.to_s', ''].join("\n") expect(IO.read('example.rb')).to eq(corrected) end it 'corrects Style/InverseMethods and Style/Not offenses' do source = <<-'RUBY'.strip_indent x.select {|y| not y.z } RUBY create_file('example.rb', source) expect(cli.run([ '--auto-correct', '--only', 'Style/InverseMethods,Style/Not' ])).to eq(0) corrected = <<-'RUBY'.strip_indent x.reject {|y| y.z } RUBY expect(IO.read('example.rb')).to eq(corrected) end it 'corrects Style/Next and Style/SafeNavigation offenses' do create_file('.rubocop.yml', <<~YAML) AllCops: TargetRubyVersion: 2.3 YAML source = <<-'RUBY'.strip_indent until x if foo foo.some_method do y end end end RUBY create_file('example.rb', source) expect(cli.run([ '--auto-correct', '--only', 'Style/Next,Style/SafeNavigation' ])).to eq(0) corrected = <<-'RUBY'.strip_indent until x next unless foo foo.some_method do y end end RUBY expect(IO.read('example.rb')).to eq(corrected) end it 'corrects `Lint/Lambda` and `Lint/UnusedBlockArgument` offenses' do source = <<-'RUBY'.strip_indent c = -> event do puts 'Hello world' end RUBY create_file('example.rb', source) expect(cli.run([ '--auto-correct', '--only', 'Lint/Lambda,Lint/UnusedBlockArgument' ])).to eq(0) corrected = <<-'RUBY'.strip_indent c = lambda do |_event| puts 'Hello world' end RUBY expect(IO.read('example.rb')).to eq(corrected) end describe 'caching' do let(:cache) do instance_double(RuboCop::ResultCache, 'valid?' => true, 'load' => cached_offenses) end let(:source) { %(puts "Hi"\n) } before do allow(RuboCop::ResultCache).to receive(:new) { cache } create_file('example.rb', source) end context 'with no offenses in the cache' do let(:cached_offenses) { [] } it "doesn't correct offenses" do expect(cli.run(['--auto-correct'])).to eq(0) expect(IO.read('example.rb')).to eq(source) end end context 'with an offense in the cache' do let(:cached_offenses) { ['Style/StringLiterals: ...'] } it 'corrects offenses' do allow(cache).to receive(:save) expect(cli.run(['--auto-correct'])).to eq(0) expect(IO.read('example.rb')).to eq(<<~RUBY) # frozen_string_literal: true puts 'Hi' RUBY end end end %i[line_count_based semantic braces_for_chaining].each do |style| context "when BlockDelimiters has #{style} style" do it 'corrects SpaceBeforeBlockBraces, SpaceInsideBlockBraces offenses' do source = <<~RUBY r = foo.map{|a| a.bar.to_s } foo.map{|a| a.bar.to_s }.baz RUBY create_file('example.rb', source) create_file('.rubocop.yml', <<~YAML) Style/BlockDelimiters: EnforcedStyle: #{style} YAML expect(cli.run(['--auto-correct'])).to eq(1) corrected = case style when :semantic <<~RUBY # frozen_string_literal: true r = foo.map { |a| a.bar.to_s } foo.map { |a| a.bar.to_s }.baz RUBY when :braces_for_chaining <<~RUBY # frozen_string_literal: true r = foo.map do |a| a.bar.to_s end foo.map { |a| a.bar.to_s }.baz RUBY when :line_count_based <<~RUBY # frozen_string_literal: true r = foo.map do |a| a.bar.to_s end foo.map do |a| a.bar.to_s end.baz RUBY end expect($stderr.string).to eq('') expect(IO.read('example.rb')).to eq(corrected) end end end it 'corrects InitialIndentation offenses' do source = <<~RUBY # comment 1 # comment 2 def func begin foo bar rescue StandardError baz end end RUBY create_file('example.rb', source) create_file('.rubocop.yml', <<~YAML) Layout/DefEndAlignment: AutoCorrect: true YAML expect(cli.run(['--auto-correct'])).to eq(0) corrected = <<~RUBY # frozen_string_literal: true # comment 1 # comment 2 def func foo bar rescue StandardError baz end RUBY expect($stderr.string).to eq('') expect(IO.read('example.rb')).to eq(corrected) end it 'corrects UnneededCopDisableDirective offenses' do source = <<~RUBY class A # rubocop:disable Metrics/MethodLength def func x = foo # rubocop:disable Lint/UselessAssignment,Style/For # rubocop:disable all # rubocop:disable Style/ClassVars @@bar = "3" end end RUBY create_file('example.rb', source) expect(cli.run(%w[--auto-correct --format simple])).to eq(1) expect($stdout.string).to eq(<<~RESULT) == example.rb == C: 1: 1: [Corrected] Style/FrozenStringLiteralComment: Missing magic comment # frozen_string_literal: true. C: 3: 1: Style/Documentation: Missing top-level class documentation comment. W: 4: 3: [Corrected] Lint/UnneededCopDisableDirective: Unnecessary disabling of Metrics/MethodLength. W: 6: 54: [Corrected] Lint/UnneededCopDisableDirective: Unnecessary disabling of Style/For. W: 8: 5: [Corrected] Lint/UnneededCopDisableDirective: Unnecessary disabling of Style/ClassVars. 1 file inspected, 5 offenses detected, 4 offenses corrected RESULT corrected = <<~RUBY # frozen_string_literal: true class A def func x = foo # rubocop:disable Lint/UselessAssignment # rubocop:disable all @@bar = "3" end end RUBY expect($stderr.string).to eq('') expect(IO.read('example.rb')).to eq(corrected) end it 'corrects RedundantBegin offenses and fixes indentation etc' do source = <<~RUBY def func begin foo bar rescue baz end end def func; begin; x; y; rescue; z end end def method begin BlockA do |strategy| foo end BlockB do |portfolio| foo end rescue => e # some problem bar end end def method begin # comment 1 do_some_stuff rescue # comment 2 end # comment 3 end RUBY create_file('example.rb', source) expect(cli.run(['--auto-correct'])).to eq(1) corrected = <<~RUBY # frozen_string_literal: true def func foo bar rescue StandardError baz end def func x; y; rescue StandardError; z end def method BlockA do |_strategy| foo end BlockB do |_portfolio| foo end rescue StandardError => e # some problem bar end def method # comment 1 do_some_stuff rescue StandardError # comment 2 # comment 3 end RUBY expect(IO.read('example.rb')).to eq(corrected) end it 'corrects Tab and IndentationConsistency offenses' do source = <<~RUBY render_views describe 'GET index' do \t it 'returns http success' do \t end \tdescribe 'admin user' do before(:each) do \t end \tend end RUBY create_file('example.rb', source) expect(cli.run(['--auto-correct'])).to eq(0) corrected = <<~RUBY # frozen_string_literal: true render_views describe 'GET index' do it 'returns http success' do end describe 'admin user' do before(:each) do end end end RUBY expect(IO.read('example.rb')).to eq(corrected) end it 'corrects IndentationWidth and IndentationConsistency offenses' do source = <<~RUBY require 'spec_helper' describe ArticlesController do render_views describe "GET \'index\'" do it "returns http success" do end describe "admin user" do before(:each) do end end end end RUBY create_file('example.rb', source) expect(cli.run(['--auto-correct'])).to eq(0) corrected = <<~RUBY # frozen_string_literal: true require 'spec_helper' describe ArticlesController do render_views describe \"GET 'index'\" do it 'returns http success' do end describe 'admin user' do before(:each) do end end end end RUBY expect(IO.read('example.rb')).to eq(corrected) end it 'corrects SymbolProc and SpaceBeforeBlockBraces offenses' do source = ['foo.map{ |a| a.nil? }'] create_file('example.rb', source) expect(cli.run(['-D', '--auto-correct'])).to eq(0) corrected = "# frozen_string_literal: true\n\nfoo.map(&:nil?)\n" expect(IO.read('example.rb')).to eq(corrected) uncorrected = $stdout.string.split($RS).select do |line| line.include?('example.rb:') && !line.include?('[Corrected]') end expect(uncorrected.empty?).to be(true) # Hence exit code 0. end it 'corrects only IndentationWidth without crashing' do source = <<~RUBY foo = if bar something elsif baz other_thing else raise end RUBY create_file('example.rb', source) expect(cli.run(%w[--only IndentationWidth --auto-correct])).to eq(0) corrected = <<~RUBY foo = if bar something elsif baz other_thing else raise end RUBY expect(IO.read('example.rb')).to eq(corrected) end it 'corrects complicated cases conservatively' do # Two cops make corrections here; Style/BracesAroundHashParameters, and # Style/AlignHash. Because they make minimal corrections relating only # to their specific areas, and stay away from cleaning up extra # whitespace in the process, the combined changes don't interfere with # each other and the result is semantically the same as the starting # point. source = <<~RUBY expect(subject[:address]).to eq({ street1: '1 Market', street2: '#200', city: 'Some Town', state: 'CA', postal_code: '99999-1111' }) RUBY create_file('example.rb', source) expect(cli.run(['-D', '--auto-correct'])).to eq(0) corrected = <<~RUBY # frozen_string_literal: true expect(subject[:address]).to eq( street1: '1 Market', street2: '#200', city: 'Some Town', state: 'CA', postal_code: '99999-1111' ) RUBY expect(IO.read('example.rb')).to eq(corrected) end it 'honors Exclude settings in individual cops' do source = 'puts %x(ls)' create_file('example.rb', source) create_file('.rubocop.yml', <<~YAML) Style/CommandLiteral: Exclude: - example.rb Style/FrozenStringLiteralComment: Enabled: false YAML expect(cli.run(['--auto-correct'])).to eq(0) expect($stdout.string).to include('no offenses detected') expect(IO.read('example.rb')).to eq("#{source}\n") end it 'corrects code with indentation problems' do create_file('example.rb', <<~RUBY) module Bar class Goo def something first call do_other 'things' if other > 34 more_work end end end end module Foo class Bar stuff = [ { some: 'hash', }, { another: 'hash', with: 'more' }, ] end end RUBY expect(cli.run(['--auto-correct'])).to eq(1) expect(IO.read('example.rb')) .to eq(<<~RUBY) # frozen_string_literal: true module Bar class Goo def something first call do_other 'things' more_work if other > 34 end end end module Foo class Bar stuff = [ { some: 'hash' }, { another: 'hash', with: 'more' } ] end end RUBY end it 'can change block comments and indent them' do create_file('example.rb', <<~RUBY) module Foo class Bar =begin This is a nice long comment which spans a few lines =end def baz do_something end end end RUBY expect(cli.run(['--auto-correct'])).to eq(1) expect(IO.read('example.rb')) .to eq(<<~RUBY) # frozen_string_literal: true module Foo class Bar # This is a nice long # comment # which spans a few lines def baz do_something end end end RUBY end it 'can correct two problems with blocks' do # {} should be do..end and space is missing. create_file('example.rb', <<~RUBY) (1..10).each{ |i| puts i } RUBY expect(cli.run(['--auto-correct'])).to eq(0) expect(IO.read('example.rb')) .to eq(<<~RUBY) # frozen_string_literal: true (1..10).each do |i| puts i end RUBY end it 'can handle spaces when removing braces' do create_file('example.rb', ["assert_post_status_code 400, 's', {:type => 'bad'}"]) expect(cli.run(%w[--auto-correct --format emacs])).to eq(0) expect(IO.read('example.rb')) .to eq(<<~RUBY) # frozen_string_literal: true assert_post_status_code 400, 's', type: 'bad' RUBY e = abs('example.rb') # TODO: Don't report that a problem is corrected when it # actually went away due to another correction. expect($stdout.string).to eq(<<~RESULT) #{e}:1:1: C: [Corrected] Style/FrozenStringLiteralComment: Missing magic comment `# frozen_string_literal: true`. #{e}:1:35: C: [Corrected] Layout/SpaceInsideHashLiteralBraces: Space inside { missing. #{e}:1:35: C: [Corrected] Style/BracesAroundHashParameters: Redundant curly braces around a hash parameter. #{e}:1:36: C: [Corrected] Style/HashSyntax: Use the new Ruby 1.9 hash syntax. #{e}:1:50: C: [Corrected] Layout/SpaceInsideHashLiteralBraces: Space inside } missing. #{e}:3:35: C: [Corrected] Style/BracesAroundHashParameters: Redundant curly braces around a hash parameter. RESULT end # A case where two cops, EmptyLinesAroundBody and EmptyLines, try to # remove the same line in autocorrect. it 'can correct two empty lines at end of class body' do create_file('example.rb', <<~RUBY) class Test def f end end RUBY expect(cli.run(['--auto-correct'])).to eq(1) expect($stderr.string).to eq('') expect(IO.read('example.rb')).to eq(<<~RUBY) # frozen_string_literal: true class Test def f; end end RUBY end # A case where WordArray's correction can be clobbered by # AccessModifierIndentation's correction. it 'can correct indentation and another thing' do create_file('example.rb', <<~RUBY) class Dsl private A = ["git", "path",] end RUBY expect(cli.run(%w[--auto-correct --format emacs])).to eq(1) expect(IO.read('example.rb')).to eq(<<~RUBY) # frozen_string_literal: true class Dsl private A = %w[git path].freeze end RUBY e = abs('example.rb') expect($stdout.string).to eq(<<~RESULT) #{e}:1:1: C: [Corrected] Style/FrozenStringLiteralComment: Missing magic comment `# frozen_string_literal: true`. #{e}:2:1: C: [Corrected] Layout/AccessModifierIndentation: Indent access modifiers like `private`. #{e}:2:1: C: [Corrected] Layout/EmptyLinesAroundAccessModifier: Keep a blank line after `private`. #{e}:2:1: C: [Corrected] Layout/IndentationWidth: Use 2 (not 0) spaces for indentation. #{e}:3:1: C: Style/Documentation: Missing top-level class documentation comment. #{e}:3:7: C: [Corrected] Style/MutableConstant: Freeze mutable objects assigned to constants. #{e}:3:7: C: [Corrected] Style/WordArray: Use `%w` or `%W` for an array of words. #{e}:3:8: C: [Corrected] Style/StringLiterals: Prefer single-quoted strings when you don't need string interpolation or special symbols. #{e}:3:15: C: [Corrected] Style/StringLiterals: Prefer single-quoted strings when you don't need string interpolation or special symbols. #{e}:3:21: C: [Corrected] Style/TrailingCommaInArrayLiteral: Avoid comma after the last item of an array. #{e}:4:1: C: [Corrected] Layout/IndentationWidth: Use 2 (not 4) spaces for indentation. #{e}:4:3: W: Lint/UselessAccessModifier: Useless `private` access modifier. #{e}:4:5: C: [Corrected] Layout/AccessModifierIndentation: Indent access modifiers like `private`. #{e}:6:1: C: [Corrected] Layout/IndentationWidth: Use 2 (not 4) spaces for indentation. #{e}:6:3: C: [Corrected] Layout/IndentationConsistency: Inconsistent indentation detected. #{e}:6:5: C: [Corrected] Layout/IndentationConsistency: Inconsistent indentation detected. #{e}:6:7: C: [Corrected] Style/WordArray: Use `%w` or `%W` for an array of words. RESULT end # A case where the same cop could try to correct an offense twice in one # place. it 'can correct empty line inside special form of nested modules' do create_file('example.rb', <<~RUBY) module A module B end end RUBY expect(cli.run(['--auto-correct'])).to eq(1) expect(IO.read('example.rb')).to eq(<<~RUBY) # frozen_string_literal: true module A module B end end RUBY uncorrected = $stdout.string.split($RS).select do |line| line.include?('example.rb:') && !line.include?('[Corrected]') end expect(uncorrected.empty?).to be(false) # Hence exit code 1. end it 'can correct single line methods' do create_file('example.rb', <<~RUBY) def func1; do_something end # comment def func2() do_1; do_2; end RUBY expect(cli.run(%w[--auto-correct --format offenses])).to eq(0) expect(IO.read('example.rb')).to eq(<<~RUBY) # comment # frozen_string_literal: true def func1 do_something end def func2 do_1 do_2 end RUBY expect($stdout.string).to eq(<<~RESULT) 6 Layout/TrailingWhitespace 3 Style/Semicolon 2 Style/SingleLineMethods 1 Layout/EmptyLineBetweenDefs 1 Style/DefWithParentheses 1 Style/FrozenStringLiteralComment -- 14 Total RESULT end # In this example, the auto-correction (changing "fail" to "raise") # creates a new problem (alignment of parameters), which is also # corrected automatically. it 'can correct a problems and the problem it creates' do create_file('example.rb', <<~RUBY) fail NotImplementedError, 'Method should be overridden in child classes' RUBY expect(cli.run(['--auto-correct'])).to eq(0) expect(IO.read('example.rb')) .to eq(<<~RUBY) # frozen_string_literal: true raise NotImplementedError, 'Method should be overridden in child classes' RUBY expect($stdout.string).to eq(<<~RESULT) Inspecting 1 file C Offenses: example.rb:1:1: C: [Corrected] Style/FrozenStringLiteralComment: Missing magic comment # frozen_string_literal: true. fail NotImplementedError, ^ example.rb:1:1: C: [Corrected] Style/SignalException: Always use raise to signal exceptions. fail NotImplementedError, ^^^^ example.rb:4:6: C: [Corrected] Layout/AlignArguments: Align the arguments of a method call if they span more than one line. 'Method should be overridden in child classes' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1 file inspected, 3 offenses detected, 3 offenses corrected RESULT end # Thanks to repeated auto-correction, we can get rid of the trailing # spaces, and then the extra empty line. it 'can correct two problems in the same place' do create_file('example.rb', ['# Example class.', 'class Klass', ' ', ' def f; end', 'end']) expect(cli.run(['--auto-correct'])).to eq(0) expect(IO.read('example.rb')) .to eq(<<~RUBY) # frozen_string_literal: true # Example class. class Klass def f; end end RUBY expect($stderr.string).to eq('') expect($stdout.string).to eq(<<~RESULT) Inspecting 1 file C Offenses: example.rb:1:1: C: [Corrected] Style/FrozenStringLiteralComment: Missing magic comment # frozen_string_literal: true. # Example class. ^ example.rb:3:1: C: [Corrected] Layout/TrailingWhitespace: Trailing whitespace detected. example.rb:5:1: C: [Corrected] Layout/EmptyLinesAroundClassBody: Extra empty line detected at class body beginning. 1 file inspected, 3 offenses detected, 3 offenses corrected RESULT end it 'can correct MethodDefParentheses and other offense' do create_file('example.rb', <<~RUBY) def primes limit 1.upto(limit).select { |i| i.even? } end RUBY expect(cli.run(%w[-D --auto-correct])).to eq(0) expect($stderr.string).to eq('') expect(IO.read('example.rb')).to eq(<<~RUBY) # frozen_string_literal: true def primes(limit) 1.upto(limit).select(&:even?) end RUBY expect($stdout.string) .to eq(['Inspecting 1 file', 'C', '', 'Offenses:', '', 'example.rb:1:1: C: [Corrected] ' \ 'Style/FrozenStringLiteralComment: Missing magic comment ' \ '# frozen_string_literal: true.', 'def primes limit', '^', 'example.rb:1:12: C: [Corrected] ' \ 'Style/MethodDefParentheses: ' \ 'Use def with parentheses when there are parameters.', 'def primes limit', ' ^^^^^', 'example.rb:2:24: C: [Corrected] Style/SymbolProc: ' \ 'Pass &:even? as an argument to select instead of a block.', ' 1.upto(limit).select { |i| i.even? }', ' ^^^^^^^^^^^^^^^', '', '1 file inspected, 3 offenses detected, 3 offenses ' \ 'corrected', ''].join("\n")) end it 'can correct WordArray and SpaceAfterComma offenses' do create_file('example.rb', <<~RUBY) f(type: ['offline','offline_payment'], bar_colors: ['958c12','953579','ff5800','0085cc']) RUBY expect(cli.run(%w[-D --auto-correct --format o])).to eq(0) expect($stdout.string) .to eq(<<~RESULT) 4 Layout/SpaceAfterComma 4 Style/WordArray 1 Style/FrozenStringLiteralComment -- 9 Total RESULT expect(IO.read('example.rb')) .to eq(<<~RUBY) # frozen_string_literal: true f(type: %w[offline offline_payment], bar_colors: %w[958c12 953579 ff5800 0085cc]) RUBY end it 'can correct SpaceAfterComma and HashSyntax offenses' do create_file('example.rb', "I18n.t('description',:property_name => property.name)") expect(cli.run(%w[-D --auto-correct --format emacs])).to eq(0) expect($stdout.string) .to eq(["#{abs('example.rb')}:1:1: C: [Corrected] " \ 'Style/FrozenStringLiteralComment: Missing magic comment ' \ '`# frozen_string_literal: true`.', "#{abs('example.rb')}:1:21: C: [Corrected] " \ 'Layout/SpaceAfterComma: Space missing after comma.', "#{abs('example.rb')}:1:22: C: [Corrected] " \ 'Style/HashSyntax: Use the new Ruby 1.9 hash syntax.', ''].join("\n")) expect(IO.read('example.rb')).to eq(<<~RUBY) # frozen_string_literal: true I18n.t('description', property_name: property.name) RUBY end it 'can correct HashSyntax and SpaceAroundOperators offenses' do create_file('example.rb', '{ :b=>1 }') expect(cli.run(%w[-D --auto-correct --format emacs])).to eq(0) expect(IO.read('example.rb')).to eq(<<~RUBY) # frozen_string_literal: true { b: 1 } RUBY expect($stdout.string) .to eq(["#{abs('example.rb')}:1:1: C: [Corrected] " \ 'Style/FrozenStringLiteralComment: Missing magic comment ' \ '`# frozen_string_literal: true`.', "#{abs('example.rb')}:1:3: C: [Corrected] " \ 'Style/HashSyntax: Use the new Ruby 1.9 hash syntax.', "#{abs('example.rb')}:1:5: C: [Corrected] " \ 'Layout/SpaceAroundOperators: Surrounding space missing for ' \ 'operator `=>`.', "#{abs('example.rb')}:3:3: C: [Corrected] " \ 'Style/HashSyntax: Use the new Ruby 1.9 hash syntax.', ''].join("\n")) end it 'can correct HashSyntax when --only is used' do create_file('example.rb', '{ :b=>1 }') expect(cli.run(%w[--auto-correct -f emacs --only Style/HashSyntax])).to eq(0) expect($stderr.string).to eq('') expect(IO.read('example.rb')).to eq("{ b: 1 }\n") expect($stdout.string) .to eq("#{abs('example.rb')}:1:3: C: [Corrected] Style/HashSyntax: " \ "Use the new Ruby 1.9 hash syntax.\n") end it 'can correct TrailingBlankLines and TrailingWhitespace offenses' do create_file('example.rb', ['# frozen_string_literal: true', '', ' ', '', '']) expect(cli.run(%w[--auto-correct --format emacs])).to eq(0) expect(IO.read('example.rb')).to eq(<<~RUBY) # frozen_string_literal: true RUBY expect($stdout.string).to eq(<<~RESULT) #{abs('example.rb')}:2:1: C: [Corrected] Layout/TrailingBlankLines: 3 trailing blank lines detected. #{abs('example.rb')}:3:1: C: [Corrected] Layout/TrailingWhitespace: Trailing whitespace detected. RESULT end it 'can correct MethodCallWithoutArgsParentheses and EmptyLiteral offenses' do create_file('example.rb', 'Hash.new()') expect(cli.run(%w[--auto-correct --format emacs])).to eq(0) expect($stderr.string).to eq('') expect(IO.read('example.rb')).to eq(<<~RUBY) # frozen_string_literal: true {} RUBY expect($stdout.string).to eq(<<~RESULT) #{abs('example.rb')}:1:1: C: [Corrected] Style/EmptyLiteral: Use hash literal `{}` instead of `Hash.new`. #{abs('example.rb')}:1:1: C: [Corrected] Style/FrozenStringLiteralComment: Missing magic comment `# frozen_string_literal: true`. #{abs('example.rb')}:1:9: C: [Corrected] Style/MethodCallWithoutArgsParentheses: Do not use parentheses for method calls with no arguments. RESULT end it 'can correct IndentHash offenses with separator style' do create_file('example.rb', <<~RUBY) CONVERSION_CORRESPONDENCE = { match_for_should: :match, match_for_should_not: :match_when_negated, failure_message_for_should: :failure_message, failure_message_for_should_not: :failure_message_when } RUBY create_file('.rubocop.yml', <<~YAML) Layout/AlignHash: EnforcedColonStyle: separator YAML expect(cli.run(%w[--auto-correct])).to eq(0) expect(IO.read('example.rb')) .to eq(<<~RUBY) # frozen_string_literal: true CONVERSION_CORRESPONDENCE = { match_for_should: :match, match_for_should_not: :match_when_negated, failure_message_for_should: :failure_message, failure_message_for_should_not: :failure_message_when }.freeze RUBY end it 'does not say [Corrected] if correction was avoided' do src = <<~RUBY func a do b end Signal.trap('TERM') { system(cmd); exit } def self.some_method(foo, bar: 1) log.debug(foo) end RUBY corrected = <<~RUBY # frozen_string_literal: true func a do b end Signal.trap('TERM') { system(cmd); exit } def self.some_method(foo, bar: 1) log.debug(foo) end RUBY create_file('.rubocop.yml', <<~YAML) AllCops: TargetRubyVersion: 2.3 YAML create_file('example.rb', src) expect(cli.run(%w[-a -f simple])).to eq(1) expect($stderr.string).to eq('') expect(IO.read('example.rb')).to eq(corrected) expect($stdout.string).to eq(<<~RESULT) == example.rb == C: 1: 1: [Corrected] Style/FrozenStringLiteralComment: Missing magic comment # frozen_string_literal: true. C: 3: 8: Style/BlockDelimiters: Prefer {...} over do...end for single-line blocks. C: 4: 34: Style/Semicolon: Do not use semicolons to terminate expressions. W: 5: 27: Lint/UnusedMethodArgument: Unused method argument - bar. 1 file inspected, 4 offenses detected, 1 offense corrected RESULT end it 'does not hang SpaceAfterPunctuation and SpaceInsideParens' do create_file('example.rb', 'some_method(a, )') Timeout.timeout(10) do expect(cli.run(%w[--auto-correct])).to eq(0) end expect($stderr.string).to eq('') expect(IO.read('example.rb')).to eq(<<~RUBY) # frozen_string_literal: true some_method(a) RUBY end it 'does not hang SpaceAfterPunctuation and ' \ 'SpaceInsideArrayLiteralBrackets' do create_file('example.rb', 'puts [1, ]') Timeout.timeout(10) do expect(cli.run(%w[--auto-correct])).to eq(0) end expect($stderr.string).to eq('') expect(IO.read('example.rb')).to eq(<<~RUBY) # frozen_string_literal: true puts [1] RUBY end it 'can be disabled for any cop in configuration' do create_file('example.rb', 'puts "Hello", 123456') create_file('.rubocop.yml', <<~YAML) Style/StringLiterals: AutoCorrect: false YAML expect(cli.run(%w[--auto-correct])).to eq(1) expect($stderr.string).to eq('') expect(IO.read('example.rb')).to eq(<<~RUBY) # frozen_string_literal: true puts \"Hello\", 123_456 RUBY end it 'handles different SpaceInsideBlockBraces and ' \ 'SpaceInsideHashLiteralBraces' do create_file('example.rb', <<~RUBY) {foo: bar, bar: baz,} foo.each {bar;} RUBY create_file('.rubocop.yml', <<~YAML) Layout/SpaceInsideBlockBraces: EnforcedStyle: space Layout/SpaceInsideHashLiteralBraces: EnforcedStyle: no_space Style/TrailingCommaInHashLiteral: EnforcedStyleForMultiline: consistent_comma YAML expect(cli.run(%w[--auto-correct])).to eq(1) expect($stderr.string).to eq('') expect(IO.read('example.rb')).to eq(<<~RUBY) # frozen_string_literal: true {foo: bar, bar: baz,} foo.each { bar; } RUBY end it 'corrects BracesAroundHashParameters offenses leaving the ' \ 'MultilineHashBraceLayout offense unchanged' do create_file('example.rb', <<~RUBY) def method_a do_something({ a: 1, }) end RUBY expect($stderr.string).to eq('') expect(cli.run(%w[--auto-correct])).to eq(0) expect(IO.read('example.rb')).to eq(<<~RUBY) # frozen_string_literal: true def method_a do_something(a: 1) end RUBY end end
{ "content_hash": "4b1f277a1641ff8729a3b4850c28559d", "timestamp": "", "source": "github", "line_count": 1564, "max_line_length": 145, "avg_line_length": 28.515345268542198, "alnum_prop": 0.5399793712722544, "repo_name": "vergenzt/rubocop", "id": "e36ee082a12e2680829567c3baf88b4257720bc0", "size": "44629", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/rubocop/cli/cli_autocorrect_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "355" }, { "name": "HTML", "bytes": "7109" }, { "name": "Ruby", "bytes": "4815239" }, { "name": "Shell", "bytes": "75" } ], "symlink_target": "" }
package org.apache.camel.component.file.remote; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.Processor; import org.apache.camel.component.file.GenericFile; import org.apache.camel.component.file.GenericFileOperationFailedException; import org.apache.camel.component.file.GenericFileProcessStrategy; import org.apache.camel.component.file.GenericFileProducer; import org.apache.camel.impl.DefaultCamelContext; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; public class RemoteFileIgnoreDoPollErrorTest { private final CamelContext camelContext = new DefaultCamelContext(); private final RemoteFileEndpoint<Object> remoteFileEndpoint = new RemoteFileEndpoint<Object>() { @Override protected RemoteFileConsumer<Object> buildConsumer(Processor processor) { return null; } @Override protected GenericFileProducer<Object> buildProducer() { return null; } @Override public RemoteFileOperations<Object> createRemoteFileOperations() { return null; } @Override public String getScheme() { return null; } @Override protected GenericFileProcessStrategy<Object> createGenericFileStrategy() { return null; } }; @Test public void testReadDirErrorIsHandled() { RemoteFileConsumer<Object> consumer = getRemoteFileConsumer("true", true); boolean result = consumer.doSafePollSubDirectory("anyPath", "adir", new ArrayList<GenericFile<Object>>(), 0); assertTrue(result); } @Test public void testReadDirErrorIsHandledWithNoMorePoll() { RemoteFileConsumer<Object> consumer = getRemoteFileConsumer("false", true); boolean result = consumer.doSafePollSubDirectory("anyPath", "adir", new ArrayList<GenericFile<Object>>(), 0); assertFalse(result); } @Test public void testReadDirErrorNotHandled() { RemoteFileConsumer<Object> consumer = getRemoteFileConsumer("IllegalStateException", false); List<GenericFile<Object>> list = Collections.emptyList(); Exception ex = assertThrows(GenericFileOperationFailedException.class, () -> consumer.doSafePollSubDirectory("anyPath", "adir", list, 0)); assertTrue(ex.getCause() instanceof IllegalStateException); } @Test public void testReadDirErrorNotHandledForGenericFileOperationException() { RemoteFileConsumer<Object> consumer = getRemoteFileConsumer("GenericFileOperationFailedException", false); List<GenericFile<Object>> list = Collections.emptyList(); Exception ex = assertThrows(GenericFileOperationFailedException.class, () -> consumer.doSafePollSubDirectory("anyPath", "adir", list, 0)); assertNull(ex.getCause()); } private RemoteFileConsumer<Object> getRemoteFileConsumer( final String doPollResult, final boolean ignoreCannotRetrieveFile) { remoteFileEndpoint.setCamelContext(camelContext); return new RemoteFileConsumer<Object>(remoteFileEndpoint, null, null, null) { @Override protected boolean doPollDirectory( String absolutePath, String dirName, List<GenericFile<Object>> genericFiles, int depth) { if ("IllegalStateException".equals(doPollResult)) { throw new IllegalStateException("Problem"); } else if ("GenericFileOperationFailedException".equals(doPollResult)) { throw new GenericFileOperationFailedException("Perm error"); } else { return "true".equals(doPollResult); } } @Override protected boolean pollDirectory(String fileName, List<GenericFile<Object>> genericFiles, int depth) { return false; } @Override protected boolean isMatched(GenericFile<Object> file, String doneFileName, Object[] files) { return false; } @Override protected boolean ignoreCannotRetrieveFile(String name, Exchange exchange, Exception cause) { return ignoreCannotRetrieveFile; } @Override protected void updateFileHeaders(GenericFile<Object> genericFile, Message message) { // noop } }; } }
{ "content_hash": "aa41949035cce1da67c63d145a32da7b", "timestamp": "", "source": "github", "line_count": 130, "max_line_length": 117, "avg_line_length": 37.223076923076924, "alnum_prop": 0.6765860715023765, "repo_name": "adessaigne/camel", "id": "d19294a0c7195859d3e9026a2cd6f2879f708859", "size": "5641", "binary": false, "copies": "6", "ref": "refs/heads/main", "path": "components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/RemoteFileIgnoreDoPollErrorTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Apex", "bytes": "6695" }, { "name": "Batchfile", "bytes": "2353" }, { "name": "CSS", "bytes": "5472" }, { "name": "Dockerfile", "bytes": "5676" }, { "name": "Elm", "bytes": "10852" }, { "name": "FreeMarker", "bytes": "16123" }, { "name": "Groovy", "bytes": "383919" }, { "name": "HTML", "bytes": "209156" }, { "name": "Java", "bytes": "109812609" }, { "name": "JavaScript", "bytes": "103655" }, { "name": "Jsonnet", "bytes": "1734" }, { "name": "Kotlin", "bytes": "41869" }, { "name": "Mustache", "bytes": "525" }, { "name": "RobotFramework", "bytes": "8461" }, { "name": "Ruby", "bytes": "88" }, { "name": "Shell", "bytes": "19367" }, { "name": "Tcl", "bytes": "4974" }, { "name": "Thrift", "bytes": "6979" }, { "name": "XQuery", "bytes": "699" }, { "name": "XSLT", "bytes": "276597" } ], "symlink_target": "" }
(function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper `window` // is present, execute the factory and get jQuery. // For environments that do not have a `window` with a `document` // (such as Node.js), expose a factory as module.exports. // This accentuates the need for the creation of a real `window`. // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info. module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Support: Firefox 18+ // Can't be in strict mode, several libs including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // var arr = []; var slice = arr.slice; var concat = arr.concat; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var support = {}; var // Use the correct document accordingly with window argument (sandbox) document = window.document, version = "2.1.3", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Support: Android<4.1 // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num != null ? // Return just the one element from the set ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return all the elements in a clean array slice.call( this ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: arr.sort, splice: arr.splice }; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // Skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // Extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN // adding 1 corrects loss of precision from parseFloat (#15100) return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0; }, isPlainObject: function( obj ) { // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } if ( obj.constructor && !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } // If the function hasn't returned already, we're confident that // |obj| is a plain object, created by {} or constructed with new Object return true; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, type: function( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android<4.0, iOS<6 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; }, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // Convert dashed to camelCase; used by the css and data modules // Support: IE9-11+ // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Support: Android<4.1 trim: function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their new values if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: Date.now, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v2.2.0-pre * http://sizzlejs.com/ * * Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-12-16 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // General-purpose constants MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // http://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + characterEncoding + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; nodeType = context.nodeType; if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } if ( !seed && documentIsHTML ) { // Try to shortcut find operations when possible (e.g., not under DocumentFragment) if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document (jQuery #6963) if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType !== 1 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, parent, doc = node ? node.ownerDocument || node : preferredDoc; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; parent = doc.defaultView; // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent !== parent.top ) { // IE11 does not have attachEvent, so all must suffer if ( parent.addEventListener ) { parent.addEventListener( "unload", unloadHandler, false ); } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", unloadHandler ); } } /* Support tests ---------------------------------------------------------------------- */ documentIsHTML = !isXML( doc ); /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Support: IE<9 support.getElementsByClassName = rnative.test( doc.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [ m ] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\f]' msallowcapture=''>" + "<option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( div.querySelectorAll("[msallowcapture^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.2+, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.7+ if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push("~="); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibing-combinator selector` fails if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push(".#.+[+~]"); } }); assert(function( div ) { // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( div.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch (e) {} } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); // Don't keep the element (issue #299) input[0] = null; return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (oldCache = outerCache[ dir ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements outerCache[ dir ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context !== document && context; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is no seed and only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome 14-35+ // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) >= 0 ) !== not; }); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }; jQuery.fn.extend({ find: function( selector ) { var i, len = this.length, ret = [], self = this; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } }); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function( selector, context ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // Option to run scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Support: Blackberry 4.6 // gEBID returns nodes no longer in the document (#6963) if ( elem && elem.parentNode ) { // Inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return typeof rootjQuery.ready !== "undefined" ? rootjQuery.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // Methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.extend({ dir: function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } }); jQuery.fn.extend({ has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter(function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within the set index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // Index in selector if ( typeof elem === "string" ) { return indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { return this.pushStack( jQuery.unique( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); var rnotwhite = (/\S+/g); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // Add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // If we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }; jQuery.extend({ // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); jQuery( document ).off( "ready" ); } } }); /** * The ready event handler and self cleanup method */ function completed() { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); jQuery.ready(); } jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // We once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); } } return readyList.promise( obj ); }; // Kick off the DOM ready check even if the user does not jQuery.ready.promise(); // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < len; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : len ? fn( elems[0], key ) : emptyGet; }; /** * Determines whether an object can have data */ jQuery.acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any /* jshint -W018 */ return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { // Support: Android<4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty( this.cache = {}, 0, { get: function() { return {}; } }); this.expando = jQuery.expando + Data.uid++; } Data.uid = 1; Data.accepts = jQuery.acceptData; Data.prototype = { key: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if ( !Data.accepts( owner ) ) { return 0; } var descriptor = {}, // Check if the owner object already has a cache key unlock = owner[ this.expando ]; // If not, create one if ( !unlock ) { unlock = Data.uid++; // Secure it in a non-enumerable, non-writable property try { descriptor[ this.expando ] = { value: unlock }; Object.defineProperties( owner, descriptor ); // Support: Android<4 // Fallback to a less secure definition } catch ( e ) { descriptor[ this.expando ] = unlock; jQuery.extend( owner, descriptor ); } } // Ensure the cache object if ( !this.cache[ unlock ] ) { this.cache[ unlock ] = {}; } return unlock; }, set: function( owner, data, value ) { var prop, // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed unlock = this.key( owner ), cache = this.cache[ unlock ]; // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if ( jQuery.isEmptyObject( cache ) ) { jQuery.extend( this.cache[ unlock ], data ); // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } return cache; }, get: function( owner, key ) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[ this.key( owner ) ]; return key === undefined ? cache : cache[ key ]; }, access: function( owner, key, value ) { var stored; // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ((key && typeof key === "string") && value === undefined) ) { stored = this.get( owner, key ); return stored !== undefined ? stored : this.get( owner, jQuery.camelCase(key) ); } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, unlock = this.key( owner ), cache = this.cache[ unlock ]; if ( key === undefined ) { this.cache[ unlock ] = {}; } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } }, hasData: function( owner ) { return !jQuery.isEmptyObject( this.cache[ owner[ this.expando ] ] || {} ); }, discard: function( owner ) { if ( owner[ this.expando ] ) { delete this.cache[ owner[ this.expando ] ]; } } }; var data_priv = new Data(); var data_user = new Data(); // Implementation Summary // // 1. Enforce API surface and semantic compatibility with 1.9.x branch // 2. Improve the module's maintainability by reducing the storage // paths to a single mechanism. // 3. Use the same single mechanism to support "private" and "user" data. // 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) // 5. Avoid exposing implementation details on user objects (eg. expando properties) // 6. Provide a clear path for implementation upgrade to WeakMap in 2014 var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /([A-Z])/g; function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later data_user.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ hasData: function( elem ) { return data_user.hasData( elem ) || data_priv.hasData( elem ); }, data: function( elem, name, data ) { return data_user.access( elem, name, data ); }, removeData: function( elem, name ) { data_user.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to data_priv methods, these can be deprecated. _data: function( elem, name, data ) { return data_priv.access( elem, name, data ); }, _removeData: function( elem, name ) { data_priv.remove( elem, name ); } }); jQuery.fn.extend({ data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = data_user.get( elem ); if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE11+ // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } } data_priv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { data_user.set( this, key ); }); } return access( this, function( value ) { var data, camelKey = jQuery.camelCase( key ); // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = data_user.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to get data from the cache // with the key camelized data = data_user.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each(function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = data_user.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* data_user.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf("-") !== -1 && data !== undefined ) { data_user.set( this, key, value ); } }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { data_user.remove( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = data_priv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = data_priv.access( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // Clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // Not public - generate a queueHooks object, or return the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return data_priv.get( elem, key ) || data_priv.access( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { data_priv.remove( elem, [ type + "queue", key ] ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // Ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = data_priv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHidden = function( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); }; var rcheckableType = (/^(?:checkbox|radio)$/i); (function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ), input = document.createElement( "input" ); // Support: Safari<=5.1 // Check state lost if the name is set (#11217) // Support: Windows Web Apps (WWA) // `name` and `type` must use .setAttribute for WWA (#14901) input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); div.appendChild( input ); // Support: Safari<=5.1, Android<4.2 // Older WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<=11+ // Make sure textarea (and checkbox) defaultValue is properly cloned div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; })(); var strundefined = typeof undefined; support.focusinBubbles = "onfocusin" in window; var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.hasData( elem ) && data_priv.get( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; data_priv.remove( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && jQuery.acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = slice.call( arguments ), handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or 2) have namespace(s) // a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome<28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: Android<4.0 src.returnValue === false ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && e.stopImmediatePropagation ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // Support: Chrome 15+ jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // Support: Firefox, Chrome, Safari // Create "bubbling" focus and blur events if ( !support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = data_priv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } data_priv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = data_priv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); data_priv.remove( doc, fix ); } else { data_priv.access( doc, fix, attaches ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { // Support: IE9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Fix IE bugs, see support tests function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Fix IE cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit, PhantomJS // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: QtWebKit, PhantomJS // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Ensure the created nodes are orphaned (#12392) tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, type, key, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( jQuery.acceptData( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each(function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } }); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because push.apply(_, arraylike) throws push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); var iframe, elemdisplay = {}; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var style, elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), // getDefaultComputedStyle might be reliably used only on attached element display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? // Use of this method is a temporary fix (more like optimization) until something better comes along, // since it was removed from specification and supported only in FF style.display : jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = iframe[ 0 ].contentDocument; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } var rmargin = (/^margin/); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { // Support: IE<=11+, Firefox<=30+ (#15098, #14150) // IE throws on elements created in popups // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" if ( elem.ownerDocument.defaultView.opener ) { return elem.ownerDocument.defaultView.getComputedStyle( elem, null ); } return window.getComputedStyle( elem, null ); }; function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); // Support: IE9 // getPropertyValue is only needed for .css('filter') (#12537) if ( computed ) { ret = computed.getPropertyValue( name ) || computed[ name ]; } if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // Support: iOS < 6 // A tribute to the "awesome hack by Dean Edwards" // iOS < 6 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret !== undefined ? // Support: IE // IE returns zIndex value as an integer. ret + "" : ret; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { if ( conditionFn() ) { // Hook not needed (or it's not possible to use it due // to missing dependency), remove it. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return (this.get = hookFn).apply( this, arguments ); } }; } (function() { var pixelPositionVal, boxSizingReliableVal, docElem = document.documentElement, container = document.createElement( "div" ), div = document.createElement( "div" ); if ( !div.style ) { return; } // Support: IE9-11+ // Style of cloned element affects source element cloned (#8908) div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; container.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;" + "position:absolute"; container.appendChild( div ); // Executing both pixelPosition & boxSizingReliable tests require only one layout // so they're executed at the same time to save the second computation. function computePixelPositionAndBoxSizingReliable() { div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" + "box-sizing:border-box;display:block;margin-top:1%;top:1%;" + "border:1px;padding:1px;width:4px;position:absolute"; div.innerHTML = ""; docElem.appendChild( container ); var divStyle = window.getComputedStyle( div, null ); pixelPositionVal = divStyle.top !== "1%"; boxSizingReliableVal = divStyle.width === "4px"; docElem.removeChild( container ); } // Support: node.js jsdom // Don't assume that getComputedStyle is a property of the global object if ( window.getComputedStyle ) { jQuery.extend( support, { pixelPosition: function() { // This test is executed only once but we still do memoizing // since we can use the boxSizingReliable pre-computing. // No need to check if the test was already performed, though. computePixelPositionAndBoxSizingReliable(); return pixelPositionVal; }, boxSizingReliable: function() { if ( boxSizingReliableVal == null ) { computePixelPositionAndBoxSizingReliable(); } return boxSizingReliableVal; }, reliableMarginRight: function() { // Support: Android 2.3 // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // This support function is only executed once so no memoizing is needed. var ret, marginDiv = div.appendChild( document.createElement( "div" ) ); // Reset CSS: box-sizing; display; margin; border; padding marginDiv.style.cssText = div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" + "box-sizing:content-box;display:block;margin:0;border:0;padding:0"; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; docElem.appendChild( container ); ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight ); docElem.removeChild( container ); div.removeChild( marginDiv ); return ret; } }); } })(); // A method for quickly swapping in/out CSS properties to get correct calculations. jQuery.swap = function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; var // Swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ), rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ), cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }, cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // Return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // Shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // Check for vendor prefixed names var capName = name[0].toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // Both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // At this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // At this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // At this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // Some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // Check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // Use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = data_priv.get( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } else { hidden = isHidden( elem ); if ( display !== "none" || !hidden ) { data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { "float": "cssFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // Gets hook for the prefixed version, then unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // Convert "+=" or "-=" to relative numbers (#7345) if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set (#7116) if ( value == null || value !== value ) { return; } // If a number, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Support: IE9-11+ // background-* props affect original clone's values if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { style[ name ] = value; } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // Try prefixed name followed by the unprefixed name hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } // Convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Make numeric if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // Certain elements can have dimension info if we invisibly show them // but it must have a current display style that would benefit return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); // Support: Android 2.3 jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight, function( elem, computed ) { if ( computed ) { return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } ); // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // Assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); jQuery.fn.extend({ css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // Passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails. // Simple values such as "10px" are parsed to Float; // complex values such as "rotate(1rad)" are returned as-is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // Use step hook for back compat. // Use cssHook if its there. // Use .style if available and use plain properties where available. if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; } }; jQuery.fx = Tween.prototype.init; // Back Compat <1.8 extension point jQuery.fx.step = {}; var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something*. // Use string for doubling so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur(), // break the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; } ] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, i = 0, attrs = { height: type }; // If we include width, step value is 1 to do all cssExpand values, // otherwise step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // We're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = data_priv.get( elem, "fxshow" ); // Handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // Ensure the complete handler is called before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // Height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE9-10 do not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated display = jQuery.css( elem, "display" ); // Test default display if display is currently "none" checkDisplay = display === "none" ? data_priv.get( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display; if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) { style.display = "inline-block"; } } if ( opts.overflow ) { style.overflow = "hidden"; anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); // Any non-fx value stops us from restoring the original display value } else { display = undefined; } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = data_priv.access( elem, "fxshow", {} ); } // Store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; data_priv.remove( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } // If this is a noop like .hide().hide(), restore an overwritten display value } else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) { style.display = display; } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // Not quite $.extend, this won't overwrite existing keys. // Reusing 'index' because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // Don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // Support: Android 2.3 // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // If we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // Resolve when we played the last frame; otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // Normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // Show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // Animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || data_priv.get( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = data_priv.get( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // Start the next in the queue if the last step wasn't forced. // Timers currently will call their complete callbacks, which // will dequeue but only if they were gotoEnd. if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = data_priv.get( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // Enable finishing flag on private data data.finish = true; // Empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // Look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // Look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // Turn off finishing flag delete data.finish; }); } }); jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.timers = []; jQuery.fx.tick = function() { var timer, i = 0, timers = jQuery.timers; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); if ( timer() ) { jQuery.fx.start(); } else { jQuery.timers.pop(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }; (function() { var input = document.createElement( "input" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); input.type = "checkbox"; // Support: iOS<=5.1, Android<=4.2+ // Default value for a checkbox should be "on" support.checkOn = input.value !== ""; // Support: IE<=11+ // Must access selectedIndex to make default options select support.optSelected = opt.selected; // Support: Android<=2.3 // Options inside disabled selects are incorrectly marked as disabled select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<=11+ // An input loses its value after becoming a radio input = document.createElement( "input" ); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; })(); var nodeHook, boolHook, attrHandle = jQuery.expr.attrHandle; jQuery.fn.extend({ attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); } }); jQuery.extend({ attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false elem[ propName ] = false; } elem.removeAttribute( name ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && jQuery.nodeName( elem, "input" ) ) { var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = function( elem, name, isXML ) { var ret, handle; if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ name ]; attrHandle[ name ] = ret; ret = getter( elem, name, isXML ) != null ? name.toLowerCase() : null; attrHandle[ name ] = handle; } return ret; }; }); var rfocusable = /^(?:input|select|textarea|button)$/i; jQuery.fn.extend({ prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each(function() { delete this[ jQuery.propFix[ name ] || name ]; }); } }); jQuery.extend({ propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // Don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? elem.tabIndex : -1; } } } }); if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); var rclass = /[\t\r\n\f]/g; jQuery.fn.extend({ addClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, proceed = typeof value === "string" && value, i = 0, len = this.length; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, proceed = arguments.length === 0 || typeof value === "string" && value, i = 0, len = this.length; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // Only assign if different to avoid unneeded rendering. finalValue = value ? jQuery.trim( cur ) : ""; if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // Toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // Check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === strundefined || type === "boolean" ) { if ( this.className ) { // store className if set data_priv.set( this, "__className__", this.className ); } // If the element has a class name or if we're passed `false`, // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; } }); var rreturn = /\r/g; jQuery.fn.extend({ val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // Handle most common string cases ret.replace(rreturn, "") : // Handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : // Support: IE10-11+ // option.text throws exceptions (#14686, #14858) jQuery.trim( jQuery.text( elem ) ); } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // IE6-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( option.value, values ) >= 0) ) { optionSet = true; } } // Force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } } }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); // Return jQuery for attributes-only inclusion jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var nonce = jQuery.now(); var rquery = (/\?/); // Support: Android 2.3 // Workaround failure to string-cast null input jQuery.parseJSON = function( data ) { return JSON.parse( data + "" ); }; // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { tmp = new DOMParser(); xml = tmp.parseFromString( data, "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat( "*" ), // Document location ajaxLocation = window.location.href, // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ) .replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) fireGlobals = jQuery.event && s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + nonce++ ) : // Otherwise add one to the end cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // Aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // Extract error from statusText and normalize for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // Shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); jQuery._evalUrl = function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); }; jQuery.fn.extend({ wrapAll: function( html ) { var wrap; if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapAll( html.call(this, i) ); }); } if ( this[ 0 ] ) { // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map(function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function( i ) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0; }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function() { var type = this.type; // Use .is( ":disabled" ) so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); }) .map(function( i, elem ) { var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); jQuery.ajaxSettings.xhr = function() { try { return new XMLHttpRequest(); } catch( e ) {} }; var xhrId = 0, xhrCallbacks = {}, xhrSuccessStatus = { // file protocol always yields status code 0, assume 200 0: 200, // Support: IE9 // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, xhrSupported = jQuery.ajaxSettings.xhr(); // Support: IE9 // Open requests must be manually aborted on unload (#5280) // See https://support.microsoft.com/kb/2856746 for more info if ( window.attachEvent ) { window.attachEvent( "onunload", function() { for ( var key in xhrCallbacks ) { xhrCallbacks[ key ](); } }); } support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport(function( options ) { var callback; // Cross domain only allowed if supported through XMLHttpRequest if ( support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, xhr = options.xhr(), id = ++xhrId; xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { delete xhrCallbacks[ id ]; callback = xhr.onload = xhr.onerror = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { complete( // file: protocol always yields status 0; see #8605, #14207 xhr.status, xhr.statusText ); } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE9 // Accessing binary-data responseText throws an exception // (#11426) typeof xhr.responseText === "string" ? { text: xhr.responseText } : undefined, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); xhr.onerror = callback("error"); // Create the abort callback callback = xhrCallbacks[ id ] = callback("abort"); try { // Do send the request (this may raise an exception) xhr.send( options.hasContent && options.data || null ); } catch ( e ) { // #14683: Only rethrow if this hasn't been notified as an error yet if ( callback ) { throw e; } } }, abort: function() { if ( callback ) { callback(); } } }; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery("<script>").prop({ async: true, charset: s.scriptCharset, src: s.url }).on( "load error", callback = function( evt ) { script.remove(); callback = null; if ( evt ) { complete( evt.type === "error" ? 404 : 200, evt.type ); } } ); document.head.appendChild( script[ 0 ] ); }, abort: function() { if ( callback ) { callback(); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; // Keep a copy of the old load method var _load = jQuery.fn.load; /** * Load a url into a page */ jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = jQuery.trim( url.slice( off ) ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) { jQuery.fn[ type ] = function( fn ) { return this.on( type, fn ); }; }); jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; var docElem = window.document.documentElement; /** * Gets a window from an element */ function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView; } jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // Set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf("auto") > -1; // Need to be able to calculate position if either // top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ offset: function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, elem = this[ 0 ], box = { top: 0, left: 0 }, doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // Support: BlackBerry 5, iOS 3 (original iPhone) // If we don't have gBCR, just use 0,0 rather than error if ( typeof elem.getBoundingClientRect !== strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // Assume getBoundingClientRect is there when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : window.pageXOffset, top ? val : window.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); // Support: Safari<7+, Chrome<37+ // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // Blink bug: https://code.google.com/p/chromium/issues/detail?id=229280 // getComputedStyle returns percent when specified for top/left/bottom/right; // rather than make the css module depend on the offset module, just check for it here jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // If curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } ); }); // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // Margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], // whichever is greatest return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. // Note that for maximum portability, libraries that are not jQuery should // declare themselves as anonymous modules, and avoid setting a global if an // AMD loader is present. jQuery is a special case. For more information, see // https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; }); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in AMD // (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( typeof noGlobal === strundefined ) { window.jQuery = window.$ = jQuery; } return jQuery; })); /** * @preserve HTML5 Shiv 3.7.2 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed */ ;(function(window, document) { /*jshint evil:true */ /** version */ var version = '3.7.2'; /** Preset options */ var options = window.html5 || {}; /** Used to skip problem elements */ var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i; /** Not all elements can be cloned in IE **/ var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i; /** Detect whether the browser supports default html5 styles */ var supportsHtml5Styles; /** Name of the expando, to work with multiple documents or to re-shiv one document */ var expando = '_html5shiv'; /** The id for the the documents expando */ var expanID = 0; /** Cached data for each document */ var expandoData = {}; /** Detect whether the browser supports unknown elements */ var supportsUnknownElements; (function() { try { var a = document.createElement('a'); a.innerHTML = '<xyz></xyz>'; //if the hidden property is implemented we can assume, that the browser supports basic HTML5 Styles supportsHtml5Styles = ('hidden' in a); supportsUnknownElements = a.childNodes.length == 1 || (function() { // assign a false positive if unable to shiv (document.createElement)('a'); var frag = document.createDocumentFragment(); return ( typeof frag.cloneNode == 'undefined' || typeof frag.createDocumentFragment == 'undefined' || typeof frag.createElement == 'undefined' ); }()); } catch(e) { // assign a false positive if detection fails => unable to shiv supportsHtml5Styles = true; supportsUnknownElements = true; } }()); /*--------------------------------------------------------------------------*/ /** * Creates a style sheet with the given CSS text and adds it to the document. * @private * @param {Document} ownerDocument The document. * @param {String} cssText The CSS text. * @returns {StyleSheet} The style element. */ function addStyleSheet(ownerDocument, cssText) { var p = ownerDocument.createElement('p'), parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement; p.innerHTML = 'x<style>' + cssText + '</style>'; return parent.insertBefore(p.lastChild, parent.firstChild); } /** * Returns the value of `html5.elements` as an array. * @private * @returns {Array} An array of shived element node names. */ function getElements() { var elements = html5.elements; return typeof elements == 'string' ? elements.split(' ') : elements; } /** * Extends the built-in list of html5 elements * @memberOf html5 * @param {String|Array} newElements whitespace separated list or array of new element names to shiv * @param {Document} ownerDocument The context document. */ function addElements(newElements, ownerDocument) { var elements = html5.elements; if(typeof elements != 'string'){ elements = elements.join(' '); } if(typeof newElements != 'string'){ newElements = newElements.join(' '); } html5.elements = elements +' '+ newElements; shivDocument(ownerDocument); } /** * Returns the data associated to the given document * @private * @param {Document} ownerDocument The document. * @returns {Object} An object of data. */ function getExpandoData(ownerDocument) { var data = expandoData[ownerDocument[expando]]; if (!data) { data = {}; expanID++; ownerDocument[expando] = expanID; expandoData[expanID] = data; } return data; } /** * returns a shived element for the given nodeName and document * @memberOf html5 * @param {String} nodeName name of the element * @param {Document} ownerDocument The context document. * @returns {Object} The shived element. */ function createElement(nodeName, ownerDocument, data){ if (!ownerDocument) { ownerDocument = document; } if(supportsUnknownElements){ return ownerDocument.createElement(nodeName); } if (!data) { data = getExpandoData(ownerDocument); } var node; if (data.cache[nodeName]) { node = data.cache[nodeName].cloneNode(); } else if (saveClones.test(nodeName)) { node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode(); } else { node = data.createElem(nodeName); } // Avoid adding some elements to fragments in IE < 9 because // * Attributes like `name` or `type` cannot be set/changed once an element // is inserted into a document/fragment // * Link elements with `src` attributes that are inaccessible, as with // a 403 response, will cause the tab/window to crash // * Script elements appended to fragments will execute when their `src` // or `text` property is set return node.canHaveChildren && !reSkip.test(nodeName) && !node.tagUrn ? data.frag.appendChild(node) : node; } /** * returns a shived DocumentFragment for the given document * @memberOf html5 * @param {Document} ownerDocument The context document. * @returns {Object} The shived DocumentFragment. */ function createDocumentFragment(ownerDocument, data){ if (!ownerDocument) { ownerDocument = document; } if(supportsUnknownElements){ return ownerDocument.createDocumentFragment(); } data = data || getExpandoData(ownerDocument); var clone = data.frag.cloneNode(), i = 0, elems = getElements(), l = elems.length; for(;i<l;i++){ clone.createElement(elems[i]); } return clone; } /** * Shivs the `createElement` and `createDocumentFragment` methods of the document. * @private * @param {Document|DocumentFragment} ownerDocument The document. * @param {Object} data of the document. */ function shivMethods(ownerDocument, data) { if (!data.cache) { data.cache = {}; data.createElem = ownerDocument.createElement; data.createFrag = ownerDocument.createDocumentFragment; data.frag = data.createFrag(); } ownerDocument.createElement = function(nodeName) { //abort shiv if (!html5.shivMethods) { return data.createElem(nodeName); } return createElement(nodeName, ownerDocument, data); }; ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' + 'var n=f.cloneNode(),c=n.createElement;' + 'h.shivMethods&&(' + // unroll the `createElement` calls getElements().join().replace(/[\w\-:]+/g, function(nodeName) { data.createElem(nodeName); data.frag.createElement(nodeName); return 'c("' + nodeName + '")'; }) + ');return n}' )(html5, data.frag); } /*--------------------------------------------------------------------------*/ /** * Shivs the given document. * @memberOf html5 * @param {Document} ownerDocument The document to shiv. * @returns {Document} The shived document. */ function shivDocument(ownerDocument) { if (!ownerDocument) { ownerDocument = document; } var data = getExpandoData(ownerDocument); if (html5.shivCSS && !supportsHtml5Styles && !data.hasCSS) { data.hasCSS = !!addStyleSheet(ownerDocument, // corrects block display not defined in IE6/7/8/9 'article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}' + // adds styling not present in IE6/7/8/9 'mark{background:#FF0;color:#000}' + // hides non-rendered elements 'template{display:none}' ); } if (!supportsUnknownElements) { shivMethods(ownerDocument, data); } return ownerDocument; } /*--------------------------------------------------------------------------*/ /** * The `html5` object is exposed so that more elements can be shived and * existing shiving can be detected on iframes. * @type Object * @example * * // options can be changed before the script is included * html5 = { 'elements': 'mark section', 'shivCSS': false, 'shivMethods': false }; */ var html5 = { /** * An array or space separated string of node names of the elements to shiv. * @memberOf html5 * @type Array|String */ 'elements': options.elements || 'abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video', /** * current version of html5shiv */ 'version': version, /** * A flag to indicate that the HTML5 style sheet should be inserted. * @memberOf html5 * @type Boolean */ 'shivCSS': (options.shivCSS !== false), /** * Is equal to true if a browser supports creating unknown/HTML5 elements * @memberOf html5 * @type boolean */ 'supportsUnknownElements': supportsUnknownElements, /** * A flag to indicate that the document's `createElement` and `createDocumentFragment` * methods should be overwritten. * @memberOf html5 * @type Boolean */ 'shivMethods': (options.shivMethods !== false), /** * A string to describe the type of `html5` object ("default" or "default print"). * @memberOf html5 * @type String */ 'type': 'default', // shivs the document according to the specified `html5` object options 'shivDocument': shivDocument, //creates a shived element createElement: createElement, //creates a shived documentFragment createDocumentFragment: createDocumentFragment, //extends list of elements addElements: addElements }; /*--------------------------------------------------------------------------*/ // expose html5 window.html5 = html5; // shiv the document shivDocument(document); }(this, document)); /*! Colorbox v1.4.37 - 2014-02-11 jQuery lightbox and modal window plugin (c) 2014 Jack Moore - http://www.jacklmoore.com/colorbox license: http://www.opensource.org/licenses/mit-license.php */ (function ($, document, window) { var // Default settings object. // See http://jacklmoore.com/colorbox for details. defaults = { // data sources html: false, photo: false, iframe: false, inline: false, // behavior and appearance transition: "elastic", speed: 300, fadeOut: 300, width: false, initialWidth: "600", innerWidth: false, maxWidth: false, height: false, initialHeight: "450", innerHeight: false, maxHeight: false, scalePhotos: true, scrolling: true, href: false, title: false, rel: false, opacity: 0.9, preloading: true, className: false, overlayClose: true, escKey: true, arrowKey: true, top: false, bottom: false, left: false, right: false, fixed: false, data: undefined, closeButton: true, fastIframe: true, open: false, reposition: true, loop: true, slideshow: false, slideshowAuto: true, slideshowSpeed: 2500, slideshowStart: "start slideshow", slideshowStop: "stop slideshow", photoRegex: /\.(gif|png|jp(e|g|eg)|bmp|ico|webp|jxr)((#|\?).*)?$/i, // alternate image paths for high-res displays retinaImage: false, retinaUrl: false, retinaSuffix: '@2x.$1', // internationalization current: "image {current} of {total}", previous: "previous", next: "next", close: "close", xhrError: "This content failed to load.", imgError: "This image failed to load.", // accessbility returnFocus: true, trapFocus: true, // callbacks onOpen: false, onLoad: false, onComplete: false, onCleanup: false, onClosed: false }, // Abstracting the HTML and event identifiers for easy rebranding colorbox = 'colorbox', prefix = 'cbox', boxElement = prefix + 'Element', // Events event_open = prefix + '_open', event_load = prefix + '_load', event_complete = prefix + '_complete', event_cleanup = prefix + '_cleanup', event_closed = prefix + '_closed', event_purge = prefix + '_purge', // Cached jQuery Object Variables $overlay, $box, $wrap, $content, $topBorder, $leftBorder, $rightBorder, $bottomBorder, $related, $window, $loaded, $loadingBay, $loadingOverlay, $title, $current, $slideshow, $next, $prev, $close, $groupControls, $events = $('<a/>'), // $([]) would be prefered, but there is an issue with jQuery 1.4.2 // Variables for cached values or use across multiple functions settings, interfaceHeight, interfaceWidth, loadedHeight, loadedWidth, element, index, photo, open, active, closing, loadingTimer, publicMethod, div = "div", className, requests = 0, previousCSS = {}, init; // **************** // HELPER FUNCTIONS // **************** // Convenience function for creating new jQuery objects function $tag(tag, id, css) { var element = document.createElement(tag); if (id) { element.id = prefix + id; } if (css) { element.style.cssText = css; } return $(element); } // Get the window height using innerHeight when available to avoid an issue with iOS // http://bugs.jquery.com/ticket/6724 function winheight() { return window.innerHeight ? window.innerHeight : $(window).height(); } // Determine the next and previous members in a group. function getIndex(increment) { var max = $related.length, newIndex = (index + increment) % max; return (newIndex < 0) ? max + newIndex : newIndex; } // Convert '%' and 'px' values to integers function setSize(size, dimension) { return Math.round((/%/.test(size) ? ((dimension === 'x' ? $window.width() : winheight()) / 100) : 1) * parseInt(size, 10)); } // Checks an href to see if it is a photo. // There is a force photo option (photo: true) for hrefs that cannot be matched by the regex. function isImage(settings, url) { return settings.photo || settings.photoRegex.test(url); } function retinaUrl(settings, url) { return settings.retinaUrl && window.devicePixelRatio > 1 ? url.replace(settings.photoRegex, settings.retinaSuffix) : url; } function trapFocus(e) { if ('contains' in $box[0] && !$box[0].contains(e.target)) { e.stopPropagation(); $box.focus(); } } // Assigns function results to their respective properties function makeSettings() { var i, data = $.data(element, colorbox); if (data == null) { settings = $.extend({}, defaults); if (console && console.log) { console.log('Error: cboxElement missing settings object'); } } else { settings = $.extend({}, data); } for (i in settings) { if ($.isFunction(settings[i]) && i.slice(0, 2) !== 'on') { // checks to make sure the function isn't one of the callbacks, they will be handled at the appropriate time. settings[i] = settings[i].call(element); } } settings.rel = settings.rel || element.rel || $(element).data('rel') || 'nofollow'; settings.href = settings.href || $(element).attr('href'); settings.title = settings.title || element.title; if (typeof settings.href === "string") { settings.href = $.trim(settings.href); } } function trigger(event, callback) { // for external use $(document).trigger(event); // for internal use $events.triggerHandler(event); if ($.isFunction(callback)) { callback.call(element); } } var slideshow = (function(){ var active, className = prefix + "Slideshow_", click = "click." + prefix, timeOut; function clear () { clearTimeout(timeOut); } function set() { if (settings.loop || $related[index + 1]) { clear(); timeOut = setTimeout(publicMethod.next, settings.slideshowSpeed); } } function start() { $slideshow .html(settings.slideshowStop) .unbind(click) .one(click, stop); $events .bind(event_complete, set) .bind(event_load, clear); $box.removeClass(className + "off").addClass(className + "on"); } function stop() { clear(); $events .unbind(event_complete, set) .unbind(event_load, clear); $slideshow .html(settings.slideshowStart) .unbind(click) .one(click, function () { publicMethod.next(); start(); }); $box.removeClass(className + "on").addClass(className + "off"); } function reset() { active = false; $slideshow.hide(); clear(); $events .unbind(event_complete, set) .unbind(event_load, clear); $box.removeClass(className + "off " + className + "on"); } return function(){ if (active) { if (!settings.slideshow) { $events.unbind(event_cleanup, reset); reset(); } } else { if (settings.slideshow && $related[1]) { active = true; $events.one(event_cleanup, reset); if (settings.slideshowAuto) { start(); } else { stop(); } $slideshow.show(); } } }; }()); function launch(target) { if (!closing) { element = target; makeSettings(); $related = $(element); index = 0; if (settings.rel !== 'nofollow') { $related = $('.' + boxElement).filter(function () { var data = $.data(this, colorbox), relRelated; if (data) { relRelated = $(this).data('rel') || data.rel || this.rel; } return (relRelated === settings.rel); }); index = $related.index(element); // Check direct calls to Colorbox. if (index === -1) { $related = $related.add(element); index = $related.length - 1; } } $overlay.css({ opacity: parseFloat(settings.opacity), cursor: settings.overlayClose ? "pointer" : "auto", visibility: 'visible' }).show(); if (className) { $box.add($overlay).removeClass(className); } if (settings.className) { $box.add($overlay).addClass(settings.className); } className = settings.className; if (settings.closeButton) { $close.html(settings.close).appendTo($content); } else { $close.appendTo('<div/>'); } if (!open) { open = active = true; // Prevents the page-change action from queuing up if the visitor holds down the left or right keys. // Show colorbox so the sizes can be calculated in older versions of jQuery $box.css({visibility:'hidden', display:'block'}); $loaded = $tag(div, 'LoadedContent', 'width:0; height:0; overflow:hidden'); $content.css({width:'', height:''}).append($loaded); // Cache values needed for size calculations interfaceHeight = $topBorder.height() + $bottomBorder.height() + $content.outerHeight(true) - $content.height(); interfaceWidth = $leftBorder.width() + $rightBorder.width() + $content.outerWidth(true) - $content.width(); loadedHeight = $loaded.outerHeight(true); loadedWidth = $loaded.outerWidth(true); // Opens inital empty Colorbox prior to content being loaded. settings.w = setSize(settings.initialWidth, 'x'); settings.h = setSize(settings.initialHeight, 'y'); $loaded.css({width:'', height:settings.h}); publicMethod.position(); trigger(event_open, settings.onOpen); $groupControls.add($title).hide(); $box.focus(); if (settings.trapFocus) { // Confine focus to the modal // Uses event capturing that is not supported in IE8- if (document.addEventListener) { document.addEventListener('focus', trapFocus, true); $events.one(event_closed, function () { document.removeEventListener('focus', trapFocus, true); }); } } // Return focus on closing if (settings.returnFocus) { $events.one(event_closed, function () { $(element).focus(); }); } } load(); } } // Colorbox's markup needs to be added to the DOM prior to being called // so that the browser will go ahead and load the CSS background images. function appendHTML() { if (!$box && document.body) { init = false; $window = $(window); $box = $tag(div).attr({ id: colorbox, 'class': $.support.opacity === false ? prefix + 'IE' : '', // class for optional IE8 & lower targeted CSS. role: 'dialog', tabindex: '-1' }).hide(); $overlay = $tag(div, "Overlay").hide(); $loadingOverlay = $([$tag(div, "LoadingOverlay")[0],$tag(div, "LoadingGraphic")[0]]); $wrap = $tag(div, "Wrapper"); $content = $tag(div, "Content").append( $title = $tag(div, "Title"), $current = $tag(div, "Current"), $prev = $('<button type="button"/>').attr({id:prefix+'Previous'}), $next = $('<button type="button"/>').attr({id:prefix+'Next'}), $slideshow = $tag('button', "Slideshow"), $loadingOverlay ); $close = $('<button type="button"/>').attr({id:prefix+'Close'}); $wrap.append( // The 3x3 Grid that makes up Colorbox $tag(div).append( $tag(div, "TopLeft"), $topBorder = $tag(div, "TopCenter"), $tag(div, "TopRight") ), $tag(div, false, 'clear:left').append( $leftBorder = $tag(div, "MiddleLeft"), $content, $rightBorder = $tag(div, "MiddleRight") ), $tag(div, false, 'clear:left').append( $tag(div, "BottomLeft"), $bottomBorder = $tag(div, "BottomCenter"), $tag(div, "BottomRight") ) ).find('div div').css({'float': 'left'}); $loadingBay = $tag(div, false, 'position:absolute; width:9999px; visibility:hidden; display:none; max-width:none;'); $groupControls = $next.add($prev).add($current).add($slideshow); $(document.body).append($overlay, $box.append($wrap, $loadingBay)); } } // Add Colorbox's event bindings function addBindings() { function clickHandler(e) { // ignore non-left-mouse-clicks and clicks modified with ctrl / command, shift, or alt. // See: http://jacklmoore.com/notes/click-events/ if (!(e.which > 1 || e.shiftKey || e.altKey || e.metaKey || e.ctrlKey)) { e.preventDefault(); launch(this); } } if ($box) { if (!init) { init = true; // Anonymous functions here keep the public method from being cached, thereby allowing them to be redefined on the fly. $next.click(function () { publicMethod.next(); }); $prev.click(function () { publicMethod.prev(); }); $close.click(function () { publicMethod.close(); }); $overlay.click(function () { if (settings.overlayClose) { publicMethod.close(); } }); // Key Bindings $(document).bind('keydown.' + prefix, function (e) { var key = e.keyCode; if (open && settings.escKey && key === 27) { e.preventDefault(); publicMethod.close(); } if (open && settings.arrowKey && $related[1] && !e.altKey) { if (key === 37) { e.preventDefault(); $prev.click(); } else if (key === 39) { e.preventDefault(); $next.click(); } } }); if ($.isFunction($.fn.on)) { // For jQuery 1.7+ $(document).on('click.'+prefix, '.'+boxElement, clickHandler); } else { // For jQuery 1.3.x -> 1.6.x // This code is never reached in jQuery 1.9, so do not contact me about 'live' being removed. // This is not here for jQuery 1.9, it's here for legacy users. $('.'+boxElement).live('click.'+prefix, clickHandler); } } return true; } return false; } // Don't do anything if Colorbox already exists. if ($.colorbox) { return; } // Append the HTML when the DOM loads $(appendHTML); // **************** // PUBLIC FUNCTIONS // Usage format: $.colorbox.close(); // Usage from within an iframe: parent.jQuery.colorbox.close(); // **************** publicMethod = $.fn[colorbox] = $[colorbox] = function (options, callback) { var $this = this; options = options || {}; appendHTML(); if (addBindings()) { if ($.isFunction($this)) { // assume a call to $.colorbox $this = $('<a/>'); options.open = true; } else if (!$this[0]) { // colorbox being applied to empty collection return $this; } if (callback) { options.onComplete = callback; } $this.each(function () { $.data(this, colorbox, $.extend({}, $.data(this, colorbox) || defaults, options)); }).addClass(boxElement); if (($.isFunction(options.open) && options.open.call($this)) || options.open) { launch($this[0]); } } return $this; }; publicMethod.position = function (speed, loadedCallback) { var css, top = 0, left = 0, offset = $box.offset(), scrollTop, scrollLeft; $window.unbind('resize.' + prefix); // remove the modal so that it doesn't influence the document width/height $box.css({top: -9e4, left: -9e4}); scrollTop = $window.scrollTop(); scrollLeft = $window.scrollLeft(); if (settings.fixed) { offset.top -= scrollTop; offset.left -= scrollLeft; $box.css({position: 'fixed'}); } else { top = scrollTop; left = scrollLeft; $box.css({position: 'absolute'}); } // keeps the top and left positions within the browser's viewport. if (settings.right !== false) { left += Math.max($window.width() - settings.w - loadedWidth - interfaceWidth - setSize(settings.right, 'x'), 0); } else if (settings.left !== false) { left += setSize(settings.left, 'x'); } else { left += Math.round(Math.max($window.width() - settings.w - loadedWidth - interfaceWidth, 0) / 2); } if (settings.bottom !== false) { top += Math.max(winheight() - settings.h - loadedHeight - interfaceHeight - setSize(settings.bottom, 'y'), 0); } else if (settings.top !== false) { top += setSize(settings.top, 'y'); } else { top += Math.round(Math.max(winheight() - settings.h - loadedHeight - interfaceHeight, 0) / 2); } $box.css({top: offset.top, left: offset.left, visibility:'visible'}); // this gives the wrapper plenty of breathing room so it's floated contents can move around smoothly, // but it has to be shrank down around the size of div#colorbox when it's done. If not, // it can invoke an obscure IE bug when using iframes. $wrap[0].style.width = $wrap[0].style.height = "9999px"; function modalDimensions() { $topBorder[0].style.width = $bottomBorder[0].style.width = $content[0].style.width = (parseInt($box[0].style.width,10) - interfaceWidth)+'px'; $content[0].style.height = $leftBorder[0].style.height = $rightBorder[0].style.height = (parseInt($box[0].style.height,10) - interfaceHeight)+'px'; } css = {width: settings.w + loadedWidth + interfaceWidth, height: settings.h + loadedHeight + interfaceHeight, top: top, left: left}; // setting the speed to 0 if the content hasn't changed size or position if (speed) { var tempSpeed = 0; $.each(css, function(i){ if (css[i] !== previousCSS[i]) { tempSpeed = speed; return; } }); speed = tempSpeed; } previousCSS = css; if (!speed) { $box.css(css); } $box.dequeue().animate(css, { duration: speed || 0, complete: function () { modalDimensions(); active = false; // shrink the wrapper down to exactly the size of colorbox to avoid a bug in IE's iframe implementation. $wrap[0].style.width = (settings.w + loadedWidth + interfaceWidth) + "px"; $wrap[0].style.height = (settings.h + loadedHeight + interfaceHeight) + "px"; if (settings.reposition) { setTimeout(function () { // small delay before binding onresize due to an IE8 bug. $window.bind('resize.' + prefix, function(){ publicMethod.position(); }); }, 1); } if ($.isFunction(loadedCallback)) { loadedCallback(); } }, step: modalDimensions }); }; publicMethod.resize = function (options) { var scrolltop; if (open) { options = options || {}; if (options.width) { settings.w = setSize(options.width, 'x') - loadedWidth - interfaceWidth; } if (options.innerWidth) { settings.w = setSize(options.innerWidth, 'x'); } $loaded.css({width: settings.w}); if (options.height) { settings.h = setSize(options.height, 'y') - loadedHeight - interfaceHeight; } if (options.innerHeight) { settings.h = setSize(options.innerHeight, 'y'); } if (!options.innerHeight && !options.height) { scrolltop = $loaded.scrollTop(); $loaded.css({height: "auto"}); settings.h = $loaded.height(); } $loaded.css({height: settings.h}); if(scrolltop) { $loaded.scrollTop(scrolltop); } publicMethod.position(settings.transition === "none" ? 0 : settings.speed); } }; publicMethod.prep = function (object) { if (!open) { return; } var callback, speed = settings.transition === "none" ? 0 : settings.speed; $loaded.empty().remove(); // Using empty first may prevent some IE7 issues. $loaded = $tag(div, 'LoadedContent').append(object); function getWidth() { settings.w = settings.w || $loaded.width(); settings.w = settings.mw && settings.mw < settings.w ? settings.mw : settings.w; return settings.w; } function getHeight() { settings.h = settings.h || $loaded.height(); settings.h = settings.mh && settings.mh < settings.h ? settings.mh : settings.h; return settings.h; } $loaded.hide() .appendTo($loadingBay.show())// content has to be appended to the DOM for accurate size calculations. .css({width: getWidth(), overflow: settings.scrolling ? 'auto' : 'hidden'}) .css({height: getHeight()})// sets the height independently from the width in case the new width influences the value of height. .prependTo($content); $loadingBay.hide(); // floating the IMG removes the bottom line-height and fixed a problem where IE miscalculates the width of the parent element as 100% of the document width. $(photo).css({'float': 'none'}); callback = function () { var total = $related.length, iframe, frameBorder = 'frameBorder', allowTransparency = 'allowTransparency', complete; if (!open) { return; } function removeFilter() { // Needed for IE7 & IE8 in versions of jQuery prior to 1.7.2 if ($.support.opacity === false) { $box[0].style.removeAttribute('filter'); } } complete = function () { clearTimeout(loadingTimer); $loadingOverlay.hide(); trigger(event_complete, settings.onComplete); }; $title.html(settings.title).add($loaded).show(); if (total > 1) { // handle grouping if (typeof settings.current === "string") { $current.html(settings.current.replace('{current}', index + 1).replace('{total}', total)).show(); } $next[(settings.loop || index < total - 1) ? "show" : "hide"]().html(settings.next); $prev[(settings.loop || index) ? "show" : "hide"]().html(settings.previous); slideshow(); // Preloads images within a rel group if (settings.preloading) { $.each([getIndex(-1), getIndex(1)], function(){ var src, img, i = $related[this], data = $.data(i, colorbox); if (data && data.href) { src = data.href; if ($.isFunction(src)) { src = src.call(i); } } else { src = $(i).attr('href'); } if (src && isImage(data, src)) { src = retinaUrl(data, src); img = document.createElement('img'); img.src = src; } }); } } else { $groupControls.hide(); } if (settings.iframe) { iframe = $tag('iframe')[0]; if (frameBorder in iframe) { iframe[frameBorder] = 0; } if (allowTransparency in iframe) { iframe[allowTransparency] = "true"; } if (!settings.scrolling) { iframe.scrolling = "no"; } $(iframe) .attr({ src: settings.href, name: (new Date()).getTime(), // give the iframe a unique name to prevent caching 'class': prefix + 'Iframe', allowFullScreen : true, // allow HTML5 video to go fullscreen webkitAllowFullScreen : true, mozallowfullscreen : true }) .one('load', complete) .appendTo($loaded); $events.one(event_purge, function () { iframe.src = "//about:blank"; }); if (settings.fastIframe) { $(iframe).trigger('load'); } } else { complete(); } if (settings.transition === 'fade') { $box.fadeTo(speed, 1, removeFilter); } else { removeFilter(); } }; if (settings.transition === 'fade') { $box.fadeTo(speed, 0, function () { publicMethod.position(0, callback); }); } else { publicMethod.position(speed, callback); } }; function load () { var href, setResize, prep = publicMethod.prep, $inline, request = ++requests; active = true; photo = false; element = $related[index]; makeSettings(); trigger(event_purge); trigger(event_load, settings.onLoad); settings.h = settings.height ? setSize(settings.height, 'y') - loadedHeight - interfaceHeight : settings.innerHeight && setSize(settings.innerHeight, 'y'); settings.w = settings.width ? setSize(settings.width, 'x') - loadedWidth - interfaceWidth : settings.innerWidth && setSize(settings.innerWidth, 'x'); // Sets the minimum dimensions for use in image scaling settings.mw = settings.w; settings.mh = settings.h; // Re-evaluate the minimum width and height based on maxWidth and maxHeight values. // If the width or height exceed the maxWidth or maxHeight, use the maximum values instead. if (settings.maxWidth) { settings.mw = setSize(settings.maxWidth, 'x') - loadedWidth - interfaceWidth; settings.mw = settings.w && settings.w < settings.mw ? settings.w : settings.mw; } if (settings.maxHeight) { settings.mh = setSize(settings.maxHeight, 'y') - loadedHeight - interfaceHeight; settings.mh = settings.h && settings.h < settings.mh ? settings.h : settings.mh; } href = settings.href; loadingTimer = setTimeout(function () { $loadingOverlay.show(); }, 100); if (settings.inline) { // Inserts an empty placeholder where inline content is being pulled from. // An event is bound to put inline content back when Colorbox closes or loads new content. $inline = $tag(div).hide().insertBefore($(href)[0]); $events.one(event_purge, function () { $inline.replaceWith($loaded.children()); }); prep($(href)); } else if (settings.iframe) { // IFrame element won't be added to the DOM until it is ready to be displayed, // to avoid problems with DOM-ready JS that might be trying to run in that iframe. prep(" "); } else if (settings.html) { prep(settings.html); } else if (isImage(settings, href)) { href = retinaUrl(settings, href); photo = document.createElement('img'); $(photo) .addClass(prefix + 'Photo') .bind('error',function () { settings.title = false; prep($tag(div, 'Error').html(settings.imgError)); }) .one('load', function () { var percent; if (request !== requests) { return; } $.each(['alt', 'longdesc', 'aria-describedby'], function(i,val){ var attr = $(element).attr(val) || $(element).attr('data-'+val); if (attr) { photo.setAttribute(val, attr); } }); if (settings.retinaImage && window.devicePixelRatio > 1) { photo.height = photo.height / window.devicePixelRatio; photo.width = photo.width / window.devicePixelRatio; } if (settings.scalePhotos) { setResize = function () { photo.height -= photo.height * percent; photo.width -= photo.width * percent; }; if (settings.mw && photo.width > settings.mw) { percent = (photo.width - settings.mw) / photo.width; setResize(); } if (settings.mh && photo.height > settings.mh) { percent = (photo.height - settings.mh) / photo.height; setResize(); } } if (settings.h) { photo.style.marginTop = Math.max(settings.mh - photo.height, 0) / 2 + 'px'; } if ($related[1] && (settings.loop || $related[index + 1])) { photo.style.cursor = 'pointer'; photo.onclick = function () { publicMethod.next(); }; } photo.style.width = photo.width + 'px'; photo.style.height = photo.height + 'px'; setTimeout(function () { // A pause because Chrome will sometimes report a 0 by 0 size otherwise. prep(photo); }, 1); }); setTimeout(function () { // A pause because Opera 10.6+ will sometimes not run the onload function otherwise. photo.src = href; }, 1); } else if (href) { $loadingBay.load(href, settings.data, function (data, status) { if (request === requests) { prep(status === 'error' ? $tag(div, 'Error').html(settings.xhrError) : $(this).contents()); } }); } } // Navigates to the next page/image in a set. publicMethod.next = function () { if (!active && $related[1] && (settings.loop || $related[index + 1])) { index = getIndex(1); launch($related[index]); } }; publicMethod.prev = function () { if (!active && $related[1] && (settings.loop || index)) { index = getIndex(-1); launch($related[index]); } }; // Note: to use this within an iframe use the following format: parent.jQuery.colorbox.close(); publicMethod.close = function () { if (open && !closing) { closing = true; open = false; trigger(event_cleanup, settings.onCleanup); $window.unbind('.' + prefix); $overlay.fadeTo(settings.fadeOut || 0, 0); $box.stop().fadeTo(settings.fadeOut || 0, 0, function () { $box.add($overlay).css({'opacity': 1, cursor: 'auto'}).hide(); trigger(event_purge); $loaded.empty().remove(); // Using empty first may prevent some IE7 issues. setTimeout(function () { closing = false; trigger(event_closed, settings.onClosed); }, 1); }); } }; // Removes changes Colorbox made to the document, but does not remove the plugin. publicMethod.remove = function () { if (!$box) { return; } $box.stop(); $.colorbox.close(); $box.stop().remove(); $overlay.remove(); closing = false; $box = null; $('.' + boxElement) .removeData(colorbox) .removeClass(boxElement); $(document).unbind('click.'+prefix); }; // A method for fetching the current element Colorbox is referencing. // returns a jQuery object. publicMethod.element = function () { return $(element); }; publicMethod.settings = defaults; }(jQuery, document, window));
{ "content_hash": "05d6d97922c38bd386b6411fd555b8a5", "timestamp": "", "source": "github", "line_count": 10603, "max_line_length": 222, "avg_line_length": 26.94916533056682, "alnum_prop": 0.6112087127548628, "repo_name": "billyshena/tedx", "id": "554d7d1fc7359c24f77bfbd2a6c4b813ab9d60d4", "size": "286023", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wp-content/themes/tedx/js/vendor.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1848833" }, { "name": "HTML", "bytes": "83127" }, { "name": "JavaScript", "bytes": "3225783" }, { "name": "PHP", "bytes": "10074528" } ], "symlink_target": "" }
;(function() { 'use strict'; console.log('Default components.js'); })();
{ "content_hash": "3fe199e01b4db2d8815eb146374124d8", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 39, "avg_line_length": 15.6, "alnum_prop": 0.5897435897435898, "repo_name": "AndreyYegorov/Frontend-Template", "id": "98bf49b35ff105369661a9ad5a4cae2d35dab73d", "size": "78", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/js/components.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "13564" }, { "name": "HTML", "bytes": "4149" }, { "name": "JavaScript", "bytes": "4982" } ], "symlink_target": "" }
namespace clang { namespace ast_matchers { TEST(DeclarationMatcher, hasMethod) { EXPECT_TRUE(matches("class A { void func(); };", cxxRecordDecl(hasMethod(hasName("func"))))); EXPECT_TRUE(notMatches("class A { void func(); };", cxxRecordDecl(hasMethod(isPublic())))); } TEST(DeclarationMatcher, ClassDerivedFromDependentTemplateSpecialization) { EXPECT_TRUE(matches( "template <typename T> struct A {" " template <typename T2> struct F {};" "};" "template <typename T> struct B : A<T>::template F<T> {};" "B<int> b;", cxxRecordDecl(hasName("B"), isDerivedFrom(recordDecl())))); } TEST(DeclarationMatcher, hasDeclContext) { EXPECT_TRUE(matches( "namespace N {" " namespace M {" " class D {};" " }" "}", recordDecl(hasDeclContext(namespaceDecl(hasName("M")))))); EXPECT_TRUE(notMatches( "namespace N {" " namespace M {" " class D {};" " }" "}", recordDecl(hasDeclContext(namespaceDecl(hasName("N")))))); EXPECT_TRUE(matches("namespace {" " namespace M {" " class D {};" " }" "}", recordDecl(hasDeclContext(namespaceDecl( hasName("M"), hasDeclContext(namespaceDecl())))))); EXPECT_TRUE(matches("class D{};", decl(hasDeclContext(decl())))); } TEST(HasDescendant, MatchesDescendantTypes) { EXPECT_TRUE(matches("void f() { int i = 3; }", decl(hasDescendant(loc(builtinType()))))); EXPECT_TRUE(matches("void f() { int i = 3; }", stmt(hasDescendant(builtinType())))); EXPECT_TRUE(matches("void f() { int i = 3; }", stmt(hasDescendant(loc(builtinType()))))); EXPECT_TRUE(matches("void f() { int i = 3; }", stmt(hasDescendant(qualType(builtinType()))))); EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }", stmt(hasDescendant(isInteger())))); EXPECT_TRUE(matchAndVerifyResultTrue( "void f() { int a; float c; int d; int e; }", functionDecl(forEachDescendant( varDecl(hasDescendant(isInteger())).bind("x"))), std::make_unique<VerifyIdIsBoundTo<Decl>>("x", 3))); } TEST(HasDescendant, MatchesDescendantsOfTypes) { EXPECT_TRUE(matches("void f() { int*** i; }", qualType(hasDescendant(builtinType())))); EXPECT_TRUE(matches("void f() { int*** i; }", qualType(hasDescendant( pointerType(pointee(builtinType())))))); EXPECT_TRUE(matches("void f() { int*** i; }", typeLoc(hasDescendant(loc(builtinType()))))); EXPECT_TRUE(matchAndVerifyResultTrue( "void f() { int*** i; }", qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))), std::make_unique<VerifyIdIsBoundTo<Type>>("x", 2))); } TEST(Has, MatchesChildrenOfTypes) { EXPECT_TRUE(matches("int i;", varDecl(hasName("i"), has(isInteger())))); EXPECT_TRUE(notMatches("int** i;", varDecl(hasName("i"), has(isInteger())))); EXPECT_TRUE(matchAndVerifyResultTrue( "int (*f)(float, int);", qualType(functionType(), forEach(qualType(isInteger()).bind("x"))), std::make_unique<VerifyIdIsBoundTo<QualType>>("x", 2))); } TEST(Has, MatchesChildTypes) { EXPECT_TRUE(matches( "int* i;", varDecl(hasName("i"), hasType(qualType(has(builtinType())))))); EXPECT_TRUE(notMatches( "int* i;", varDecl(hasName("i"), hasType(qualType(has(pointerType())))))); } TEST(StatementMatcher, Has) { StatementMatcher HasVariableI = expr(hasType(pointsTo(recordDecl(hasName("X")))), has(ignoringParenImpCasts(declRefExpr(to(varDecl(hasName("i"))))))); EXPECT_TRUE(matches( "class X; X *x(int); void c() { int i; x(i); }", HasVariableI)); EXPECT_TRUE(notMatches( "class X; X *x(int); void c() { int i; x(42); }", HasVariableI)); } TEST(StatementMatcher, HasDescendant) { StatementMatcher HasDescendantVariableI = expr(hasType(pointsTo(recordDecl(hasName("X")))), hasDescendant(declRefExpr(to(varDecl(hasName("i")))))); EXPECT_TRUE(matches( "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }", HasDescendantVariableI)); EXPECT_TRUE(notMatches( "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }", HasDescendantVariableI)); } TEST(TypeMatcher, MatchesClassType) { TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A"))); EXPECT_TRUE(matches("class A { public: A *a; };", TypeA)); EXPECT_TRUE(notMatches("class A {};", TypeA)); TypeMatcher TypeDerivedFromA = hasDeclaration(cxxRecordDecl(isDerivedFrom("A"))); EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };", TypeDerivedFromA)); EXPECT_TRUE(notMatches("class A {};", TypeA)); TypeMatcher TypeAHasClassB = hasDeclaration( recordDecl(hasName("A"), has(recordDecl(hasName("B"))))); EXPECT_TRUE( matches("class A { public: A *a; class B {}; };", TypeAHasClassB)); EXPECT_TRUE(matchesC("struct S {}; void f(void) { struct S s; }", varDecl(hasType(namedDecl(hasName("S")))))); } TEST(TypeMatcher, MatchesDeclTypes) { // TypedefType -> TypedefNameDecl EXPECT_TRUE(matches("typedef int I; void f(I i);", parmVarDecl(hasType(namedDecl(hasName("I")))))); // ObjCObjectPointerType EXPECT_TRUE(matchesObjC("@interface Foo @end void f(Foo *f);", parmVarDecl(hasType(objcObjectPointerType())))); // ObjCObjectPointerType -> ObjCInterfaceType -> ObjCInterfaceDecl EXPECT_TRUE(matchesObjC( "@interface Foo @end void f(Foo *f);", parmVarDecl(hasType(pointsTo(objcInterfaceDecl(hasName("Foo"))))))); // TemplateTypeParmType EXPECT_TRUE(matches("template <typename T> void f(T t);", parmVarDecl(hasType(templateTypeParmType())))); // TemplateTypeParmType -> TemplateTypeParmDecl EXPECT_TRUE(matches("template <typename T> void f(T t);", parmVarDecl(hasType(namedDecl(hasName("T")))))); // InjectedClassNameType EXPECT_TRUE(matches("template <typename T> struct S {" " void f(S s);" "};", parmVarDecl(hasType(injectedClassNameType())))); EXPECT_TRUE(notMatches("template <typename T> struct S {" " void g(S<T> s);" "};", parmVarDecl(hasType(injectedClassNameType())))); // InjectedClassNameType -> CXXRecordDecl EXPECT_TRUE(matches("template <typename T> struct S {" " void f(S s);" "};", parmVarDecl(hasType(namedDecl(hasName("S")))))); static const char Using[] = "template <typename T>" "struct Base {" " typedef T Foo;" "};" "" "template <typename T>" "struct S : private Base<T> {" " using typename Base<T>::Foo;" " void f(Foo);" "};"; // UnresolvedUsingTypenameDecl EXPECT_TRUE(matches(Using, unresolvedUsingTypenameDecl(hasName("Foo")))); // UnresolvedUsingTypenameType -> UnresolvedUsingTypenameDecl EXPECT_TRUE(matches(Using, parmVarDecl(hasType(namedDecl(hasName("Foo")))))); } TEST(HasDeclaration, HasDeclarationOfEnumType) { EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }", expr(hasType(pointsTo( qualType(hasDeclaration(enumDecl(hasName("X"))))))))); } TEST(HasDeclaration, HasGetDeclTraitTest) { static_assert(internal::has_getDecl<TypedefType>::value, "Expected TypedefType to have a getDecl."); static_assert(internal::has_getDecl<RecordType>::value, "Expected RecordType to have a getDecl."); static_assert(!internal::has_getDecl<TemplateSpecializationType>::value, "Expected TemplateSpecializationType to *not* have a getDecl."); } TEST(HasDeclaration, ElaboratedType) { EXPECT_TRUE(matches( "namespace n { template <typename T> struct X {}; }" "void f(n::X<int>);", parmVarDecl(hasType(qualType(hasDeclaration(cxxRecordDecl())))))); EXPECT_TRUE(matches( "namespace n { template <typename T> struct X {}; }" "void f(n::X<int>);", parmVarDecl(hasType(elaboratedType(hasDeclaration(cxxRecordDecl())))))); } TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) { EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"), hasType(typedefType(hasDeclaration(decl())))))); // FIXME: Add tests for other types with getDecl() (e.g. RecordType) } TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) { EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;", varDecl(hasType(templateSpecializationType( hasDeclaration(namedDecl(hasName("A")))))))); EXPECT_TRUE(matches("template <typename T> class A {};" "template <typename T> class B { A<T> a; };", fieldDecl(hasType(templateSpecializationType( hasDeclaration(namedDecl(hasName("A")))))))); EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;", varDecl(hasType(templateSpecializationType( hasDeclaration(cxxRecordDecl())))))); } TEST(HasDeclaration, HasDeclarationOfCXXNewExpr) { EXPECT_TRUE( matches("int *A = new int();", cxxNewExpr(hasDeclaration(functionDecl(parameterCountIs(1)))))); } TEST(HasDeclaration, HasDeclarationOfTypeAlias) { EXPECT_TRUE(matches("template <typename T> using C = T; C<int> c;", varDecl(hasType(templateSpecializationType( hasDeclaration(typeAliasTemplateDecl())))))); } TEST(HasUnqualifiedDesugaredType, DesugarsUsing) { EXPECT_TRUE( matches("struct A {}; using B = A; B b;", varDecl(hasType(hasUnqualifiedDesugaredType(recordType()))))); EXPECT_TRUE( matches("struct A {}; using B = A; using C = B; C b;", varDecl(hasType(hasUnqualifiedDesugaredType(recordType()))))); } TEST(HasUnderlyingDecl, Matches) { EXPECT_TRUE(matches("namespace N { template <class T> void f(T t); }" "template <class T> void g() { using N::f; f(T()); }", unresolvedLookupExpr(hasAnyDeclaration( namedDecl(hasUnderlyingDecl(hasName("::N::f"))))))); EXPECT_TRUE(matches( "namespace N { template <class T> void f(T t); }" "template <class T> void g() { N::f(T()); }", unresolvedLookupExpr(hasAnyDeclaration(namedDecl(hasName("::N::f")))))); EXPECT_TRUE(notMatches( "namespace N { template <class T> void f(T t); }" "template <class T> void g() { using N::f; f(T()); }", unresolvedLookupExpr(hasAnyDeclaration(namedDecl(hasName("::N::f")))))); } TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) { TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X"))); EXPECT_TRUE( matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX)))); EXPECT_TRUE( notMatches("class X {}; void y(X *x) { x; }", expr(hasType(ClassX)))); EXPECT_TRUE( matches("class X {}; void y(X *x) { x; }", expr(hasType(pointsTo(ClassX))))); } TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) { TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X"))); EXPECT_TRUE( matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX)))); EXPECT_TRUE( notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX)))); EXPECT_TRUE( matches("class X {}; void y() { X *x; }", varDecl(hasType(pointsTo(ClassX))))); } TEST(HasType, TakesDeclMatcherAndMatchesExpr) { DeclarationMatcher ClassX = recordDecl(hasName("X")); EXPECT_TRUE( matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX)))); EXPECT_TRUE( notMatches("class X {}; void y(X *x) { x; }", expr(hasType(ClassX)))); } TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) { DeclarationMatcher ClassX = recordDecl(hasName("X")); EXPECT_TRUE( matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX)))); EXPECT_TRUE( notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX)))); } TEST(HasType, MatchesTypedefDecl) { EXPECT_TRUE(matches("typedef int X;", typedefDecl(hasType(asString("int"))))); EXPECT_TRUE(matches("typedef const int T;", typedefDecl(hasType(asString("const int"))))); EXPECT_TRUE(notMatches("typedef const int T;", typedefDecl(hasType(asString("int"))))); EXPECT_TRUE(matches("typedef int foo; typedef foo bar;", typedefDecl(hasType(asString("foo")), hasName("bar")))); } TEST(HasType, MatchesTypedefNameDecl) { EXPECT_TRUE(matches("using X = int;", typedefNameDecl(hasType(asString("int"))))); EXPECT_TRUE(matches("using T = const int;", typedefNameDecl(hasType(asString("const int"))))); EXPECT_TRUE(notMatches("using T = const int;", typedefNameDecl(hasType(asString("int"))))); EXPECT_TRUE(matches("using foo = int; using bar = foo;", typedefNameDecl(hasType(asString("foo")), hasName("bar")))); } TEST(HasTypeLoc, MatchesDeclaratorDecls) { EXPECT_TRUE(matches("int x;", varDecl(hasName("x"), hasTypeLoc(loc(asString("int")))))); // Make sure we don't crash on implicit constructors. EXPECT_TRUE(notMatches("class X {}; X x;", declaratorDecl(hasTypeLoc(loc(asString("int")))))); } TEST(Callee, MatchesDeclarations) { StatementMatcher CallMethodX = callExpr(callee(cxxMethodDecl(hasName("x")))); EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX)); EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX)); CallMethodX = callExpr(callee(cxxConversionDecl())); EXPECT_TRUE( matches("struct Y { operator int() const; }; int i = Y();", CallMethodX)); EXPECT_TRUE(notMatches("struct Y { operator int() const; }; Y y = Y();", CallMethodX)); } TEST(Callee, MatchesMemberExpressions) { EXPECT_TRUE(matches("class Y { void x() { this->x(); } };", callExpr(callee(memberExpr())))); EXPECT_TRUE( notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr())))); } TEST(Matcher, Argument) { StatementMatcher CallArgumentY = callExpr( hasArgument(0, declRefExpr(to(varDecl(hasName("y")))))); EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY)); EXPECT_TRUE( matches("class X { void x(int) { int y; x(y); } };", CallArgumentY)); EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY)); StatementMatcher WrongIndex = callExpr( hasArgument(42, declRefExpr(to(varDecl(hasName("y")))))); EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex)); } TEST(Matcher, AnyArgument) { auto HasArgumentY = hasAnyArgument( ignoringParenImpCasts(declRefExpr(to(varDecl(hasName("y")))))); StatementMatcher CallArgumentY = callExpr(HasArgumentY); StatementMatcher CtorArgumentY = cxxConstructExpr(HasArgumentY); StatementMatcher UnresolvedCtorArgumentY = cxxUnresolvedConstructExpr(HasArgumentY); StatementMatcher ObjCCallArgumentY = objcMessageExpr(HasArgumentY); EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY)); EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY)); EXPECT_TRUE(matches("struct Y { Y(int, int); };" "void x() { int y; (void)Y(1, y); }", CtorArgumentY)); EXPECT_TRUE(matches("struct Y { Y(int, int); };" "void x() { int y; (void)Y(y, 42); }", CtorArgumentY)); EXPECT_TRUE(matches("template <class Y> void x() { int y; (void)Y(1, y); }", UnresolvedCtorArgumentY)); EXPECT_TRUE(matches("template <class Y> void x() { int y; (void)Y(y, 42); }", UnresolvedCtorArgumentY)); EXPECT_TRUE(matchesObjC("@interface I -(void)f:(int) y; @end " "void x(I* i) { int y; [i f:y]; }", ObjCCallArgumentY)); EXPECT_FALSE(matchesObjC("@interface I -(void)f:(int) z; @end " "void x(I* i) { int z; [i f:z]; }", ObjCCallArgumentY)); EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY)); EXPECT_TRUE(notMatches("struct Y { Y(int, int); };" "void x() { int y; (void)Y(1, 2); }", CtorArgumentY)); EXPECT_TRUE(notMatches("template <class Y>" "void x() { int y; (void)Y(1, 2); }", UnresolvedCtorArgumentY)); StatementMatcher ImplicitCastedArgument = callExpr( hasAnyArgument(implicitCastExpr())); EXPECT_TRUE(matches("void x(long) { int y; x(y); }", ImplicitCastedArgument)); } TEST(Matcher, HasReceiver) { EXPECT_TRUE(matchesObjC( "@interface NSString @end " "void f(NSString *x) {" "[x containsString];" "}", objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x")))))))); EXPECT_FALSE(matchesObjC( "@interface NSString +(NSString *) stringWithFormat; @end " "void f() { [NSString stringWithFormat]; }", objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x")))))))); } TEST(Matcher, isClassMessage) { EXPECT_TRUE(matchesObjC( "@interface NSString +(NSString *) stringWithFormat; @end " "void f() { [NSString stringWithFormat]; }", objcMessageExpr(isClassMessage()))); EXPECT_FALSE(matchesObjC( "@interface NSString @end " "void f(NSString *x) {" "[x containsString];" "}", objcMessageExpr(isClassMessage()))); } TEST(Matcher, isInstanceMessage) { EXPECT_TRUE(matchesObjC( "@interface NSString @end " "void f(NSString *x) {" "[x containsString];" "}", objcMessageExpr(isInstanceMessage()))); EXPECT_FALSE(matchesObjC( "@interface NSString +(NSString *) stringWithFormat; @end " "void f() { [NSString stringWithFormat]; }", objcMessageExpr(isInstanceMessage()))); } TEST(Matcher, isClassMethod) { EXPECT_TRUE(matchesObjC( "@interface Bar + (void)bar; @end", objcMethodDecl(isClassMethod()))); EXPECT_TRUE(matchesObjC( "@interface Bar @end" "@implementation Bar + (void)bar {} @end", objcMethodDecl(isClassMethod()))); EXPECT_FALSE(matchesObjC( "@interface Foo - (void)foo; @end", objcMethodDecl(isClassMethod()))); EXPECT_FALSE(matchesObjC( "@interface Foo @end " "@implementation Foo - (void)foo {} @end", objcMethodDecl(isClassMethod()))); } TEST(Matcher, isInstanceMethod) { EXPECT_TRUE(matchesObjC( "@interface Foo - (void)foo; @end", objcMethodDecl(isInstanceMethod()))); EXPECT_TRUE(matchesObjC( "@interface Foo @end " "@implementation Foo - (void)foo {} @end", objcMethodDecl(isInstanceMethod()))); EXPECT_FALSE(matchesObjC( "@interface Bar + (void)bar; @end", objcMethodDecl(isInstanceMethod()))); EXPECT_FALSE(matchesObjC( "@interface Bar @end" "@implementation Bar + (void)bar {} @end", objcMethodDecl(isInstanceMethod()))); } TEST(MatcherCXXMemberCallExpr, On) { auto Snippet1 = R"cc( struct Y { void m(); }; void z(Y y) { y.m(); } )cc"; auto Snippet2 = R"cc( struct Y { void m(); }; struct X : public Y {}; void z(X x) { x.m(); } )cc"; auto MatchesY = cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y"))))); EXPECT_TRUE(matches(Snippet1, MatchesY)); EXPECT_TRUE(notMatches(Snippet2, MatchesY)); auto MatchesX = cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("X"))))); EXPECT_TRUE(matches(Snippet2, MatchesX)); // Parens are ignored. auto Snippet3 = R"cc( struct Y { void m(); }; Y g(); void z(Y y) { (g()).m(); } )cc"; auto MatchesCall = cxxMemberCallExpr(on(callExpr())); EXPECT_TRUE(matches(Snippet3, MatchesCall)); } TEST(MatcherCXXMemberCallExpr, OnImplicitObjectArgument) { auto Snippet1 = R"cc( struct Y { void m(); }; void z(Y y) { y.m(); } )cc"; auto Snippet2 = R"cc( struct Y { void m(); }; struct X : public Y {}; void z(X x) { x.m(); } )cc"; auto MatchesY = cxxMemberCallExpr( onImplicitObjectArgument(hasType(cxxRecordDecl(hasName("Y"))))); EXPECT_TRUE(matches(Snippet1, MatchesY)); EXPECT_TRUE(matches(Snippet2, MatchesY)); auto MatchesX = cxxMemberCallExpr( onImplicitObjectArgument(hasType(cxxRecordDecl(hasName("X"))))); EXPECT_TRUE(notMatches(Snippet2, MatchesX)); // Parens are not ignored. auto Snippet3 = R"cc( struct Y { void m(); }; Y g(); void z(Y y) { (g()).m(); } )cc"; auto MatchesCall = cxxMemberCallExpr(onImplicitObjectArgument(callExpr())); EXPECT_TRUE(notMatches(Snippet3, MatchesCall)); } TEST(Matcher, HasObjectExpr) { auto Snippet1 = R"cc( struct X { int m; int f(X x) { return x.m; } }; )cc"; auto Snippet2 = R"cc( struct X { int m; int f(X x) { return m; } }; )cc"; auto MatchesX = memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X"))))); EXPECT_TRUE(matches(Snippet1, MatchesX)); EXPECT_TRUE(notMatches(Snippet2, MatchesX)); auto MatchesXPointer = memberExpr( hasObjectExpression(hasType(pointsTo(cxxRecordDecl(hasName("X")))))); EXPECT_TRUE(notMatches(Snippet1, MatchesXPointer)); EXPECT_TRUE(matches(Snippet2, MatchesXPointer)); } TEST(ForEachArgumentWithParam, ReportsNoFalsePositives) { StatementMatcher ArgumentY = declRefExpr(to(varDecl(hasName("y")))).bind("arg"); DeclarationMatcher IntParam = parmVarDecl(hasType(isInteger())).bind("param"); StatementMatcher CallExpr = callExpr(forEachArgumentWithParam(ArgumentY, IntParam)); // IntParam does not match. EXPECT_TRUE(notMatches("void f(int* i) { int* y; f(y); }", CallExpr)); // ArgumentY does not match. EXPECT_TRUE(notMatches("void f(int i) { int x; f(x); }", CallExpr)); } TEST(ForEachArgumentWithParam, MatchesCXXMemberCallExpr) { StatementMatcher ArgumentY = declRefExpr(to(varDecl(hasName("y")))).bind("arg"); DeclarationMatcher IntParam = parmVarDecl(hasType(isInteger())).bind("param"); StatementMatcher CallExpr = callExpr(forEachArgumentWithParam(ArgumentY, IntParam)); EXPECT_TRUE(matchAndVerifyResultTrue( "struct S {" " const S& operator[](int i) { return *this; }" "};" "void f(S S1) {" " int y = 1;" " S1[y];" "}", CallExpr, std::make_unique<VerifyIdIsBoundTo<ParmVarDecl>>("param", 1))); StatementMatcher CallExpr2 = callExpr(forEachArgumentWithParam(ArgumentY, IntParam)); EXPECT_TRUE(matchAndVerifyResultTrue( "struct S {" " static void g(int i);" "};" "void f() {" " int y = 1;" " S::g(y);" "}", CallExpr2, std::make_unique<VerifyIdIsBoundTo<ParmVarDecl>>("param", 1))); } TEST(ForEachArgumentWithParam, MatchesCallExpr) { StatementMatcher ArgumentY = declRefExpr(to(varDecl(hasName("y")))).bind("arg"); DeclarationMatcher IntParam = parmVarDecl(hasType(isInteger())).bind("param"); StatementMatcher CallExpr = callExpr(forEachArgumentWithParam(ArgumentY, IntParam)); EXPECT_TRUE( matchAndVerifyResultTrue("void f(int i) { int y; f(y); }", CallExpr, std::make_unique<VerifyIdIsBoundTo<ParmVarDecl>>( "param"))); EXPECT_TRUE( matchAndVerifyResultTrue("void f(int i) { int y; f(y); }", CallExpr, std::make_unique<VerifyIdIsBoundTo<DeclRefExpr>>( "arg"))); EXPECT_TRUE(matchAndVerifyResultTrue( "void f(int i, int j) { int y; f(y, y); }", CallExpr, std::make_unique<VerifyIdIsBoundTo<ParmVarDecl>>("param", 2))); EXPECT_TRUE(matchAndVerifyResultTrue( "void f(int i, int j) { int y; f(y, y); }", CallExpr, std::make_unique<VerifyIdIsBoundTo<DeclRefExpr>>("arg", 2))); } TEST(ForEachArgumentWithParam, MatchesConstructExpr) { StatementMatcher ArgumentY = declRefExpr(to(varDecl(hasName("y")))).bind("arg"); DeclarationMatcher IntParam = parmVarDecl(hasType(isInteger())).bind("param"); StatementMatcher ConstructExpr = cxxConstructExpr(forEachArgumentWithParam(ArgumentY, IntParam)); EXPECT_TRUE(matchAndVerifyResultTrue( "struct C {" " C(int i) {}" "};" "int y = 0;" "C Obj(y);", ConstructExpr, std::make_unique<VerifyIdIsBoundTo<ParmVarDecl>>("param"))); } TEST(ForEachArgumentWithParam, HandlesBoundNodesForNonMatches) { EXPECT_TRUE(matchAndVerifyResultTrue( "void g(int i, int j) {" " int a;" " int b;" " int c;" " g(a, 0);" " g(a, b);" " g(0, b);" "}", functionDecl( forEachDescendant(varDecl().bind("v")), forEachDescendant(callExpr(forEachArgumentWithParam( declRefExpr(to(decl(equalsBoundNode("v")))), parmVarDecl())))), std::make_unique<VerifyIdIsBoundTo<VarDecl>>("v", 4))); } TEST(QualType, hasCanonicalType) { EXPECT_TRUE(notMatches("typedef int &int_ref;" "int a;" "int_ref b = a;", varDecl(hasType(qualType(referenceType()))))); EXPECT_TRUE( matches("typedef int &int_ref;" "int a;" "int_ref b = a;", varDecl(hasType(qualType(hasCanonicalType(referenceType())))))); } TEST(HasParameter, CallsInnerMatcher) { EXPECT_TRUE(matches("class X { void x(int) {} };", cxxMethodDecl(hasParameter(0, varDecl())))); EXPECT_TRUE(notMatches("class X { void x(int) {} };", cxxMethodDecl(hasParameter(0, hasName("x"))))); EXPECT_TRUE(matchesObjC("@interface I -(void)f:(int) x; @end", objcMethodDecl(hasParameter(0, hasName("x"))))); EXPECT_TRUE(matchesObjC("int main() { void (^b)(int) = ^(int p) {}; }", blockDecl(hasParameter(0, hasName("p"))))); } TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) { EXPECT_TRUE(notMatches("class X { void x(int) {} };", cxxMethodDecl(hasParameter(42, varDecl())))); } TEST(HasType, MatchesParameterVariableTypesStrictly) { EXPECT_TRUE(matches( "class X { void x(X x) {} };", cxxMethodDecl(hasParameter(0, hasType(recordDecl(hasName("X"))))))); EXPECT_TRUE(notMatches( "class X { void x(const X &x) {} };", cxxMethodDecl(hasParameter(0, hasType(recordDecl(hasName("X"))))))); EXPECT_TRUE(matches("class X { void x(const X *x) {} };", cxxMethodDecl(hasParameter( 0, hasType(pointsTo(recordDecl(hasName("X")))))))); EXPECT_TRUE(matches("class X { void x(const X &x) {} };", cxxMethodDecl(hasParameter( 0, hasType(references(recordDecl(hasName("X")))))))); } TEST(HasAnyParameter, MatchesIndependentlyOfPosition) { EXPECT_TRUE(matches( "class Y {}; class X { void x(X x, Y y) {} };", cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X"))))))); EXPECT_TRUE(matches( "class Y {}; class X { void x(Y y, X x) {} };", cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X"))))))); EXPECT_TRUE(matchesObjC("@interface I -(void)f:(int) x; @end", objcMethodDecl(hasAnyParameter(hasName("x"))))); EXPECT_TRUE(matchesObjC("int main() { void (^b)(int) = ^(int p) {}; }", blockDecl(hasAnyParameter(hasName("p"))))); } TEST(Returns, MatchesReturnTypes) { EXPECT_TRUE(matches("class Y { int f() { return 1; } };", functionDecl(returns(asString("int"))))); EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };", functionDecl(returns(asString("float"))))); EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };", functionDecl(returns(hasDeclaration( recordDecl(hasName("Y"))))))); } TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) { EXPECT_TRUE(notMatches( "class Y {}; class X { void x(int) {} };", cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X"))))))); } TEST(HasAnyParameter, DoesNotMatchThisPointer) { EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };", cxxMethodDecl(hasAnyParameter( hasType(pointsTo(recordDecl(hasName("X")))))))); } TEST(HasName, MatchesParameterVariableDeclarations) { EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };", cxxMethodDecl(hasAnyParameter(hasName("x"))))); EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };", cxxMethodDecl(hasAnyParameter(hasName("x"))))); } TEST(Matcher, MatchesTypeTemplateArgument) { EXPECT_TRUE(matches( "template<typename T> struct B {};" "B<int> b;", classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType( asString("int")))))); } TEST(Matcher, MatchesTemplateTemplateArgument) { EXPECT_TRUE(matches("template<template <typename> class S> class X {};" "template<typename T> class Y {};" "X<Y> xi;", classTemplateSpecializationDecl(hasAnyTemplateArgument( refersToTemplate(templateName()))))); } TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) { EXPECT_TRUE(matches( "struct B { int next; };" "template<int(B::*next_ptr)> struct A {};" "A<&B::next> a;", classTemplateSpecializationDecl(hasAnyTemplateArgument( refersToDeclaration(fieldDecl(hasName("next"))))))); EXPECT_TRUE(notMatches( "template <typename T> struct A {};" "A<int> a;", classTemplateSpecializationDecl(hasAnyTemplateArgument( refersToDeclaration(decl()))))); EXPECT_TRUE(matches( "struct B { int next; };" "template<int(B::*next_ptr)> struct A {};" "A<&B::next> a;", templateSpecializationType(hasAnyTemplateArgument(isExpr( hasDescendant(declRefExpr(to(fieldDecl(hasName("next")))))))))); EXPECT_TRUE(notMatches( "template <typename T> struct A {};" "A<int> a;", templateSpecializationType(hasAnyTemplateArgument( refersToDeclaration(decl()))))); } TEST(Matcher, MatchesSpecificArgument) { EXPECT_TRUE(matches( "template<typename T, typename U> class A {};" "A<bool, int> a;", classTemplateSpecializationDecl(hasTemplateArgument( 1, refersToType(asString("int")))))); EXPECT_TRUE(notMatches( "template<typename T, typename U> class A {};" "A<int, bool> a;", classTemplateSpecializationDecl(hasTemplateArgument( 1, refersToType(asString("int")))))); EXPECT_TRUE(matches( "template<typename T, typename U> class A {};" "A<bool, int> a;", templateSpecializationType(hasTemplateArgument( 1, refersToType(asString("int")))))); EXPECT_TRUE(notMatches( "template<typename T, typename U> class A {};" "A<int, bool> a;", templateSpecializationType(hasTemplateArgument( 1, refersToType(asString("int")))))); EXPECT_TRUE(matches( "template<typename T> void f() {};" "void func() { f<int>(); }", functionDecl(hasTemplateArgument(0, refersToType(asString("int")))))); EXPECT_TRUE(notMatches( "template<typename T> void f() {};", functionDecl(hasTemplateArgument(0, refersToType(asString("int")))))); } TEST(TemplateArgument, Matches) { EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;", classTemplateSpecializationDecl( hasAnyTemplateArgument(templateArgument())))); EXPECT_TRUE(matches( "template<typename T> struct C {}; C<int> c;", templateSpecializationType(hasAnyTemplateArgument(templateArgument())))); EXPECT_TRUE(matches( "template<typename T> void f() {};" "void func() { f<int>(); }", functionDecl(hasAnyTemplateArgument(templateArgument())))); } TEST(TemplateTypeParmDecl, CXXMethodDecl) { const char input[] = "template<typename T>\n" "class Class {\n" " void method();\n" "};\n" "template<typename U>\n" "void Class<U>::method() {}\n"; EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("T")))); EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("U")))); } TEST(TemplateTypeParmDecl, VarDecl) { const char input[] = "template<typename T>\n" "class Class {\n" " static T pi;\n" "};\n" "template<typename U>\n" "U Class<U>::pi = U(3.1415926535897932385);\n"; EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("T")))); EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("U")))); } TEST(TemplateTypeParmDecl, VarTemplatePartialSpecializationDecl) { const char input[] = "template<typename T>\n" "struct Struct {\n" " template<typename T2> static int field;\n" "};\n" "template<typename U>\n" "template<typename U2>\n" "int Struct<U>::field<U2*> = 123;\n"; EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("T")))); EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("T2")))); EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("U")))); EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("U2")))); } TEST(TemplateTypeParmDecl, ClassTemplatePartialSpecializationDecl) { const char input[] = "template<typename T>\n" "class Class {\n" " template<typename T2> struct Struct;\n" "};\n" "template<typename U>\n" "template<typename U2>\n" "struct Class<U>::Struct<U2*> {};\n"; EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("T")))); EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("T2")))); EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("U")))); EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("U2")))); } TEST(TemplateTypeParmDecl, EnumDecl) { const char input[] = "template<typename T>\n" "struct Struct {\n" " enum class Enum : T;\n" "};\n" "template<typename U>\n" "enum class Struct<U>::Enum : U {\n" " e1,\n" " e2\n" "};\n"; EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("T")))); EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("U")))); } TEST(TemplateTypeParmDecl, RecordDecl) { const char input[] = "template<typename T>\n" "class Class {\n" " struct Struct;\n" "};\n" "template<typename U>\n" "struct Class<U>::Struct {\n" " U field;\n" "};\n"; EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("T")))); EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("U")))); } TEST(RefersToIntegralType, Matches) { EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;", classTemplateSpecializationDecl( hasAnyTemplateArgument(refersToIntegralType( asString("int")))))); EXPECT_TRUE(notMatches("template<unsigned T> struct C {}; C<42> c;", classTemplateSpecializationDecl(hasAnyTemplateArgument( refersToIntegralType(asString("int")))))); } TEST(ConstructorDeclaration, SimpleCase) { EXPECT_TRUE(matches("class Foo { Foo(int i); };", cxxConstructorDecl(ofClass(hasName("Foo"))))); EXPECT_TRUE(notMatches("class Foo { Foo(int i); };", cxxConstructorDecl(ofClass(hasName("Bar"))))); } TEST(DestructorDeclaration, MatchesVirtualDestructor) { EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };", cxxDestructorDecl(ofClass(hasName("Foo"))))); } TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) { EXPECT_TRUE(notMatches("class Foo {};", cxxDestructorDecl(ofClass(hasName("Foo"))))); } TEST(HasAnyConstructorInitializer, SimpleCase) { EXPECT_TRUE( notMatches("class Foo { Foo() { } };", cxxConstructorDecl(hasAnyConstructorInitializer(anything())))); EXPECT_TRUE( matches("class Foo {" " Foo() : foo_() { }" " int foo_;" "};", cxxConstructorDecl(hasAnyConstructorInitializer(anything())))); } TEST(HasAnyConstructorInitializer, ForField) { static const char Code[] = "class Baz { };" "class Foo {" " Foo() : foo_(), bar_() { }" " Baz foo_;" " struct {" " Baz bar_;" " };" "};"; EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer( forField(hasType(recordDecl(hasName("Baz")))))))); EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer( forField(hasName("foo_")))))); EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer( forField(hasName("bar_")))))); EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer( forField(hasType(recordDecl(hasName("Bar")))))))); } TEST(HasAnyConstructorInitializer, WithInitializer) { static const char Code[] = "class Foo {" " Foo() : foo_(0) { }" " int foo_;" "};"; EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer( withInitializer(integerLiteral(equals(0))))))); EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer( withInitializer(integerLiteral(equals(1))))))); } TEST(HasAnyConstructorInitializer, IsWritten) { static const char Code[] = "struct Bar { Bar(){} };" "class Foo {" " Foo() : foo_() { }" " Bar foo_;" " Bar bar_;" "};"; EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer( allOf(forField(hasName("foo_")), isWritten()))))); EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer( allOf(forField(hasName("bar_")), isWritten()))))); EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer( allOf(forField(hasName("bar_")), unless(isWritten())))))); } TEST(HasAnyConstructorInitializer, IsBaseInitializer) { static const char Code[] = "struct B {};" "struct D : B {" " int I;" " D(int i) : I(i) {}" "};" "struct E : B {" " E() : B() {}" "};"; EXPECT_TRUE(matches(Code, cxxConstructorDecl(allOf( hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())), hasName("E"))))); EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(allOf( hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())), hasName("D"))))); EXPECT_TRUE(matches(Code, cxxConstructorDecl(allOf( hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())), hasName("D"))))); EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(allOf( hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())), hasName("E"))))); } TEST(IfStmt, ChildTraversalMatchers) { EXPECT_TRUE(matches("void f() { if (false) true; else false; }", ifStmt(hasThen(cxxBoolLiteral(equals(true)))))); EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }", ifStmt(hasThen(cxxBoolLiteral(equals(true)))))); EXPECT_TRUE(matches("void f() { if (false) false; else true; }", ifStmt(hasElse(cxxBoolLiteral(equals(true)))))); EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }", ifStmt(hasElse(cxxBoolLiteral(equals(true)))))); } TEST(MatchBinaryOperator, HasOperatorName) { StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||")); EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr)); EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr)); } TEST(MatchBinaryOperator, HasLHSAndHasRHS) { StatementMatcher OperatorTrueFalse = binaryOperator(hasLHS(cxxBoolLiteral(equals(true))), hasRHS(cxxBoolLiteral(equals(false)))); EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse)); EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse)); EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse)); StatementMatcher OperatorIntPointer = arraySubscriptExpr( hasLHS(hasType(isInteger())), hasRHS(hasType(pointsTo(qualType())))); EXPECT_TRUE(matches("void x() { 1[\"abc\"]; }", OperatorIntPointer)); EXPECT_TRUE(notMatches("void x() { \"abc\"[1]; }", OperatorIntPointer)); } TEST(MatchBinaryOperator, HasEitherOperand) { StatementMatcher HasOperand = binaryOperator(hasEitherOperand(cxxBoolLiteral(equals(false)))); EXPECT_TRUE(matches("void x() { true || false; }", HasOperand)); EXPECT_TRUE(matches("void x() { false && true; }", HasOperand)); EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand)); } TEST(Matcher, BinaryOperatorTypes) { // Integration test that verifies the AST provides all binary operators in // a way we expect. // FIXME: Operator ',' EXPECT_TRUE( matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(",")))); EXPECT_TRUE( matches("bool b; bool c = (b = true);", binaryOperator(hasOperatorName("=")))); EXPECT_TRUE( matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!=")))); EXPECT_TRUE( matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("==")))); EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<")))); EXPECT_TRUE( matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<=")))); EXPECT_TRUE( matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<")))); EXPECT_TRUE( matches("int i = 1; int j = (i <<= 2);", binaryOperator(hasOperatorName("<<=")))); EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">")))); EXPECT_TRUE( matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">=")))); EXPECT_TRUE( matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>")))); EXPECT_TRUE( matches("int i = 1; int j = (i >>= 2);", binaryOperator(hasOperatorName(">>=")))); EXPECT_TRUE( matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^")))); EXPECT_TRUE( matches("int i = 42; int j = (i ^= 42);", binaryOperator(hasOperatorName("^=")))); EXPECT_TRUE( matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%")))); EXPECT_TRUE( matches("int i = 42; int j = (i %= 42);", binaryOperator(hasOperatorName("%=")))); EXPECT_TRUE( matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&")))); EXPECT_TRUE( matches("bool b = true && false;", binaryOperator(hasOperatorName("&&")))); EXPECT_TRUE( matches("bool b = true; bool c = (b &= false);", binaryOperator(hasOperatorName("&=")))); EXPECT_TRUE( matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|")))); EXPECT_TRUE( matches("bool b = true || false;", binaryOperator(hasOperatorName("||")))); EXPECT_TRUE( matches("bool b = true; bool c = (b |= false);", binaryOperator(hasOperatorName("|=")))); EXPECT_TRUE( matches("int i = 42 *23;", binaryOperator(hasOperatorName("*")))); EXPECT_TRUE( matches("int i = 42; int j = (i *= 23);", binaryOperator(hasOperatorName("*=")))); EXPECT_TRUE( matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/")))); EXPECT_TRUE( matches("int i = 42; int j = (i /= 23);", binaryOperator(hasOperatorName("/=")))); EXPECT_TRUE( matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+")))); EXPECT_TRUE( matches("int i = 42; int j = (i += 23);", binaryOperator(hasOperatorName("+=")))); EXPECT_TRUE( matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-")))); EXPECT_TRUE( matches("int i = 42; int j = (i -= 23);", binaryOperator(hasOperatorName("-=")))); EXPECT_TRUE( matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };", binaryOperator(hasOperatorName("->*")))); EXPECT_TRUE( matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };", binaryOperator(hasOperatorName(".*")))); // Member expressions as operators are not supported in matches. EXPECT_TRUE( notMatches("struct A { void x(A *a) { a->x(this); } };", binaryOperator(hasOperatorName("->")))); // Initializer assignments are not represented as operator equals. EXPECT_TRUE( notMatches("bool b = true;", binaryOperator(hasOperatorName("=")))); // Array indexing is not represented as operator. EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator())); // Overloaded operators do not match at all. EXPECT_TRUE(notMatches( "struct A { bool operator&&(const A &a) const { return false; } };" "void x() { A a, b; a && b; }", binaryOperator())); } TEST(MatchUnaryOperator, HasOperatorName) { StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!")); EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot)); EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot)); } TEST(MatchUnaryOperator, HasUnaryOperand) { StatementMatcher OperatorOnFalse = unaryOperator(hasUnaryOperand(cxxBoolLiteral(equals(false)))); EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse)); EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse)); } TEST(Matcher, UnaryOperatorTypes) { // Integration test that verifies the AST provides all unary operators in // a way we expect. EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!")))); EXPECT_TRUE( matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&")))); EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~")))); EXPECT_TRUE( matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*")))); EXPECT_TRUE( matches("int i; int j = +i;", unaryOperator(hasOperatorName("+")))); EXPECT_TRUE( matches("int i; int j = -i;", unaryOperator(hasOperatorName("-")))); EXPECT_TRUE( matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++")))); EXPECT_TRUE( matches("int i; int j = i++;", unaryOperator(hasOperatorName("++")))); EXPECT_TRUE( matches("int i; int j = --i;", unaryOperator(hasOperatorName("--")))); EXPECT_TRUE( matches("int i; int j = i--;", unaryOperator(hasOperatorName("--")))); // We don't match conversion operators. EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator())); // Function calls are not represented as operator. EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator())); // Overloaded operators do not match at all. // FIXME: We probably want to add that. EXPECT_TRUE(notMatches( "struct A { bool operator!() const { return false; } };" "void x() { A a; !a; }", unaryOperator(hasOperatorName("!")))); } TEST(ArraySubscriptMatchers, ArrayIndex) { EXPECT_TRUE(matches( "int i[2]; void f() { i[1] = 1; }", arraySubscriptExpr(hasIndex(integerLiteral(equals(1)))))); EXPECT_TRUE(matches( "int i[2]; void f() { 1[i] = 1; }", arraySubscriptExpr(hasIndex(integerLiteral(equals(1)))))); EXPECT_TRUE(notMatches( "int i[2]; void f() { i[1] = 1; }", arraySubscriptExpr(hasIndex(integerLiteral(equals(0)))))); } TEST(ArraySubscriptMatchers, MatchesArrayBase) { EXPECT_TRUE(matches( "int i[2]; void f() { i[1] = 2; }", arraySubscriptExpr(hasBase(implicitCastExpr( hasSourceExpression(declRefExpr())))))); } TEST(Matcher, OfClass) { StatementMatcher Constructor = cxxConstructExpr(hasDeclaration(cxxMethodDecl( ofClass(hasName("X"))))); EXPECT_TRUE( matches("class X { public: X(); }; void x(int) { X x; }", Constructor)); EXPECT_TRUE( matches("class X { public: X(); }; void x(int) { X x = X(); }", Constructor)); EXPECT_TRUE( notMatches("class Y { public: Y(); }; void x(int) { Y y; }", Constructor)); } TEST(Matcher, VisitsTemplateInstantiations) { EXPECT_TRUE(matches( "class A { public: void x(); };" "template <typename T> class B { public: void y() { T t; t.x(); } };" "void f() { B<A> b; b.y(); }", callExpr(callee(cxxMethodDecl(hasName("x")))))); EXPECT_TRUE(matches( "class A { public: void x(); };" "class C {" " public:" " template <typename T> class B { public: void y() { T t; t.x(); } };" "};" "void f() {" " C::B<A> b; b.y();" "}", recordDecl(hasName("C"), hasDescendant(callExpr( callee(cxxMethodDecl(hasName("x")))))))); } TEST(Matcher, HasCondition) { StatementMatcher IfStmt = ifStmt(hasCondition(cxxBoolLiteral(equals(true)))); EXPECT_TRUE(matches("void x() { if (true) {} }", IfStmt)); EXPECT_TRUE(notMatches("void x() { if (false) {} }", IfStmt)); StatementMatcher ForStmt = forStmt(hasCondition(cxxBoolLiteral(equals(true)))); EXPECT_TRUE(matches("void x() { for (;true;) {} }", ForStmt)); EXPECT_TRUE(notMatches("void x() { for (;false;) {} }", ForStmt)); StatementMatcher WhileStmt = whileStmt(hasCondition(cxxBoolLiteral(equals(true)))); EXPECT_TRUE(matches("void x() { while (true) {} }", WhileStmt)); EXPECT_TRUE(notMatches("void x() { while (false) {} }", WhileStmt)); StatementMatcher SwitchStmt = switchStmt(hasCondition(integerLiteral(equals(42)))); EXPECT_TRUE(matches("void x() { switch (42) {case 42:;} }", SwitchStmt)); EXPECT_TRUE(notMatches("void x() { switch (43) {case 43:;} }", SwitchStmt)); } TEST(For, ForLoopInternals) { EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }", forStmt(hasCondition(anything())))); EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }", forStmt(hasLoopInit(anything())))); } TEST(For, ForRangeLoopInternals) { EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }", cxxForRangeStmt(hasLoopVariable(anything())))); EXPECT_TRUE(matches( "void f(){ int a[] {1, 2}; for (int i : a); }", cxxForRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a")))))))); } TEST(For, NegativeForLoopInternals) { EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }", forStmt(hasCondition(expr())))); EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }", forStmt(hasLoopInit(anything())))); } TEST(HasBody, FindsBodyOfForWhileDoLoops) { EXPECT_TRUE(matches("void f() { for(;;) {} }", forStmt(hasBody(compoundStmt())))); EXPECT_TRUE(notMatches("void f() { for(;;); }", forStmt(hasBody(compoundStmt())))); EXPECT_TRUE(matches("void f() { while(true) {} }", whileStmt(hasBody(compoundStmt())))); EXPECT_TRUE(matches("void f() { do {} while(true); }", doStmt(hasBody(compoundStmt())))); EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }", cxxForRangeStmt(hasBody(compoundStmt())))); EXPECT_TRUE(matches("void f() {}", functionDecl(hasBody(compoundStmt())))); EXPECT_TRUE(notMatches("void f();", functionDecl(hasBody(compoundStmt())))); EXPECT_TRUE(matches("void f(); void f() {}", functionDecl(hasBody(compoundStmt())))); } TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) { // The simplest case: every compound statement is in a function // definition, and the function body itself must be a compound // statement. EXPECT_TRUE(matches("void f() { for (;;); }", compoundStmt(hasAnySubstatement(forStmt())))); } TEST(HasAnySubstatement, IsNotRecursive) { // It's really "has any immediate substatement". EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }", compoundStmt(hasAnySubstatement(forStmt())))); } TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) { EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }", compoundStmt(hasAnySubstatement(forStmt())))); } TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) { EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }", compoundStmt(hasAnySubstatement(forStmt())))); } TEST(Member, MatchesMemberAllocationFunction) { // Fails in C++11 mode EXPECT_TRUE(matchesConditionally( "namespace std { typedef typeof(sizeof(int)) size_t; }" "class X { void *operator new(std::size_t); };", cxxMethodDecl(ofClass(hasName("X"))), true, "-std=gnu++98")); EXPECT_TRUE(matches("class X { void operator delete(void*); };", cxxMethodDecl(ofClass(hasName("X"))))); // Fails in C++11 mode EXPECT_TRUE(matchesConditionally( "namespace std { typedef typeof(sizeof(int)) size_t; }" "class X { void operator delete[](void*, std::size_t); };", cxxMethodDecl(ofClass(hasName("X"))), true, "-std=gnu++98")); } TEST(HasDestinationType, MatchesSimpleCase) { EXPECT_TRUE(matches("char* p = static_cast<char*>(0);", cxxStaticCastExpr(hasDestinationType( pointsTo(TypeMatcher(anything())))))); } TEST(HasImplicitDestinationType, MatchesSimpleCase) { // This test creates an implicit const cast. EXPECT_TRUE(matches("int x; const int i = x;", implicitCastExpr( hasImplicitDestinationType(isInteger())))); // This test creates an implicit array-to-pointer cast. EXPECT_TRUE(matches("int arr[3]; int *p = arr;", implicitCastExpr(hasImplicitDestinationType( pointsTo(TypeMatcher(anything())))))); } TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) { // This test creates an implicit cast from int to char. EXPECT_TRUE(notMatches("char c = 0;", implicitCastExpr(hasImplicitDestinationType( unless(anything()))))); // This test creates an implicit array-to-pointer cast. EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;", implicitCastExpr(hasImplicitDestinationType( unless(anything()))))); } TEST(Matcher, IgnoresElidableConstructors) { EXPECT_TRUE( matches("struct H {};" "template<typename T> H B(T A);" "void f() {" " H D1;" " D1 = B(B(1));" "}", cxxOperatorCallExpr(hasArgument( 1, callExpr(hasArgument( 0, ignoringElidableConstructorCall(callExpr()))))), LanguageMode::Cxx11OrLater)); EXPECT_TRUE( matches("struct H {};" "template<typename T> H B(T A);" "void f() {" " H D1;" " D1 = B(1);" "}", cxxOperatorCallExpr(hasArgument( 1, callExpr(hasArgument(0, ignoringElidableConstructorCall( integerLiteral()))))), LanguageMode::Cxx11OrLater)); EXPECT_TRUE(matches( "struct H {};" "H G();" "void f() {" " H D = G();" "}", varDecl(hasInitializer(anyOf( ignoringElidableConstructorCall(callExpr()), exprWithCleanups(has(ignoringElidableConstructorCall(callExpr())))))), LanguageMode::Cxx11OrLater)); } TEST(Matcher, IgnoresElidableInReturn) { auto matcher = expr(ignoringElidableConstructorCall(declRefExpr())); EXPECT_TRUE(matches("struct H {};" "H f() {" " H g;" " return g;" "}", matcher, LanguageMode::Cxx11OrLater)); EXPECT_TRUE(notMatches("struct H {};" "H f() {" " return H();" "}", matcher, LanguageMode::Cxx11OrLater)); } TEST(Matcher, IgnoreElidableConstructorDoesNotMatchConstructors) { EXPECT_TRUE(matches("struct H {};" "void f() {" " H D;" "}", varDecl(hasInitializer( ignoringElidableConstructorCall(cxxConstructExpr()))), LanguageMode::Cxx11OrLater)); } TEST(Matcher, IgnoresElidableDoesNotPreventMatches) { EXPECT_TRUE(matches("void f() {" " int D = 10;" "}", expr(ignoringElidableConstructorCall(integerLiteral())), LanguageMode::Cxx11OrLater)); } TEST(Matcher, IgnoresElidableInVarInit) { auto matcher = varDecl(hasInitializer(ignoringElidableConstructorCall(callExpr()))); EXPECT_TRUE(matches("struct H {};" "H G();" "void f(H D = G()) {" " return;" "}", matcher, LanguageMode::Cxx11OrLater)); EXPECT_TRUE(matches("struct H {};" "H G();" "void f() {" " H D = G();" "}", matcher, LanguageMode::Cxx11OrLater)); } TEST(IgnoringImplicit, MatchesImplicit) { EXPECT_TRUE(matches("class C {}; C a = C();", varDecl(has(ignoringImplicit(cxxConstructExpr()))))); } TEST(IgnoringImplicit, MatchesNestedImplicit) { StringRef Code = R"( struct OtherType; struct SomeType { SomeType() {} SomeType(const OtherType&) {} SomeType& operator=(OtherType const&) { return *this; } }; struct OtherType { OtherType() {} ~OtherType() {} }; OtherType something() { return {}; } int main() { SomeType i = something(); } )"; EXPECT_TRUE(matches(Code, varDecl( hasName("i"), hasInitializer(exprWithCleanups(has( cxxConstructExpr(has(expr(ignoringImplicit(cxxConstructExpr( has(expr(ignoringImplicit(callExpr()))) ))))) ))) ) )); } TEST(IgnoringImplicit, DoesNotMatchIncorrectly) { EXPECT_TRUE( notMatches("class C {}; C a = C();", varDecl(has(cxxConstructExpr())))); } TEST(IgnoringImpCasts, MatchesImpCasts) { // This test checks that ignoringImpCasts matches when implicit casts are // present and its inner matcher alone does not match. // Note that this test creates an implicit const cast. EXPECT_TRUE(matches("int x = 0; const int y = x;", varDecl(hasInitializer(ignoringImpCasts( declRefExpr(to(varDecl(hasName("x"))))))))); // This test creates an implict cast from int to char. EXPECT_TRUE(matches("char x = 0;", varDecl(hasInitializer(ignoringImpCasts( integerLiteral(equals(0))))))); } TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) { // These tests verify that ignoringImpCasts does not match if the inner // matcher does not match. // Note that the first test creates an implicit const cast. EXPECT_TRUE(notMatches("int x; const int y = x;", varDecl(hasInitializer(ignoringImpCasts( unless(anything())))))); EXPECT_TRUE(notMatches("int x; int y = x;", varDecl(hasInitializer(ignoringImpCasts( unless(anything())))))); // These tests verify that ignoringImplictCasts does not look through explicit // casts or parentheses. EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);", varDecl(hasInitializer(ignoringImpCasts( integerLiteral()))))); EXPECT_TRUE(notMatches("int i = (0);", varDecl(hasInitializer(ignoringImpCasts( integerLiteral()))))); EXPECT_TRUE(notMatches("float i = (float)0;", varDecl(hasInitializer(ignoringImpCasts( integerLiteral()))))); EXPECT_TRUE(notMatches("float i = float(0);", varDecl(hasInitializer(ignoringImpCasts( integerLiteral()))))); } TEST(IgnoringImpCasts, MatchesWithoutImpCasts) { // This test verifies that expressions that do not have implicit casts // still match the inner matcher. EXPECT_TRUE(matches("int x = 0; int &y = x;", varDecl(hasInitializer(ignoringImpCasts( declRefExpr(to(varDecl(hasName("x"))))))))); } TEST(IgnoringParenCasts, MatchesParenCasts) { // This test checks that ignoringParenCasts matches when parentheses and/or // casts are present and its inner matcher alone does not match. EXPECT_TRUE(matches("int x = (0);", varDecl(hasInitializer(ignoringParenCasts( integerLiteral(equals(0))))))); EXPECT_TRUE(matches("int x = (((((0)))));", varDecl(hasInitializer(ignoringParenCasts( integerLiteral(equals(0))))))); // This test creates an implict cast from int to char in addition to the // parentheses. EXPECT_TRUE(matches("char x = (0);", varDecl(hasInitializer(ignoringParenCasts( integerLiteral(equals(0))))))); EXPECT_TRUE(matches("char x = (char)0;", varDecl(hasInitializer(ignoringParenCasts( integerLiteral(equals(0))))))); EXPECT_TRUE(matches("char* p = static_cast<char*>(0);", varDecl(hasInitializer(ignoringParenCasts( integerLiteral(equals(0))))))); } TEST(IgnoringParenCasts, MatchesWithoutParenCasts) { // This test verifies that expressions that do not have any casts still match. EXPECT_TRUE(matches("int x = 0;", varDecl(hasInitializer(ignoringParenCasts( integerLiteral(equals(0))))))); } TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) { // These tests verify that ignoringImpCasts does not match if the inner // matcher does not match. EXPECT_TRUE(notMatches("int x = ((0));", varDecl(hasInitializer(ignoringParenCasts( unless(anything())))))); // This test creates an implicit cast from int to char in addition to the // parentheses. EXPECT_TRUE(notMatches("char x = ((0));", varDecl(hasInitializer(ignoringParenCasts( unless(anything())))))); EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));", varDecl(hasInitializer(ignoringParenCasts( unless(anything())))))); } TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) { // This test checks that ignoringParenAndImpCasts matches when // parentheses and/or implicit casts are present and its inner matcher alone // does not match. // Note that this test creates an implicit const cast. EXPECT_TRUE(matches("int x = 0; const int y = x;", varDecl(hasInitializer(ignoringParenImpCasts( declRefExpr(to(varDecl(hasName("x"))))))))); // This test creates an implicit cast from int to char. EXPECT_TRUE(matches("const char x = (0);", varDecl(hasInitializer(ignoringParenImpCasts( integerLiteral(equals(0))))))); } TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) { // This test verifies that expressions that do not have parentheses or // implicit casts still match. EXPECT_TRUE(matches("int x = 0; int &y = x;", varDecl(hasInitializer(ignoringParenImpCasts( declRefExpr(to(varDecl(hasName("x"))))))))); EXPECT_TRUE(matches("int x = 0;", varDecl(hasInitializer(ignoringParenImpCasts( integerLiteral(equals(0))))))); } TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) { // These tests verify that ignoringParenImpCasts does not match if // the inner matcher does not match. // This test creates an implicit cast. EXPECT_TRUE(notMatches("char c = ((3));", varDecl(hasInitializer(ignoringParenImpCasts( unless(anything())))))); // These tests verify that ignoringParenAndImplictCasts does not look // through explicit casts. EXPECT_TRUE(notMatches("float y = (float(0));", varDecl(hasInitializer(ignoringParenImpCasts( integerLiteral()))))); EXPECT_TRUE(notMatches("float y = (float)0;", varDecl(hasInitializer(ignoringParenImpCasts( integerLiteral()))))); EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);", varDecl(hasInitializer(ignoringParenImpCasts( integerLiteral()))))); } TEST(HasSourceExpression, MatchesImplicitCasts) { EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };" "void r() {string a_string; URL url = a_string; }", implicitCastExpr( hasSourceExpression(cxxConstructExpr())))); } TEST(HasSourceExpression, MatchesExplicitCasts) { EXPECT_TRUE(matches("float x = static_cast<float>(42);", explicitCastExpr( hasSourceExpression(hasDescendant( expr(integerLiteral())))))); } TEST(UsingDeclaration, MatchesSpecificTarget) { EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;", usingDecl(hasAnyUsingShadowDecl( hasTargetDecl(functionDecl()))))); EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;", usingDecl(hasAnyUsingShadowDecl( hasTargetDecl(functionDecl()))))); } TEST(UsingDeclaration, ThroughUsingDeclaration) { EXPECT_TRUE(matches( "namespace a { void f(); } using a::f; void g() { f(); }", declRefExpr(throughUsingDecl(anything())))); EXPECT_TRUE(notMatches( "namespace a { void f(); } using a::f; void g() { a::f(); }", declRefExpr(throughUsingDecl(anything())))); } TEST(SingleDecl, IsSingleDecl) { StatementMatcher SingleDeclStmt = declStmt(hasSingleDecl(varDecl(hasInitializer(anything())))); EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt)); EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt)); EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}", SingleDeclStmt)); } TEST(DeclStmt, ContainsDeclaration) { DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything())); EXPECT_TRUE(matches("void f() {int a = 4;}", declStmt(containsDeclaration(0, MatchesInit)))); EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}", declStmt(containsDeclaration(0, MatchesInit), containsDeclaration(1, MatchesInit)))); unsigned WrongIndex = 42; EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}", declStmt(containsDeclaration(WrongIndex, MatchesInit)))); } TEST(SwitchCase, MatchesEachCase) { EXPECT_TRUE(notMatches("void x() { switch(42); }", switchStmt(forEachSwitchCase(caseStmt())))); EXPECT_TRUE(matches("void x() { switch(42) case 42:; }", switchStmt(forEachSwitchCase(caseStmt())))); EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt(forEachSwitchCase(caseStmt())))); EXPECT_TRUE(notMatches( "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }", ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt())))))); EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }", switchStmt(forEachSwitchCase( caseStmt(hasCaseConstant( constantExpr(has(integerLiteral())))))))); EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }", switchStmt(forEachSwitchCase( caseStmt(hasCaseConstant( constantExpr(has(integerLiteral())))))))); EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }", switchStmt(forEachSwitchCase( caseStmt(hasCaseConstant( constantExpr(has(integerLiteral())))))))); EXPECT_TRUE(matchAndVerifyResultTrue( "void x() { switch (42) { case 1: case 2: case 3: default:; } }", switchStmt(forEachSwitchCase(caseStmt().bind("x"))), std::make_unique<VerifyIdIsBoundTo<CaseStmt>>("x", 3))); } TEST(Declaration, HasExplicitSpecifier) { EXPECT_TRUE(matchesConditionally( "void f();", functionDecl(hasExplicitSpecifier(constantExpr())), false, "-std=c++2a")); EXPECT_TRUE(matchesConditionally( "template<bool b> struct S { explicit operator int(); };", cxxConversionDecl(hasExplicitSpecifier(constantExpr(has(cxxBoolLiteral())))), false, "-std=c++2a")); EXPECT_TRUE(matchesConditionally( "template<bool b> struct S { explicit(b) operator int(); };", cxxConversionDecl(hasExplicitSpecifier(constantExpr(has(cxxBoolLiteral())))), false, "-std=c++2a")); EXPECT_TRUE(matchesConditionally( "struct S { explicit(true) operator int(); };", cxxConversionDecl(hasExplicitSpecifier(constantExpr(has(cxxBoolLiteral())))), true, "-std=c++2a")); EXPECT_TRUE(matchesConditionally( "struct S { explicit(false) operator int(); };", cxxConversionDecl(hasExplicitSpecifier(constantExpr(has(cxxBoolLiteral())))), true, "-std=c++2a")); EXPECT_TRUE(matchesConditionally( "template<bool b> struct S { explicit(b) S(int); };", cxxConstructorDecl(hasExplicitSpecifier(constantExpr(has(cxxBoolLiteral())))), false, "-std=c++2a")); EXPECT_TRUE(matchesConditionally( "struct S { explicit(true) S(int); };", cxxConstructorDecl(hasExplicitSpecifier(constantExpr(has(cxxBoolLiteral())))), true, "-std=c++2a")); EXPECT_TRUE(matchesConditionally( "struct S { explicit(false) S(int); };", cxxConstructorDecl(hasExplicitSpecifier(constantExpr(has(cxxBoolLiteral())))), true, "-std=c++2a")); EXPECT_TRUE(matchesConditionally( "template<typename T> struct S { S(int); };" "template<bool b = true> explicit(b) S(int) -> S<int>;", cxxDeductionGuideDecl( hasExplicitSpecifier(constantExpr(has(cxxBoolLiteral())))), false, "-std=c++2a")); EXPECT_TRUE(matchesConditionally("template<typename T> struct S { S(int); };" "explicit(true) S(int) -> S<int>;", cxxDeductionGuideDecl(hasExplicitSpecifier( constantExpr(has(cxxBoolLiteral())))), true, "-std=c++2a")); EXPECT_TRUE(matchesConditionally("template<typename T> struct S { S(int); };" "explicit(false) S(int) -> S<int>;", cxxDeductionGuideDecl(hasExplicitSpecifier( constantExpr(has(cxxBoolLiteral())))), true, "-std=c++2a")); } TEST(ForEachConstructorInitializer, MatchesInitializers) { EXPECT_TRUE(matches( "struct X { X() : i(42), j(42) {} int i, j; };", cxxConstructorDecl(forEachConstructorInitializer(cxxCtorInitializer())))); } TEST(HasConditionVariableStatement, DoesNotMatchCondition) { EXPECT_TRUE(notMatches( "void x() { if(true) {} }", ifStmt(hasConditionVariableStatement(declStmt())))); EXPECT_TRUE(notMatches( "void x() { int x; if((x = 42)) {} }", ifStmt(hasConditionVariableStatement(declStmt())))); } TEST(HasConditionVariableStatement, MatchesConditionVariables) { EXPECT_TRUE(matches( "void x() { if(int* a = 0) {} }", ifStmt(hasConditionVariableStatement(declStmt())))); } TEST(ForEach, BindsOneNode) { EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };", recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))), std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("x", 1))); } TEST(ForEach, BindsMultipleNodes) { EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };", recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))), std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("f", 3))); } TEST(ForEach, BindsRecursiveCombinations) { EXPECT_TRUE(matchAndVerifyResultTrue( "class C { class D { int x; int y; }; class E { int y; int z; }; };", recordDecl(hasName("C"), forEach(recordDecl(forEach(fieldDecl().bind("f"))))), std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("f", 4))); } TEST(ForEachDescendant, BindsOneNode) { EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };", recordDecl(hasName("C"), forEachDescendant(fieldDecl(hasName("x")).bind("x"))), std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("x", 1))); } TEST(ForEachDescendant, NestedForEachDescendant) { DeclarationMatcher m = recordDecl( isDefinition(), decl().bind("x"), hasName("C")); EXPECT_TRUE(matchAndVerifyResultTrue( "class A { class B { class C {}; }; };", recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))), std::make_unique<VerifyIdIsBoundTo<Decl>>("x", "C"))); // Check that a partial match of 'm' that binds 'x' in the // first part of anyOf(m, anything()) will not overwrite the // binding created by the earlier binding in the hasDescendant. EXPECT_TRUE(matchAndVerifyResultTrue( "class A { class B { class C {}; }; };", recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))), std::make_unique<VerifyIdIsBoundTo<Decl>>("x", "C"))); } TEST(ForEachDescendant, BindsMultipleNodes) { EXPECT_TRUE(matchAndVerifyResultTrue( "class C { class D { int x; int y; }; " " class E { class F { int y; int z; }; }; };", recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))), std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("f", 4))); } TEST(ForEachDescendant, BindsRecursiveCombinations) { EXPECT_TRUE(matchAndVerifyResultTrue( "class C { class D { " " class E { class F { class G { int y; int z; }; }; }; }; };", recordDecl(hasName("C"), forEachDescendant(recordDecl( forEachDescendant(fieldDecl().bind("f"))))), std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("f", 8))); } TEST(ForEachDescendant, BindsCombinations) { EXPECT_TRUE(matchAndVerifyResultTrue( "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while " "(true) {} }", compoundStmt(forEachDescendant(ifStmt().bind("if")), forEachDescendant(whileStmt().bind("while"))), std::make_unique<VerifyIdIsBoundTo<IfStmt>>("if", 6))); } TEST(Has, DoesNotDeleteBindings) { EXPECT_TRUE(matchAndVerifyResultTrue( "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())), std::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1))); } TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) { // Those matchers cover all the cases where an inner matcher is called // and there is not a 1:1 relationship between the match of the outer // matcher and the match of the inner matcher. // The pattern to look for is: // ... return InnerMatcher.matches(...); ... // In which case no special handling is needed. // // On the other hand, if there are multiple alternative matches // (for example forEach*) or matches might be discarded (for example has*) // the implementation must make sure that the discarded matches do not // affect the bindings. // When new such matchers are added, add a test here that: // - matches a simple node, and binds it as the first thing in the matcher: // recordDecl(decl().bind("x"), hasName("X"))) // - uses the matcher under test afterwards in a way that not the first // alternative is matched; for anyOf, that means the first branch // would need to return false; for hasAncestor, it means that not // the direct parent matches the inner matcher. EXPECT_TRUE(matchAndVerifyResultTrue( "class X { int y; };", recordDecl( recordDecl().bind("x"), hasName("::X"), anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())), std::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("x", 1))); EXPECT_TRUE(matchAndVerifyResultTrue( "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"), anyOf(unless(anything()), anything())), std::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("x", 1))); EXPECT_TRUE(matchAndVerifyResultTrue( "template<typename T1, typename T2> class X {}; X<float, int> x;", classTemplateSpecializationDecl( decl().bind("x"), hasAnyTemplateArgument(refersToType(asString("int")))), std::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1))); EXPECT_TRUE(matchAndVerifyResultTrue( "class X { void f(); void g(); };", cxxRecordDecl(decl().bind("x"), hasMethod(hasName("g"))), std::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1))); EXPECT_TRUE(matchAndVerifyResultTrue( "class X { X() : a(1), b(2) {} double a; int b; };", recordDecl(decl().bind("x"), has(cxxConstructorDecl( hasAnyConstructorInitializer(forField(hasName("b")))))), std::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1))); EXPECT_TRUE(matchAndVerifyResultTrue( "void x(int, int) { x(0, 42); }", callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))), std::make_unique<VerifyIdIsBoundTo<Expr>>("x", 1))); EXPECT_TRUE(matchAndVerifyResultTrue( "void x(int, int y) {}", functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))), std::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1))); EXPECT_TRUE(matchAndVerifyResultTrue( "void x() { return; if (true) {} }", functionDecl(decl().bind("x"), has(compoundStmt(hasAnySubstatement(ifStmt())))), std::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1))); EXPECT_TRUE(matchAndVerifyResultTrue( "namespace X { void b(int); void b(); }" "using X::b;", usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl( functionDecl(parameterCountIs(1))))), std::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1))); EXPECT_TRUE(matchAndVerifyResultTrue( "class A{}; class B{}; class C : B, A {};", cxxRecordDecl(decl().bind("x"), isDerivedFrom("::A")), std::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1))); EXPECT_TRUE(matchAndVerifyResultTrue( "class A{}; typedef A B; typedef A C; typedef A D;" "class E : A {};", cxxRecordDecl(decl().bind("x"), isDerivedFrom("C")), std::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1))); EXPECT_TRUE(matchAndVerifyResultTrue( "class A { class B { void f() {} }; };", functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))), std::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1))); EXPECT_TRUE(matchAndVerifyResultTrue( "template <typename T> struct A { struct B {" " void f() { if(true) {} }" "}; };" "void t() { A<int>::B b; b.f(); }", ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))), std::make_unique<VerifyIdIsBoundTo<Stmt>>("x", 2))); EXPECT_TRUE(matchAndVerifyResultTrue( "class A {};", recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))), std::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1))); EXPECT_TRUE(matchAndVerifyResultTrue( "class A { A() : s(), i(42) {} const char *s; int i; };", cxxConstructorDecl(hasName("::A::A"), decl().bind("x"), forEachConstructorInitializer(forField(hasName("i")))), std::make_unique<VerifyIdIsBoundTo<Decl>>("x", 1))); } TEST(ForEachDescendant, BindsCorrectNodes) { EXPECT_TRUE(matchAndVerifyResultTrue( "class C { void f(); int i; };", recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))), std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("decl", 1))); EXPECT_TRUE(matchAndVerifyResultTrue( "class C { void f() {} int i; };", recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))), std::make_unique<VerifyIdIsBoundTo<FunctionDecl>>("decl", 1))); } TEST(FindAll, BindsNodeOnMatch) { EXPECT_TRUE(matchAndVerifyResultTrue( "class A {};", recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))), std::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("v", 1))); } TEST(FindAll, BindsDescendantNodeOnMatch) { EXPECT_TRUE(matchAndVerifyResultTrue( "class A { int a; int b; };", recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))), std::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v", 2))); } TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) { EXPECT_TRUE(matchAndVerifyResultTrue( "class A { int a; int b; };", recordDecl(hasName("::A"), findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"), fieldDecl().bind("v"))))), std::make_unique<VerifyIdIsBoundTo<Decl>>("v", 3))); EXPECT_TRUE(matchAndVerifyResultTrue( "class A { class B {}; class C {}; };", recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))), std::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("v", 3))); } TEST(HasAncenstor, MatchesDeclarationAncestors) { EXPECT_TRUE(matches( "class A { class B { class C {}; }; };", recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A")))))); } TEST(HasAncenstor, FailsIfNoAncestorMatches) { EXPECT_TRUE(notMatches( "class A { class B { class C {}; }; };", recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X")))))); } TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) { EXPECT_TRUE(matches( "class A { class B { void f() { C c; } class C {}; }; };", varDecl(hasName("c"), hasType(recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A")))))))); } TEST(HasAncenstor, MatchesStatementAncestors) { EXPECT_TRUE(matches( "void f() { if (true) { while (false) { 42; } } }", integerLiteral(equals(42), hasAncestor(ifStmt())))); } TEST(HasAncestor, DrillsThroughDifferentHierarchies) { EXPECT_TRUE(matches( "void f() { if (true) { int x = 42; } }", integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f")))))); } TEST(HasAncestor, BindsRecursiveCombinations) { EXPECT_TRUE(matchAndVerifyResultTrue( "class C { class D { class E { class F { int y; }; }; }; };", fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))), std::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("r", 1))); } TEST(HasAncestor, BindsCombinationsWithHasDescendant) { EXPECT_TRUE(matchAndVerifyResultTrue( "class C { class D { class E { class F { int y; }; }; }; };", fieldDecl(hasAncestor( decl( hasDescendant(recordDecl(isDefinition(), hasAncestor(recordDecl()))) ).bind("d") )), std::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("d", "E"))); } TEST(HasAncestor, MatchesClosestAncestor) { EXPECT_TRUE(matchAndVerifyResultTrue( "template <typename T> struct C {" " void f(int) {" " struct I { void g(T) { int x; } } i; i.g(42);" " }" "};" "template struct C<int>;", varDecl(hasName("x"), hasAncestor(functionDecl(hasParameter( 0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"), std::make_unique<VerifyIdIsBoundTo<FunctionDecl>>("f", "g", 2))); } TEST(HasAncestor, MatchesInTemplateInstantiations) { EXPECT_TRUE(matches( "template <typename T> struct A { struct B { struct C { T t; }; }; }; " "A<int>::B::C a;", fieldDecl(hasType(asString("int")), hasAncestor(recordDecl(hasName("A")))))); } TEST(HasAncestor, MatchesInImplicitCode) { EXPECT_TRUE(matches( "struct X {}; struct A { A() {} X x; };", cxxConstructorDecl( hasAnyConstructorInitializer(withInitializer(expr( hasAncestor(recordDecl(hasName("A"))))))))); } TEST(HasParent, MatchesOnlyParent) { EXPECT_TRUE(matches( "void f() { if (true) { int x = 42; } }", compoundStmt(hasParent(ifStmt())))); EXPECT_TRUE(notMatches( "void f() { for (;;) { int x = 42; } }", compoundStmt(hasParent(ifStmt())))); EXPECT_TRUE(notMatches( "void f() { if (true) for (;;) { int x = 42; } }", compoundStmt(hasParent(ifStmt())))); } TEST(HasAncestor, MatchesAllAncestors) { EXPECT_TRUE(matches( "template <typename T> struct C { static void f() { 42; } };" "void t() { C<int>::f(); }", integerLiteral( equals(42), allOf( hasAncestor(cxxRecordDecl(isTemplateInstantiation())), hasAncestor(cxxRecordDecl(unless(isTemplateInstantiation()))))))); } TEST(HasAncestor, ImplicitArrayCopyCtorDeclRefExpr) { EXPECT_TRUE(matches("struct MyClass {\n" " int c[1];\n" " static MyClass Create() { return MyClass(); }\n" "};", declRefExpr(to(decl(hasAncestor(decl())))))); } TEST(HasAncestor, AnonymousUnionMemberExpr) { EXPECT_TRUE(matches("int F() {\n" " union { int i; };\n" " return i;\n" "}\n", memberExpr(member(hasAncestor(decl()))))); EXPECT_TRUE(matches("void f() {\n" " struct {\n" " struct { int a; int b; };\n" " } s;\n" " s.a = 4;\n" "}\n", memberExpr(member(hasAncestor(decl()))))); EXPECT_TRUE(matches("void f() {\n" " struct {\n" " struct { int a; int b; };\n" " } s;\n" " s.a = 4;\n" "}\n", declRefExpr(to(decl(hasAncestor(decl())))))); } TEST(HasAncestor, NonParmDependentTemplateParmVarDeclRefExpr) { EXPECT_TRUE(matches("struct PartitionAllocator {\n" " template<typename T>\n" " static int quantizedSize(int count) {\n" " return count;\n" " }\n" " void f() { quantizedSize<int>(10); }\n" "};", declRefExpr(to(decl(hasAncestor(decl())))))); } TEST(HasAncestor, AddressOfExplicitSpecializationFunction) { EXPECT_TRUE(matches("template <class T> void f();\n" "template <> void f<int>();\n" "void (*get_f())() { return f<int>; }\n", declRefExpr(to(decl(hasAncestor(decl())))))); } TEST(HasParent, MatchesAllParents) { EXPECT_TRUE(matches( "template <typename T> struct C { static void f() { 42; } };" "void t() { C<int>::f(); }", integerLiteral( equals(42), hasParent(compoundStmt(hasParent(functionDecl( hasParent(cxxRecordDecl(isTemplateInstantiation()))))))))); EXPECT_TRUE( matches("template <typename T> struct C { static void f() { 42; } };" "void t() { C<int>::f(); }", integerLiteral( equals(42), hasParent(compoundStmt(hasParent(functionDecl(hasParent( cxxRecordDecl(unless(isTemplateInstantiation())))))))))); EXPECT_TRUE(matches( "template <typename T> struct C { static void f() { 42; } };" "void t() { C<int>::f(); }", integerLiteral(equals(42), hasParent(compoundStmt( allOf(hasParent(functionDecl(hasParent( cxxRecordDecl(isTemplateInstantiation())))), hasParent(functionDecl(hasParent(cxxRecordDecl( unless(isTemplateInstantiation()))))))))))); EXPECT_TRUE( notMatches("template <typename T> struct C { static void f() {} };" "void t() { C<int>::f(); }", compoundStmt(hasParent(recordDecl())))); } TEST(HasParent, NoDuplicateParents) { class HasDuplicateParents : public BoundNodesCallback { public: bool run(const BoundNodes *Nodes) override { return false; } bool run(const BoundNodes *Nodes, ASTContext *Context) override { const Stmt *Node = Nodes->getNodeAs<Stmt>("node"); std::set<const void *> Parents; for (const auto &Parent : Context->getParents(*Node)) { if (!Parents.insert(Parent.getMemoizationData()).second) { return true; } } return false; } }; EXPECT_FALSE(matchAndVerifyResultTrue( "template <typename T> int Foo() { return 1 + 2; }\n" "int x = Foo<int>() + Foo<unsigned>();", stmt().bind("node"), std::make_unique<HasDuplicateParents>())); } TEST(TypeMatching, PointeeTypes) { EXPECT_TRUE(matches("int b; int &a = b;", referenceType(pointee(builtinType())))); EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType())))); EXPECT_TRUE(matches("int *a;", loc(pointerType(pointee(builtinType()))))); EXPECT_TRUE(matches( "int const *A;", pointerType(pointee(isConstQualified(), builtinType())))); EXPECT_TRUE(notMatches( "int *A;", pointerType(pointee(isConstQualified(), builtinType())))); } TEST(ElaboratedTypeNarrowing, hasQualifier) { EXPECT_TRUE(matches( "namespace N {" " namespace M {" " class D {};" " }" "}" "N::M::D d;", elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))))); EXPECT_TRUE(notMatches( "namespace M {" " class D {};" "}" "M::D d;", elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))))); EXPECT_TRUE(notMatches( "struct D {" "} d;", elaboratedType(hasQualifier(nestedNameSpecifier())))); } TEST(ElaboratedTypeNarrowing, namesType) { EXPECT_TRUE(matches( "namespace N {" " namespace M {" " class D {};" " }" "}" "N::M::D d;", elaboratedType(elaboratedType(namesType(recordType( hasDeclaration(namedDecl(hasName("D"))))))))); EXPECT_TRUE(notMatches( "namespace M {" " class D {};" "}" "M::D d;", elaboratedType(elaboratedType(namesType(typedefType()))))); } TEST(NNS, BindsNestedNameSpecifiers) { EXPECT_TRUE(matchAndVerifyResultTrue( "namespace ns { struct E { struct B {}; }; } ns::E::B b;", nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"), std::make_unique<VerifyIdIsBoundTo<NestedNameSpecifier>>( "nns", "ns::struct E::"))); } TEST(NNS, BindsNestedNameSpecifierLocs) { EXPECT_TRUE(matchAndVerifyResultTrue( "namespace ns { struct B {}; } ns::B b;", loc(nestedNameSpecifier()).bind("loc"), std::make_unique<VerifyIdIsBoundTo<NestedNameSpecifierLoc>>("loc", 1))); } TEST(NNS, DescendantsOfNestedNameSpecifiers) { std::string Fragment = "namespace a { struct A { struct B { struct C {}; }; }; };" "void f() { a::A::B::C c; }"; EXPECT_TRUE(matches( Fragment, nestedNameSpecifier(specifiesType(asString("struct a::A::B")), hasDescendant(nestedNameSpecifier( specifiesNamespace(hasName("a"))))))); EXPECT_TRUE(notMatches( Fragment, nestedNameSpecifier(specifiesType(asString("struct a::A::B")), has(nestedNameSpecifier( specifiesNamespace(hasName("a"))))))); EXPECT_TRUE(matches( Fragment, nestedNameSpecifier(specifiesType(asString("struct a::A")), has(nestedNameSpecifier( specifiesNamespace(hasName("a"))))))); // Not really useful because a NestedNameSpecifier can af at most one child, // but to complete the interface. EXPECT_TRUE(matchAndVerifyResultTrue( Fragment, nestedNameSpecifier(specifiesType(asString("struct a::A::B")), forEach(nestedNameSpecifier().bind("x"))), std::make_unique<VerifyIdIsBoundTo<NestedNameSpecifier>>("x", 1))); } TEST(NNS, NestedNameSpecifiersAsDescendants) { std::string Fragment = "namespace a { struct A { struct B { struct C {}; }; }; };" "void f() { a::A::B::C c; }"; EXPECT_TRUE(matches( Fragment, decl(hasDescendant(nestedNameSpecifier(specifiesType( asString("struct a::A"))))))); EXPECT_TRUE(matchAndVerifyResultTrue( Fragment, functionDecl(hasName("f"), forEachDescendant(nestedNameSpecifier().bind("x"))), // Nested names: a, a::A and a::A::B. std::make_unique<VerifyIdIsBoundTo<NestedNameSpecifier>>("x", 3))); } TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) { std::string Fragment = "namespace a { struct A { struct B { struct C {}; }; }; };" "void f() { a::A::B::C c; }"; EXPECT_TRUE(matches( Fragment, nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))), hasDescendant(loc(nestedNameSpecifier( specifiesNamespace(hasName("a")))))))); EXPECT_TRUE(notMatches( Fragment, nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))), has(loc(nestedNameSpecifier( specifiesNamespace(hasName("a")))))))); EXPECT_TRUE(matches( Fragment, nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))), has(loc(nestedNameSpecifier( specifiesNamespace(hasName("a")))))))); EXPECT_TRUE(matchAndVerifyResultTrue( Fragment, nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))), forEach(nestedNameSpecifierLoc().bind("x"))), std::make_unique<VerifyIdIsBoundTo<NestedNameSpecifierLoc>>("x", 1))); } TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) { std::string Fragment = "namespace a { struct A { struct B { struct C {}; }; }; };" "void f() { a::A::B::C c; }"; EXPECT_TRUE(matches( Fragment, decl(hasDescendant(loc(nestedNameSpecifier(specifiesType( asString("struct a::A")))))))); EXPECT_TRUE(matchAndVerifyResultTrue( Fragment, functionDecl(hasName("f"), forEachDescendant(nestedNameSpecifierLoc().bind("x"))), // Nested names: a, a::A and a::A::B. std::make_unique<VerifyIdIsBoundTo<NestedNameSpecifierLoc>>("x", 3))); } template <typename T> class VerifyMatchOnNode : public BoundNodesCallback { public: VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher, StringRef InnerId) : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) { } bool run(const BoundNodes *Nodes) override { return false; } bool run(const BoundNodes *Nodes, ASTContext *Context) override { const T *Node = Nodes->getNodeAs<T>(Id); return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) != nullptr; } private: std::string Id; internal::Matcher<T> InnerMatcher; std::string InnerId; }; TEST(MatchFinder, CanMatchDeclarationsRecursively) { EXPECT_TRUE(matchAndVerifyResultTrue( "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"), std::make_unique<VerifyMatchOnNode<Decl>>( "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))), "Y"))); EXPECT_TRUE(matchAndVerifyResultFalse( "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"), std::make_unique<VerifyMatchOnNode<Decl>>( "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))), "Z"))); } TEST(MatchFinder, CanMatchStatementsRecursively) { EXPECT_TRUE(matchAndVerifyResultTrue( "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"), std::make_unique<VerifyMatchOnNode<Stmt>>( "if", stmt(hasDescendant(forStmt().bind("for"))), "for"))); EXPECT_TRUE(matchAndVerifyResultFalse( "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"), std::make_unique<VerifyMatchOnNode<Stmt>>( "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl"))); } TEST(MatchFinder, CanMatchSingleNodesRecursively) { EXPECT_TRUE(matchAndVerifyResultTrue( "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"), std::make_unique<VerifyMatchOnNode<Decl>>( "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y"))); EXPECT_TRUE(matchAndVerifyResultFalse( "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"), std::make_unique<VerifyMatchOnNode<Decl>>( "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z"))); } TEST(StatementMatcher, HasReturnValue) { StatementMatcher RetVal = returnStmt(hasReturnValue(binaryOperator())); EXPECT_TRUE(matches("int F() { int a, b; return a + b; }", RetVal)); EXPECT_FALSE(matches("int F() { int a; return a; }", RetVal)); EXPECT_FALSE(matches("void F() { return; }", RetVal)); } TEST(StatementMatcher, ForFunction) { const auto CppString1 = "struct PosVec {" " PosVec& operator=(const PosVec&) {" " auto x = [] { return 1; };" " return *this;" " }" "};"; const auto CppString2 = "void F() {" " struct S {" " void F2() {" " return;" " }" " };" "}"; EXPECT_TRUE( matches( CppString1, returnStmt(forFunction(hasName("operator=")), has(unaryOperator(hasOperatorName("*")))))); EXPECT_TRUE( notMatches( CppString1, returnStmt(forFunction(hasName("operator=")), has(integerLiteral())))); EXPECT_TRUE( matches( CppString1, returnStmt(forFunction(hasName("operator()")), has(integerLiteral())))); EXPECT_TRUE(matches(CppString2, returnStmt(forFunction(hasName("F2"))))); EXPECT_TRUE(notMatches(CppString2, returnStmt(forFunction(hasName("F"))))); } TEST(Matcher, ForEachOverriden) { const auto ForEachOverriddenInClass = [](const char *ClassName) { return cxxMethodDecl(ofClass(hasName(ClassName)), isVirtual(), forEachOverridden(cxxMethodDecl().bind("overridden"))) .bind("override"); }; static const char Code1[] = "class A { virtual void f(); };" "class B : public A { void f(); };" "class C : public B { void f(); };"; // C::f overrides A::f. EXPECT_TRUE(matchAndVerifyResultTrue( Code1, ForEachOverriddenInClass("C"), std::make_unique<VerifyIdIsBoundTo<CXXMethodDecl>>("override", "f", 1))); EXPECT_TRUE(matchAndVerifyResultTrue( Code1, ForEachOverriddenInClass("C"), std::make_unique<VerifyIdIsBoundTo<CXXMethodDecl>>("overridden", "f", 1))); // B::f overrides A::f. EXPECT_TRUE(matchAndVerifyResultTrue( Code1, ForEachOverriddenInClass("B"), std::make_unique<VerifyIdIsBoundTo<CXXMethodDecl>>("override", "f", 1))); EXPECT_TRUE(matchAndVerifyResultTrue( Code1, ForEachOverriddenInClass("B"), std::make_unique<VerifyIdIsBoundTo<CXXMethodDecl>>("overridden", "f", 1))); // A::f overrides nothing. EXPECT_TRUE(notMatches(Code1, ForEachOverriddenInClass("A"))); static const char Code2[] = "class A1 { virtual void f(); };" "class A2 { virtual void f(); };" "class B : public A1, public A2 { void f(); };"; // B::f overrides A1::f and A2::f. This produces two matches. EXPECT_TRUE(matchAndVerifyResultTrue( Code2, ForEachOverriddenInClass("B"), std::make_unique<VerifyIdIsBoundTo<CXXMethodDecl>>("override", "f", 2))); EXPECT_TRUE(matchAndVerifyResultTrue( Code2, ForEachOverriddenInClass("B"), std::make_unique<VerifyIdIsBoundTo<CXXMethodDecl>>("overridden", "f", 2))); // A1::f overrides nothing. EXPECT_TRUE(notMatches(Code2, ForEachOverriddenInClass("A1"))); } TEST(Matcher, HasAnyDeclaration) { std::string Fragment = "void foo(int p1);" "void foo(int *p2);" "void bar(int p3);" "template <typename T> void baz(T t) { foo(t); }"; EXPECT_TRUE( matches(Fragment, unresolvedLookupExpr(hasAnyDeclaration(functionDecl( hasParameter(0, parmVarDecl(hasName("p1")))))))); EXPECT_TRUE( matches(Fragment, unresolvedLookupExpr(hasAnyDeclaration(functionDecl( hasParameter(0, parmVarDecl(hasName("p2")))))))); EXPECT_TRUE( notMatches(Fragment, unresolvedLookupExpr(hasAnyDeclaration(functionDecl( hasParameter(0, parmVarDecl(hasName("p3")))))))); EXPECT_TRUE(notMatches(Fragment, unresolvedLookupExpr(hasAnyDeclaration( functionDecl(hasName("bar")))))); } TEST(SubstTemplateTypeParmType, HasReplacementType) { std::string Fragment = "template<typename T>" "double F(T t);" "int i;" "double j = F(i);"; EXPECT_TRUE(matches(Fragment, substTemplateTypeParmType(hasReplacementType( qualType(asString("int")))))); EXPECT_TRUE(notMatches(Fragment, substTemplateTypeParmType(hasReplacementType( qualType(asString("double")))))); EXPECT_TRUE( notMatches("template<int N>" "double F();" "double j = F<5>();", substTemplateTypeParmType(hasReplacementType(qualType())))); } TEST(ClassTemplateSpecializationDecl, HasSpecializedTemplate) { auto Matcher = classTemplateSpecializationDecl( hasSpecializedTemplate(classTemplateDecl())); EXPECT_TRUE( matches("template<typename T> class A {}; typedef A<int> B;", Matcher)); EXPECT_TRUE(notMatches("template<typename T> class A {};", Matcher)); } } // namespace ast_matchers } // namespace clang
{ "content_hash": "421449fed5921cdc311a1e6b5a685a05", "timestamp": "", "source": "github", "line_count": 2631, "max_line_length": 108, "avg_line_length": 39.29532497149373, "alnum_prop": 0.6003520786179947, "repo_name": "llvm-mirror/clang", "id": "693962919051ee8a0ffba0bd80815f2fd514fea9", "size": "104032", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "unittests/ASTMatchers/ASTMatchersTraversalTest.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AppleScript", "bytes": "1429" }, { "name": "Assembly", "bytes": "52848" }, { "name": "Batchfile", "bytes": "73" }, { "name": "C", "bytes": "21778565" }, { "name": "C#", "bytes": "27472" }, { "name": "C++", "bytes": "74235878" }, { "name": "CMake", "bytes": "177439" }, { "name": "CSS", "bytes": "8395" }, { "name": "Cool", "bytes": "26684" }, { "name": "Cuda", "bytes": "425982" }, { "name": "Dockerfile", "bytes": "2124" }, { "name": "Emacs Lisp", "bytes": "17060" }, { "name": "Forth", "bytes": "925" }, { "name": "Fortran", "bytes": "8180" }, { "name": "HTML", "bytes": "993731" }, { "name": "JavaScript", "bytes": "42269" }, { "name": "LLVM", "bytes": "29443" }, { "name": "M", "bytes": "4660" }, { "name": "MATLAB", "bytes": "61446" }, { "name": "Makefile", "bytes": "8489" }, { "name": "Mathematica", "bytes": "5584" }, { "name": "Mercury", "bytes": "1193" }, { "name": "Objective-C", "bytes": "3646294" }, { "name": "Objective-C++", "bytes": "915138" }, { "name": "Perl", "bytes": "96915" }, { "name": "Python", "bytes": "815826" }, { "name": "RenderScript", "bytes": "741" }, { "name": "Roff", "bytes": "10932" }, { "name": "Rust", "bytes": "200" }, { "name": "Shell", "bytes": "10663" } ], "symlink_target": "" }
img: https://storage.googleapis.com/mail-attachments subject: "Isha Yoga Center" preview: https://rawgit.com/ishacrm/emails/master/dist/hk/2017/iyc-mailer.html --- <container> <row class="collapse no-vpad"> <columns> <wrapper> <a href="http://www.ishafoundation.org/" target="_blank"> <img src="http://www.ishafoundation.org/mailmarketer/admin/temp/user/3/isha-yoga-center.jpg" title="Isha Yoga Center" alt="Isha Yoga Center" style="width: 100%; border: none;" /> </a> </wrapper> </columns> </row> <row> <columns style="background: #ffecc9"> <p style="font-family: Georgia; color: #21343f; line-height: 35px; padding-top: 20px;"><span style="font-size: 40px;"><span style="font-size: large;">Dear {{{{raw}}}}{{FIRST_NAME}}{{{{/raw}}}},</span></span></p> <p style="font-family: Georgia; font-size: 18px; color: #21343f; line-height: 35px;">Hope your practices are going well. We would like to take this opportunity to welcome you and your family to the Isha Yoga Center in Coimbatore, India. The Isha Yoga Center is set at the foothills of the Velliangiri mountains and offers a peaceful and beautiful place to take a welcome break from the din of the daily life in the city. This is a powerful energy space created by Sadhguru that acts as a support for inner transformation. </p> <p style="font-family: Georgia; font-size: 18px; color: #21343f; line-height: 35px;">This space is extremely supportive for your everyday practices and kriya. You can also meditate in the Dhyanalinga Temple or get soaked in the grace of the Linga Bhairavi- they are both energy forms consecrated by Sadhguru for human well-being. A dip in the Theerthakund- an energised pool inside the temple complex, will revitalise and purify your body and mind as you become more receptive to the energies of the space. </p> <p style="font-family: Georgia; font-size: 18px; color: #21343f; line-height: 35px;"> To visit and experience Isha Yoga Center on your own, you can write to <a style="color: #b9801d;" href="mailto:visitindia-apac@ishafoundation.org">visitindia-apac@ishafoundation.org</a>. </p> <p style="font-family: Georgia; font-size: 18px; color: #21343f; line-height: 35px;"> Alternatively, you can also join <a style="color: #b9801d;" href="https://ishayoga.hk/isha-yoga-center-retreat" target="_blank">Isha Yoga Centre Retreat</a> conducted regularly, where a volunteer accompanies a group of participants from airport and back. To express your interest in upcoming retreats, please write to <a style="color: #b9801d;" href="mailto:retreat.apac@ishafoundation.org">retreat.apac@ishafoundation.org</a>. </p> <p style="font-family: Georgia; font-size: 18px; color: #21343f; line-height: 35px;"> You can also take a step towards volunteering by sharing this inner science with your friends and family. To express your interest as a volunteer, please fill <a style="color: #b9801d;" href="http://fb.com/hongkongisha" target="_blank">this</a> form. </p><p style="font-family: Georgia; font-size: 18px; color: #21343f; line-height: 35px;"> There are also various <a style="color: #b9801d;" href="http://www.ishaoutreach.org" target="_blank"><strong>social outreach projects</strong></a> you can involve yourself with, and you can stay updated with the Isha Yoga Centre through various articles and videos on <a style="color: #b9801d;" href="http://fb.com/hongkongisha" target="_blank"><strong>Facebook</strong></a>, <a style="color: #b9801d;" href="https://www.youtube.com/Sadhguru" target="_blank"><strong>Youtube</strong></a>, the <a style="color: #b9801d;" href="http://isha.sadhguru.org/blog/" target="_blank"><strong>Blog</strong></a>, and download <a style="color: #b9801d;" href="http://isha.sadhguru.org/mobile-apps/" target="_blank"><strong>Sadhguru</strong></a> mobile application&nbsp; </p> <p style="font-family: Georgia; font-size: 18px; color: #21343f; line-height: 35px;"> We hope this month has been a transformative and enriching experience for you with the Shambhavi Mahamudra Kriya offered to you by Sadhguru and wish you a beautiful inner journey! </p> <p style="font-family: Georgia,Arial, Helvetica; font-size: 18px; color: #21343f; line-height: 30px;">To receive local centre updates including daily quotes and weekly videos via WhatsApp broadcast, save the number &ldquo;<a href="whatsapp://send?text=Subscribe" data-action="share/whatsapp/share">+852 5920 0385</a>&rdquo; in your phonebook and send &ldquo;<strong>Subscribe</strong>&rdquo; via Whatsapp. <br /><br/> </p> <p style="font-family: Georgia,Arial, Helvetica; font-size: 18px; color: #21343f; line-height: 30px;"> With joy,<br /> Isha Hongkong Volunteers <br /> <a style="color: #b9801d;" href="mailto:hongkong@ishafoundation.org"><strong>hongkong@ishafoundation.org</strong></a><br/> <a href="whatsapp://send?text=Subscribe" data-action="share/whatsapp/share">+852 5920 0385</a> </p> <p>&nbsp;</p> </columns> </row> {{> drop-shadow }} <row class="collapse no-vpad"> <columns> <wrapper> <img src="https://storage.googleapis.com/mail-attachments/2017/HK-whatsapp.jpg" alt="Subscribe to WhatsApp Quotes: 5920 0385" /> </wrapper> </columns> </row> {{> drop-shadow }} {{> footer-hk-unsub }} {{> spacer }} </container>
{ "content_hash": "25478c3a5fbd8a6e155be275d9f7b83d", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 533, "avg_line_length": 74.09876543209876, "alnum_prop": 0.6371209596801066, "repo_name": "ishacrm/emails", "id": "0a1f59107a1bd90f6d49fbddd8ad83973c483f36", "size": "6006", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/pages/hk/2017/iyc-mailer.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "16048" }, { "name": "HTML", "bytes": "4520612" }, { "name": "JavaScript", "bytes": "4418" } ], "symlink_target": "" }
{-# OPTIONS_GHC -fno-warn-type-defaults #-} import Data.Foldable (for_) import Test.Hspec (Spec, describe, it, shouldBe) import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith) import PrimeFactors (primeFactors) main :: IO () main = hspecWith defaultConfig {configFastFail = True} specs specs :: Spec specs = describe "primeFactors" $ for_ cases test where test (description, n, expected) = it description assertion where assertion = primeFactors n `shouldBe` expected cases = [ ("no factors", 1, [] ) , ("prime number", 2, [2] ) , ("square of a prime", 9, [3, 3] ) , ("cube of a prime", 8, [2, 2, 2] ) , ("product of primes and non-primes", 12, [2, 2, 3] ) , ("product of primes", 901255, [5, 17, 23, 461] ) , ("factors include a large prime", 93819012551, [11, 9539, 894119] ) ]
{ "content_hash": "ebcf183d4533060a28660d7eceef6db4", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 83, "avg_line_length": 42.15384615384615, "alnum_prop": 0.49178832116788324, "repo_name": "c19/Exercism-Haskell", "id": "878f84d2d70d633fea22962b2d7299b56c2cff83", "size": "1096", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "prime-factors/test/Tests.hs", "mode": "33188", "license": "mit", "language": [ { "name": "Haskell", "bytes": "161692" } ], "symlink_target": "" }
<?php class FileStorageUtils { /** * Gaufrette Vendor Classloader * * @param string $class Classname to be loaded * @return void */ public static function gaufretteLoader($class) { $base = Configure::read('FileStorage.GaufretteLib'); if (empty($base)) { $base = CakePlugin::path('FileStorage') . 'Vendor' . DS . 'Gaufrette' . DS . 'src' . DS; } $class = str_replace('\\', DS, $class); if (file_exists($base . $class . '.php')) { include ($base . $class . '.php'); } } /** * Return file extension from a given filename * * @param string * @return boolean string or false */ public static function fileExtension($name) { $list = explode('.', $name); if (count($list) > 1) { $ext = $list[count($list) - 1]; return $ext; } return false; } /** * Builds a semi-random path based on a given string to avoid having thousands of files * or directories in one directory. This would result in a slowdown on most file systems. * * Works up to 5 level deep * * @throws InvalidArgumentException * @param mixed $string * @param integer $level 1 to 5 * @return mixed */ public static function randomPath($string, $level = 3) { if (!$string) { throw new \InvalidArgumentException('First argument is not a string!'); } $string = crc32($string); $decrement = 0; $path = null; for ($i = 0; $i < $level; $i++) { $decrement = $decrement - 2; $path .= sprintf("%02d" . DS, substr(str_pad('', 2 * $level, '0') . $string, $decrement, 2)); } return $path; } /** * Helper method to trim last trailing slash in file path * * @param string $path Path to trim * @return string Trimmed path */ public static function trimPath($path) { $len = strlen($path); if ($path[$len - 1] == '\\' || $path[$len - 1] == '/') { $path = substr($path, 0, $len - 1); } return $path; } /** * Converts windows to linux pathes and vice versa * * @param string * @return string */ public static function normalizePath($string) { if (DS == '\\') { return str_replace('/', '\\', $string); } else { return str_replace('\\', '/', $string); } } /** * Method to normalize the annoying inconsistency of the $_FILE array structure * * @link http://www.php.net/manual/en/features.file-upload.multiple.php#109437 * @return array Empty array if $_FILE is empty, if not normalize array of Filedata.{n} */ public static function normalizeGlobalFilesArray($array = null) { if (empty($array)) { $array = $_FILES; } $newfiles = array(); if (!empty($array)) { foreach ($array as $fieldname => $fieldvalue) { foreach ($fieldvalue as $paramname => $paramvalue) { foreach ((array)$paramvalue as $index => $value) { $newfiles[$fieldname][$index][$paramname] = $value; } } } } return $newfiles; } public static function detectModelByFileType ($mime_type) { if(empty($mime_type)) return false; $ext = array_search($mime_type, self::getMimeTypes()); $models = App::objects('FileStorage.Model'); foreach ($models as $model) { $model = explode(".", $model); $model = isset($model[1]) ? $model[1] : $model[0]; App::uses($model, 'FileStorage.Model'); $Model = new $model(); // mp4 is returning null, it should return VideoStorage (ImageStorage is working) if(isset($Model->actsAs['FileStorage.UploadValidator']['allowedExtensions']) && !empty($Model->actsAs['FileStorage.UploadValidator']['allowedExtensions'])) { if(array_search($ext, $Model->actsAs['FileStorage.UploadValidator']['allowedExtensions']) !== false) { return $model; } } } return false; } public static function getMimeTypes() { return array( '123' => 'application/vnd.lotus-1-2-3', '3dml' => 'text/vnd.in3d.3dml', '3ds' => 'image/x-3ds', '3g2' => 'video/3gpp2', '3gp' => 'video/3gpp', '7z' => 'application/x-7z-compressed', 'aab' => 'application/x-authorware-bin', 'aac' => 'audio/x-aac', 'aam' => 'application/x-authorware-map', 'aas' => 'application/x-authorware-seg', 'abw' => 'application/x-abiword', 'ac' => 'application/pkix-attr-cert', 'acc' => 'application/vnd.americandynamics.acc', 'ace' => 'application/x-ace-compressed', 'acu' => 'application/vnd.acucobol', 'acutc' => 'application/vnd.acucorp', 'adp' => 'audio/adpcm', 'aep' => 'application/vnd.audiograph', 'afm' => 'application/x-font-type1', 'afp' => 'application/vnd.ibm.modcap', 'ahead' => 'application/vnd.ahead.space', 'ai' => 'application/postscript', 'aif' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff', 'aiff' => 'audio/x-aiff', 'air' => 'application/vnd.adobe.air-application-installer-package+zip', 'ait' => 'application/vnd.dvb.ait', 'ami' => 'application/vnd.amiga.ami', 'apk' => 'application/vnd.android.package-archive', 'appcache' => 'text/cache-manifest', 'application' => 'application/x-ms-application', 'apr' => 'application/vnd.lotus-approach', 'arc' => 'application/x-freearc', 'asc' => 'application/pgp-signature', 'asf' => 'video/x-ms-asf', 'asm' => 'text/x-asm', 'aso' => 'application/vnd.accpac.simply.aso', 'asx' => 'video/x-ms-asf', 'atc' => 'application/vnd.acucorp', 'atom' => 'application/atom+xml', 'atomcat' => 'application/atomcat+xml', 'atomsvc' => 'application/atomsvc+xml', 'atx' => 'application/vnd.antix.game-component', 'au' => 'audio/basic', 'avi' => 'video/x-msvideo', 'aw' => 'application/applixware', 'azf' => 'application/vnd.airzip.filesecure.azf', 'azs' => 'application/vnd.airzip.filesecure.azs', 'azw' => 'application/vnd.amazon.ebook', 'bat' => 'application/x-msdownload', 'bcpio' => 'application/x-bcpio', 'bdf' => 'application/x-font-bdf', 'bdm' => 'application/vnd.syncml.dm+wbxml', 'bed' => 'application/vnd.realvnc.bed', 'bh2' => 'application/vnd.fujitsu.oasysprs', 'bin' => 'application/octet-stream', 'blb' => 'application/x-blorb', 'blorb' => 'application/x-blorb', 'bmi' => 'application/vnd.bmi', 'bmp' => 'image/x-ms-bmp', 'book' => 'application/vnd.framemaker', 'box' => 'application/vnd.previewsystems.box', 'boz' => 'application/x-bzip2', 'bpk' => 'application/octet-stream', 'btif' => 'image/prs.btif', 'buffer' => 'application/octet-stream', 'bz' => 'application/x-bzip', 'bz2' => 'application/x-bzip2', 'c' => 'text/x-c', 'c11amc' => 'application/vnd.cluetrust.cartomobile-config', 'c11amz' => 'application/vnd.cluetrust.cartomobile-config-pkg', 'c4d' => 'application/vnd.clonk.c4group', 'c4f' => 'application/vnd.clonk.c4group', 'c4g' => 'application/vnd.clonk.c4group', 'c4p' => 'application/vnd.clonk.c4group', 'c4u' => 'application/vnd.clonk.c4group', 'cab' => 'application/vnd.ms-cab-compressed', 'caf' => 'audio/x-caf', 'cap' => 'application/vnd.tcpdump.pcap', 'car' => 'application/vnd.curl.car', 'cat' => 'application/vnd.ms-pki.seccat', 'cb7' => 'application/x-cbr', 'cba' => 'application/x-cbr', 'cbr' => 'application/x-cbr', 'cbt' => 'application/x-cbr', 'cbz' => 'application/x-cbr', 'cc' => 'text/x-c', 'cct' => 'application/x-director', 'ccxml' => 'application/ccxml+xml', 'cdbcmsg' => 'application/vnd.contact.cmsg', 'cdf' => 'application/x-netcdf', 'cdkey' => 'application/vnd.mediastation.cdkey', 'cdmia' => 'application/cdmi-capability', 'cdmic' => 'application/cdmi-container', 'cdmid' => 'application/cdmi-domain', 'cdmio' => 'application/cdmi-object', 'cdmiq' => 'application/cdmi-queue', 'cdx' => 'chemical/x-cdx', 'cdxml' => 'application/vnd.chemdraw+xml', 'cdy' => 'application/vnd.cinderella', 'cer' => 'application/pkix-cert', 'cfs' => 'application/x-cfs-compressed', 'cgm' => 'image/cgm', 'chat' => 'application/x-chat', 'chm' => 'application/vnd.ms-htmlhelp', 'chrt' => 'application/vnd.kde.kchart', 'cif' => 'chemical/x-cif', 'cii' => 'application/vnd.anser-web-certificate-issue-initiation', 'cil' => 'application/vnd.ms-artgalry', 'cla' => 'application/vnd.claymore', 'class' => 'application/java-vm', 'clkk' => 'application/vnd.crick.clicker.keyboard', 'clkp' => 'application/vnd.crick.clicker.palette', 'clkt' => 'application/vnd.crick.clicker.template', 'clkw' => 'application/vnd.crick.clicker.wordbank', 'clkx' => 'application/vnd.crick.clicker', 'clp' => 'application/x-msclip', 'cmc' => 'application/vnd.cosmocaller', 'cmdf' => 'chemical/x-cmdf', 'cml' => 'chemical/x-cml', 'cmp' => 'application/vnd.yellowriver-custom-menu', 'cmx' => 'image/x-cmx', 'cod' => 'application/vnd.rim.cod', 'com' => 'application/x-msdownload', 'conf' => 'text/plain', 'cpio' => 'application/x-cpio', 'cpp' => 'text/x-c', 'cpt' => 'application/mac-compactpro', 'crd' => 'application/x-mscardfile', 'crl' => 'application/pkix-crl', 'crt' => 'application/x-x509-ca-cert', 'crx' => 'application/x-chrome-extension', 'cryptonote' => 'application/vnd.rig.cryptonote', 'csh' => 'application/x-csh', 'csml' => 'chemical/x-csml', 'csp' => 'application/vnd.commonspace', 'css' => 'text/css', 'cst' => 'application/x-director', 'csv' => 'text/csv', 'cu' => 'application/cu-seeme', 'curl' => 'text/vnd.curl', 'cww' => 'application/prs.cww', 'cxt' => 'application/x-director', 'cxx' => 'text/x-c', 'dae' => 'model/vnd.collada+xml', 'daf' => 'application/vnd.mobius.daf', 'dart' => 'application/vnd.dart', 'dataless' => 'application/vnd.fdsn.seed', 'davmount' => 'application/davmount+xml', 'dbk' => 'application/docbook+xml', 'dcr' => 'application/x-director', 'dcurl' => 'text/vnd.curl.dcurl', 'dd2' => 'application/vnd.oma.dd2+xml', 'ddd' => 'application/vnd.fujixerox.ddd', 'deb' => 'application/x-debian-package', 'def' => 'text/plain', 'deploy' => 'application/octet-stream', 'der' => 'application/x-x509-ca-cert', 'dfac' => 'application/vnd.dreamfactory', 'dgc' => 'application/x-dgc-compressed', 'dic' => 'text/x-c', 'dir' => 'application/x-director', 'dis' => 'application/vnd.mobius.dis', 'dist' => 'application/octet-stream', 'distz' => 'application/octet-stream', 'djv' => 'image/vnd.djvu', 'djvu' => 'image/vnd.djvu', 'dll' => 'application/x-msdownload', 'dmg' => 'application/x-apple-diskimage', 'dmp' => 'application/vnd.tcpdump.pcap', 'dms' => 'application/octet-stream', 'dna' => 'application/vnd.dna', 'doc' => 'application/msword', 'docm' => 'application/vnd.ms-word.document.macroenabled.12', 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'dot' => 'application/msword', 'dotm' => 'application/vnd.ms-word.template.macroenabled.12', 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'dp' => 'application/vnd.osgi.dp', 'dpg' => 'application/vnd.dpgraph', 'dra' => 'audio/vnd.dra', 'dsc' => 'text/prs.lines.tag', 'dssc' => 'application/dssc+der', 'dtb' => 'application/x-dtbook+xml', 'dtd' => 'application/xml-dtd', 'dts' => 'audio/vnd.dts', 'dtshd' => 'audio/vnd.dts.hd', 'dump' => 'application/octet-stream', 'dvb' => 'video/vnd.dvb.file', 'dvi' => 'application/x-dvi', 'dwf' => 'model/vnd.dwf', 'dwg' => 'image/vnd.dwg', 'dxf' => 'image/vnd.dxf', 'dxp' => 'application/vnd.spotfire.dxp', 'dxr' => 'application/x-director', 'ecelp4800' => 'audio/vnd.nuera.ecelp4800', 'ecelp7470' => 'audio/vnd.nuera.ecelp7470', 'ecelp9600' => 'audio/vnd.nuera.ecelp9600', 'ecma' => 'application/ecmascript', 'edm' => 'application/vnd.novadigm.edm', 'edx' => 'application/vnd.novadigm.edx', 'efif' => 'application/vnd.picsel', 'ei6' => 'application/vnd.pg.osasli', 'elc' => 'application/octet-stream', 'emf' => 'application/x-msmetafile', 'eml' => 'message/rfc822', 'emma' => 'application/emma+xml', 'emz' => 'application/x-msmetafile', 'eol' => 'audio/vnd.digital-winds', 'eot' => 'application/vnd.ms-fontobject', 'eps' => 'application/postscript', 'epub' => 'application/epub+zip', 'es3' => 'application/vnd.eszigno3+xml', 'esa' => 'application/vnd.osgi.subsystem', 'esf' => 'application/vnd.epson.esf', 'et3' => 'application/vnd.eszigno3+xml', 'etx' => 'text/x-setext', 'eva' => 'application/x-eva', 'event-stream' => 'text/event-stream', 'evy' => 'application/x-envoy', 'exe' => 'application/x-msdownload', 'exi' => 'application/exi', 'ext' => 'application/vnd.novadigm.ext', 'ez' => 'application/andrew-inset', 'ez2' => 'application/vnd.ezpix-album', 'ez3' => 'application/vnd.ezpix-package', 'f' => 'text/x-fortran', 'f4v' => 'video/x-f4v', 'f77' => 'text/x-fortran', 'f90' => 'text/x-fortran', 'fbs' => 'image/vnd.fastbidsheet', 'fcdt' => 'application/vnd.adobe.formscentral.fcdt', 'fcs' => 'application/vnd.isac.fcs', 'fdf' => 'application/vnd.fdf', 'fe_launch' => 'application/vnd.denovo.fcselayout-link', 'fg5' => 'application/vnd.fujitsu.oasysgp', 'fgd' => 'application/x-director', 'fh' => 'image/x-freehand', 'fh4' => 'image/x-freehand', 'fh5' => 'image/x-freehand', 'fh7' => 'image/x-freehand', 'fhc' => 'image/x-freehand', 'fig' => 'application/x-xfig', 'flac' => 'audio/flac', 'fli' => 'video/x-fli', 'flo' => 'application/vnd.micrografx.flo', 'flv' => 'video/x-flv', 'flw' => 'application/vnd.kde.kivio', 'flx' => 'text/vnd.fmi.flexstor', 'fly' => 'text/vnd.fly', 'fm' => 'application/vnd.framemaker', 'fnc' => 'application/vnd.frogans.fnc', 'for' => 'text/x-fortran', 'fpx' => 'image/vnd.fpx', 'frame' => 'application/vnd.framemaker', 'fsc' => 'application/vnd.fsc.weblaunch', 'fst' => 'image/vnd.fst', 'ftc' => 'application/vnd.fluxtime.clip', 'fti' => 'application/vnd.anser-web-funds-transfer-initiation', 'fvt' => 'video/vnd.fvt', 'fxp' => 'application/vnd.adobe.fxp', 'fxpl' => 'application/vnd.adobe.fxp', 'fzs' => 'application/vnd.fuzzysheet', 'g2w' => 'application/vnd.geoplan', 'g3' => 'image/g3fax', 'g3w' => 'application/vnd.geospace', 'gac' => 'application/vnd.groove-account', 'gam' => 'application/x-tads', 'gbr' => 'application/rpki-ghostbusters', 'gca' => 'application/x-gca-compressed', 'gdl' => 'model/vnd.gdl', 'geo' => 'application/vnd.dynageo', 'gex' => 'application/vnd.geometry-explorer', 'ggb' => 'application/vnd.geogebra.file', 'ggt' => 'application/vnd.geogebra.tool', 'ghf' => 'application/vnd.groove-help', 'gif' => 'image/gif', 'gim' => 'application/vnd.groove-identity-message', 'gml' => 'application/gml+xml', 'gmx' => 'application/vnd.gmx', 'gnumeric' => 'application/x-gnumeric', 'gph' => 'application/vnd.flographit', 'gpx' => 'application/gpx+xml', 'gqf' => 'application/vnd.grafeq', 'gqs' => 'application/vnd.grafeq', 'gram' => 'application/srgs', 'gramps' => 'application/x-gramps-xml', 'gre' => 'application/vnd.geometry-explorer', 'grv' => 'application/vnd.groove-injector', 'grxml' => 'application/srgs+xml', 'gsf' => 'application/x-font-ghostscript', 'gtar' => 'application/x-gtar', 'gtm' => 'application/vnd.groove-tool-message', 'gtw' => 'model/vnd.gtw', 'gv' => 'text/vnd.graphviz', 'gxf' => 'application/gxf', 'gxt' => 'application/vnd.geonext', 'h' => 'text/x-c', 'h261' => 'video/h261', 'h263' => 'video/h263', 'h264' => 'video/h264', 'hal' => 'application/vnd.hal+xml', 'hbci' => 'application/vnd.hbci', 'hdf' => 'application/x-hdf', 'hh' => 'text/x-c', 'hlp' => 'application/winhlp', 'hpgl' => 'application/vnd.hp-hpgl', 'hpid' => 'application/vnd.hp-hpid', 'hps' => 'application/vnd.hp-hps', 'hqx' => 'application/mac-binhex40', 'htc' => 'text/x-component', 'htke' => 'application/vnd.kenameaapp', 'htm' => 'text/html', 'html' => 'text/html', 'hvd' => 'application/vnd.yamaha.hv-dic', 'hvp' => 'application/vnd.yamaha.hv-voice', 'hvs' => 'application/vnd.yamaha.hv-script', 'i2g' => 'application/vnd.intergeo', 'icc' => 'application/vnd.iccprofile', 'ice' => 'x-conference/x-cooltalk', 'icm' => 'application/vnd.iccprofile', 'ico' => 'image/x-icon', 'ics' => 'text/calendar', 'ief' => 'image/ief', 'ifb' => 'text/calendar', 'ifm' => 'application/vnd.shana.informed.formdata', 'iges' => 'model/iges', 'igl' => 'application/vnd.igloader', 'igm' => 'application/vnd.insors.igm', 'igs' => 'model/iges', 'igx' => 'application/vnd.micrografx.igx', 'iif' => 'application/vnd.shana.informed.interchange', 'imp' => 'application/vnd.accpac.simply.imp', 'ims' => 'application/vnd.ms-ims', 'in' => 'text/plain', 'ink' => 'application/inkml+xml', 'inkml' => 'application/inkml+xml', 'install' => 'application/x-install-instructions', 'iota' => 'application/vnd.astraea-software.iota', 'ipfix' => 'application/ipfix', 'ipk' => 'application/vnd.shana.informed.package', 'irm' => 'application/vnd.ibm.rights-management', 'irp' => 'application/vnd.irepository.package+xml', 'iso' => 'application/x-iso9660-image', 'itp' => 'application/vnd.shana.informed.formtemplate', 'ivp' => 'application/vnd.immervision-ivp', 'ivu' => 'application/vnd.immervision-ivu', 'jad' => 'text/vnd.sun.j2me.app-descriptor', 'jam' => 'application/vnd.jam', 'jar' => 'application/java-archive', 'java' => 'text/x-java-source', 'jisp' => 'application/vnd.jisp', 'jlt' => 'application/vnd.hp-jlyt', 'jnlp' => 'application/x-java-jnlp-file', 'joda' => 'application/vnd.joost.joda-archive', 'jpg' => 'image/jpeg', 'jpgm' => 'video/jpm', 'jpgv' => 'video/jpeg', 'jpm' => 'video/jpm', 'js' => 'application/javascript', 'json' => 'application/json', 'jsonml' => 'application/jsonml+json', 'kar' => 'audio/midi', 'karbon' => 'application/vnd.kde.karbon', 'kfo' => 'application/vnd.kde.kformula', 'kia' => 'application/vnd.kidspiration', 'kml' => 'application/vnd.google-earth.kml+xml', 'kmz' => 'application/vnd.google-earth.kmz', 'kne' => 'application/vnd.kinar', 'knp' => 'application/vnd.kinar', 'kon' => 'application/vnd.kde.kontour', 'kpr' => 'application/vnd.kde.kpresenter', 'kpt' => 'application/vnd.kde.kpresenter', 'kpxx' => 'application/vnd.ds-keypoint', 'ksp' => 'application/vnd.kde.kspread', 'ktr' => 'application/vnd.kahootz', 'ktx' => 'image/ktx', 'ktz' => 'application/vnd.kahootz', 'kwd' => 'application/vnd.kde.kword', 'kwt' => 'application/vnd.kde.kword', 'lasxml' => 'application/vnd.las.las+xml', 'latex' => 'application/x-latex', 'lbd' => 'application/vnd.llamagraphics.life-balance.desktop', 'lbe' => 'application/vnd.llamagraphics.life-balance.exchange+xml', 'les' => 'application/vnd.hhe.lesson-player', 'lha' => 'application/x-lzh-compressed', 'link66' => 'application/vnd.route66.link66+xml', 'list' => 'text/plain', 'list3820' => 'application/vnd.ibm.modcap', 'listafp' => 'application/vnd.ibm.modcap', 'lnk' => 'application/x-ms-shortcut', 'log' => 'text/plain', 'lostxml' => 'application/lost+xml', 'lrf' => 'application/octet-stream', 'lrm' => 'application/vnd.ms-lrm', 'ltf' => 'application/vnd.frogans.ltf', 'lua' => 'text/x-lua', 'luac' => 'application/x-lua-bytecode', 'lvp' => 'audio/vnd.lucent.voice', 'lwp' => 'application/vnd.lotus-wordpro', 'lzh' => 'application/x-lzh-compressed', 'm13' => 'application/x-msmediaview', 'm14' => 'application/x-msmediaview', 'm1v' => 'video/mpeg', 'm21' => 'application/mp21', 'm2a' => 'audio/mpeg', 'm2v' => 'video/mpeg', 'm3a' => 'audio/mpeg', 'm3u' => 'audio/x-mpegurl', 'm3u8' => 'application/x-mpegURL', 'm4a' => 'audio/mp4', 'm4p' => 'application/mp4', 'm4u' => 'video/vnd.mpegurl', 'm4v' => 'video/x-m4v', 'ma' => 'application/mathematica', 'mads' => 'application/mads+xml', 'mag' => 'application/vnd.ecowin.chart', 'maker' => 'application/vnd.framemaker', 'man' => 'text/troff', 'manifest' => 'text/cache-manifest', 'mar' => 'application/octet-stream', 'markdown' => 'text/x-markdown', 'mathml' => 'application/mathml+xml', 'mb' => 'application/mathematica', 'mbk' => 'application/vnd.mobius.mbk', 'mbox' => 'application/mbox', 'mc1' => 'application/vnd.medcalcdata', 'mcd' => 'application/vnd.mcd', 'mcurl' => 'text/vnd.curl.mcurl', 'md' => 'text/x-markdown', 'mdb' => 'application/x-msaccess', 'mdi' => 'image/vnd.ms-modi', 'me' => 'text/troff', 'mesh' => 'model/mesh', 'meta4' => 'application/metalink4+xml', 'metalink' => 'application/metalink+xml', 'mets' => 'application/mets+xml', 'mfm' => 'application/vnd.mfmp', 'mft' => 'application/rpki-manifest', 'mgp' => 'application/vnd.osgeo.mapguide.package', 'mgz' => 'application/vnd.proteus.magazine', 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mie' => 'application/x-mie', 'mif' => 'application/vnd.mif', 'mime' => 'message/rfc822', 'mj2' => 'video/mj2', 'mjp2' => 'video/mj2', 'mk3d' => 'video/x-matroska', 'mka' => 'audio/x-matroska', 'mkd' => 'text/x-markdown', 'mks' => 'video/x-matroska', 'mkv' => 'video/x-matroska', 'mlp' => 'application/vnd.dolby.mlp', 'mmd' => 'application/vnd.chipnuts.karaoke-mmd', 'mmf' => 'application/vnd.smaf', 'mmr' => 'image/vnd.fujixerox.edmics-mmr', 'mng' => 'video/x-mng', 'mny' => 'application/x-msmoney', 'mobi' => 'application/x-mobipocket-ebook', 'mods' => 'application/mods+xml', 'mov' => 'video/quicktime', 'movie' => 'video/x-sgi-movie', 'mp2' => 'audio/mpeg', 'mp21' => 'application/mp21', 'mp2a' => 'audio/mpeg', 'mp3' => 'audio/mp3', 'mp4' => 'video/mp4', 'mp4a' => 'audio/mp4', 'mp4s' => 'application/mp4', 'mp4v' => 'video/mp4', 'mpc' => 'application/vnd.mophun.certificate', 'mpe' => 'video/mpeg', 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mpg4' => 'video/mp4', 'mpga' => 'audio/mpeg', 'mpkg' => 'application/vnd.apple.installer+xml', 'mpm' => 'application/vnd.blueice.multipass', 'mpn' => 'application/vnd.mophun.application', 'mpp' => 'application/vnd.ms-project', 'mpt' => 'application/vnd.ms-project', 'mpy' => 'application/vnd.ibm.minipay', 'mqy' => 'application/vnd.mobius.mqy', 'mrc' => 'application/marc', 'mrcx' => 'application/marcxml+xml', 'ms' => 'text/troff', 'mscml' => 'application/mediaservercontrol+xml', 'mseed' => 'application/vnd.fdsn.mseed', 'mseq' => 'application/vnd.mseq', 'msf' => 'application/vnd.epson.msf', 'msh' => 'model/mesh', 'msi' => 'application/x-msdownload', 'msl' => 'application/vnd.mobius.msl', 'msty' => 'application/vnd.muvee.style', 'mts' => 'model/vnd.mts', 'mus' => 'application/vnd.musician', 'musicxml' => 'application/vnd.recordare.musicxml+xml', 'mvb' => 'application/x-msmediaview', 'mwf' => 'application/vnd.mfer', 'mxf' => 'application/mxf', 'mxl' => 'application/vnd.recordare.musicxml', 'mxml' => 'application/xv+xml', 'mxs' => 'application/vnd.triscape.mxs', 'mxu' => 'video/vnd.mpegurl', 'n-gage' => 'application/vnd.nokia.n-gage.symbian.install', 'n3' => 'text/n3', 'nb' => 'application/mathematica', 'nbp' => 'application/vnd.wolfram.player', 'nc' => 'application/x-netcdf', 'ncx' => 'application/x-dtbncx+xml', 'nfo' => 'text/x-nfo', 'ngdat' => 'application/vnd.nokia.n-gage.data', 'nitf' => 'application/vnd.nitf', 'nlu' => 'application/vnd.neurolanguage.nlu', 'nml' => 'application/vnd.enliven', 'nnd' => 'application/vnd.noblenet-directory', 'nns' => 'application/vnd.noblenet-sealer', 'nnw' => 'application/vnd.noblenet-web', 'npx' => 'image/vnd.net-fpx', 'nsc' => 'application/x-conference', 'nsf' => 'application/vnd.lotus-notes', 'ntf' => 'application/vnd.nitf', 'nzb' => 'application/x-nzb', 'oa2' => 'application/vnd.fujitsu.oasys2', 'oa3' => 'application/vnd.fujitsu.oasys3', 'oas' => 'application/vnd.fujitsu.oasys', 'obd' => 'application/x-msbinder', 'obj' => 'application/x-tgif', 'oda' => 'application/oda', 'odb' => 'application/vnd.oasis.opendocument.database', 'odc' => 'application/vnd.oasis.opendocument.chart', 'odf' => 'application/vnd.oasis.opendocument.formula', 'odft' => 'application/vnd.oasis.opendocument.formula-template', 'odg' => 'application/vnd.oasis.opendocument.graphics', 'odi' => 'application/vnd.oasis.opendocument.image', 'odm' => 'application/vnd.oasis.opendocument.text-master', 'odp' => 'application/vnd.oasis.opendocument.presentation', 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', 'odt' => 'application/vnd.oasis.opendocument.text', 'oga' => 'audio/ogg', 'ogg' => 'audio/ogg', 'ogv' => 'video/ogg', 'ogx' => 'application/ogg', 'omdoc' => 'application/omdoc+xml', 'onepkg' => 'application/onenote', 'onetmp' => 'application/onenote', 'onetoc' => 'application/onenote', 'onetoc2' => 'application/onenote', 'opf' => 'application/oebps-package+xml', 'opml' => 'text/x-opml', 'oprc' => 'application/vnd.palm', 'org' => 'application/vnd.lotus-organizer', 'osf' => 'application/vnd.yamaha.openscoreformat', 'osfpvg' => 'application/vnd.yamaha.openscoreformat.osfpvg+xml', 'otc' => 'application/vnd.oasis.opendocument.chart-template', 'otf' => 'font/opentype', 'otg' => 'application/vnd.oasis.opendocument.graphics-template', 'oth' => 'application/vnd.oasis.opendocument.text-web', 'oti' => 'application/vnd.oasis.opendocument.image-template', 'otp' => 'application/vnd.oasis.opendocument.presentation-template', 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template', 'ott' => 'application/vnd.oasis.opendocument.text-template', 'oxps' => 'application/oxps', 'oxt' => 'application/vnd.openofficeorg.extension', 'p' => 'text/x-pascal', 'p10' => 'application/pkcs10', 'p12' => 'application/x-pkcs12', 'p7b' => 'application/x-pkcs7-certificates', 'p7c' => 'application/pkcs7-mime', 'p7m' => 'application/pkcs7-mime', 'p7r' => 'application/x-pkcs7-certreqresp', 'p7s' => 'application/pkcs7-signature', 'p8' => 'application/pkcs8', 'pas' => 'text/x-pascal', 'paw' => 'application/vnd.pawaafile', 'pbd' => 'application/vnd.powerbuilder6', 'pbm' => 'image/x-portable-bitmap', 'pcap' => 'application/vnd.tcpdump.pcap', 'pcf' => 'application/x-font-pcf', 'pcl' => 'application/vnd.hp-pcl', 'pclxl' => 'application/vnd.hp-pclxl', 'pct' => 'image/x-pict', 'pcurl' => 'application/vnd.curl.pcurl', 'pcx' => 'image/x-pcx', 'pdb' => 'application/vnd.palm', 'pdf' => 'application/pdf', 'pfa' => 'application/x-font-type1', 'pfb' => 'application/x-font-type1', 'pfm' => 'application/x-font-type1', 'pfr' => 'application/font-tdpfr', 'pfx' => 'application/x-pkcs12', 'pgm' => 'image/x-portable-graymap', 'pgn' => 'application/x-chess-pgn', 'pgp' => 'application/pgp-encrypted', 'pic' => 'image/x-pict', 'pkg' => 'application/octet-stream', 'pki' => 'application/pkixcmp', 'pkipath' => 'application/pkix-pkipath', 'plb' => 'application/vnd.3gpp.pic-bw-large', 'plc' => 'application/vnd.mobius.plc', 'plf' => 'application/vnd.pocketlearn', 'pls' => 'application/pls+xml', 'pml' => 'application/vnd.ctc-posml', 'png' => 'image/png', 'pnm' => 'image/x-portable-anymap', 'portpkg' => 'application/vnd.macports.portpkg', 'pot' => 'application/vnd.ms-powerpoint', 'potm' => 'application/vnd.ms-powerpoint.template.macroenabled.12', 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', 'ppam' => 'application/vnd.ms-powerpoint.addin.macroenabled.12', 'ppd' => 'application/vnd.cups-ppd', 'ppm' => 'image/x-portable-pixmap', 'pps' => 'application/vnd.ms-powerpoint', 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroenabled.12', 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'ppt' => 'application/vnd.ms-powerpoint', 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroenabled.12', 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'pqa' => 'application/vnd.palm', 'prc' => 'application/x-mobipocket-ebook', 'pre' => 'application/vnd.lotus-freelance', 'prf' => 'application/pics-rules', 'ps' => 'application/postscript', 'psb' => 'application/vnd.3gpp.pic-bw-small', 'psd' => 'image/vnd.adobe.photoshop', 'psf' => 'application/x-font-linux-psf', 'pskcxml' => 'application/pskc+xml', 'ptid' => 'application/vnd.pvi.ptid1', 'pub' => 'application/x-mspublisher', 'pvb' => 'application/vnd.3gpp.pic-bw-var', 'pwn' => 'application/vnd.3m.post-it-notes', 'pya' => 'audio/vnd.ms-playready.media.pya', 'pyv' => 'video/vnd.ms-playready.media.pyv', 'qam' => 'application/vnd.epson.quickanime', 'qbo' => 'application/vnd.intu.qbo', 'qfx' => 'application/vnd.intu.qfx', 'qps' => 'application/vnd.publishare-delta-tree', 'qt' => 'video/quicktime', 'qwd' => 'application/vnd.quark.quarkxpress', 'qwt' => 'application/vnd.quark.quarkxpress', 'qxb' => 'application/vnd.quark.quarkxpress', 'qxd' => 'application/vnd.quark.quarkxpress', 'qxl' => 'application/vnd.quark.quarkxpress', 'qxt' => 'application/vnd.quark.quarkxpress', 'ra' => 'audio/x-pn-realaudio', 'ram' => 'audio/x-pn-realaudio', 'rar' => 'application/x-rar-compressed', 'ras' => 'image/x-cmu-raster', 'rcprofile' => 'application/vnd.ipunplugged.rcprofile', 'rdf' => 'application/rdf+xml', 'rdz' => 'application/vnd.data-vision.rdz', 'rep' => 'application/vnd.businessobjects', 'res' => 'application/x-dtbresource+xml', 'rgb' => 'image/x-rgb', 'rif' => 'application/reginfo+xml', 'rip' => 'audio/vnd.rip', 'ris' => 'application/x-research-info-systems', 'rl' => 'application/resource-lists+xml', 'rlc' => 'image/vnd.fujixerox.edmics-rlc', 'rld' => 'application/resource-lists-diff+xml', 'rm' => 'application/vnd.rn-realmedia', 'rmi' => 'audio/midi', 'rmp' => 'audio/x-pn-realaudio-plugin', 'rms' => 'application/vnd.jcp.javame.midlet-rms', 'rmvb' => 'application/vnd.rn-realmedia-vbr', 'rnc' => 'application/relax-ng-compact-syntax', 'roa' => 'application/rpki-roa', 'roff' => 'text/troff', 'rp9' => 'application/vnd.cloanto.rp9', 'rpss' => 'application/vnd.nokia.radio-presets', 'rpst' => 'application/vnd.nokia.radio-preset', 'rq' => 'application/sparql-query', 'rs' => 'application/rls-services+xml', 'rsd' => 'application/rsd+xml', 'rss' => 'application/rss+xml', 'rtf' => 'text/rtf', 'rtx' => 'text/richtext', 's' => 'text/x-asm', 's3m' => 'audio/s3m', 'saf' => 'application/vnd.yamaha.smaf-audio', 'sbml' => 'application/sbml+xml', 'sc' => 'application/vnd.ibm.secure-container', 'scd' => 'application/x-msschedule', 'scm' => 'application/vnd.lotus-screencam', 'scq' => 'application/scvp-cv-request', 'scs' => 'application/scvp-cv-response', 'scurl' => 'text/vnd.curl.scurl', 'sda' => 'application/vnd.stardivision.draw', 'sdc' => 'application/vnd.stardivision.calc', 'sdd' => 'application/vnd.stardivision.impress', 'sdkd' => 'application/vnd.solent.sdkm+xml', 'sdkm' => 'application/vnd.solent.sdkm+xml', 'sdp' => 'application/sdp', 'sdw' => 'application/vnd.stardivision.writer', 'see' => 'application/vnd.seemail', 'seed' => 'application/vnd.fdsn.seed', 'sema' => 'application/vnd.sema', 'semd' => 'application/vnd.semd', 'semf' => 'application/vnd.semf', 'ser' => 'application/java-serialized-object', 'setpay' => 'application/set-payment-initiation', 'setreg' => 'application/set-registration-initiation', 'sfd-hdstx' => 'application/vnd.hydrostatix.sof-data', 'sfs' => 'application/vnd.spotfire.sfs', 'sfv' => 'text/x-sfv', 'sgi' => 'image/sgi', 'sgl' => 'application/vnd.stardivision.writer-global', 'sgm' => 'text/sgml', 'sgml' => 'text/sgml', 'sh' => 'application/x-sh', 'shar' => 'application/x-shar', 'shf' => 'application/shf+xml', 'sid' => 'image/x-mrsid-image', 'sig' => 'application/pgp-signature', 'sil' => 'audio/silk', 'silo' => 'model/mesh', 'sis' => 'application/vnd.symbian.install', 'sisx' => 'application/vnd.symbian.install', 'sit' => 'application/x-stuffit', 'sitx' => 'application/x-stuffitx', 'skd' => 'application/vnd.koan', 'skm' => 'application/vnd.koan', 'skp' => 'application/vnd.koan', 'skt' => 'application/vnd.koan', 'sldm' => 'application/vnd.ms-powerpoint.slide.macroenabled.12', 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', 'slt' => 'application/vnd.epson.salt', 'sm' => 'application/vnd.stepmania.stepchart', 'smf' => 'application/vnd.stardivision.math', 'smi' => 'application/smil+xml', 'smil' => 'application/smil+xml', 'smv' => 'video/x-smv', 'smzip' => 'application/vnd.stepmania.package', 'snd' => 'audio/basic', 'snf' => 'application/x-font-snf', 'so' => 'application/octet-stream', 'spc' => 'application/x-pkcs7-certificates', 'spf' => 'application/vnd.yamaha.smaf-phrase', 'spl' => 'application/x-futuresplash', 'spot' => 'text/vnd.in3d.spot', 'spp' => 'application/scvp-vp-response', 'spq' => 'application/scvp-vp-request', 'spx' => 'audio/ogg', 'sql' => 'application/x-sql', 'src' => 'application/x-wais-source', 'srt' => 'application/x-subrip', 'sru' => 'application/sru+xml', 'srx' => 'application/sparql-results+xml', 'ssdl' => 'application/ssdl+xml', 'sse' => 'application/vnd.kodak-descriptor', 'ssf' => 'application/vnd.epson.ssf', 'ssml' => 'application/ssml+xml', 'st' => 'application/vnd.sailingtracker.track', 'stc' => 'application/vnd.sun.xml.calc.template', 'std' => 'application/vnd.sun.xml.draw.template', 'stf' => 'application/vnd.wt.stf', 'sti' => 'application/vnd.sun.xml.impress.template', 'stk' => 'application/hyperstudio', 'stl' => 'application/vnd.ms-pki.stl', 'str' => 'application/vnd.pg.format', 'stw' => 'application/vnd.sun.xml.writer.template', 'sub' => 'text/vnd.dvb.subtitle', 'sus' => 'application/vnd.sus-calendar', 'susp' => 'application/vnd.sus-calendar', 'sv4cpio' => 'application/x-sv4cpio', 'sv4crc' => 'application/x-sv4crc', 'svc' => 'application/vnd.dvb.service', 'svd' => 'application/vnd.svd', 'svg' => 'image/svg+xml', 'svgz' => 'image/svg+xml', 'swa' => 'application/x-director', 'swf' => 'application/x-shockwave-flash', 'swi' => 'application/vnd.aristanetworks.swi', 'sxc' => 'application/vnd.sun.xml.calc', 'sxd' => 'application/vnd.sun.xml.draw', 'sxg' => 'application/vnd.sun.xml.writer.global', 'sxi' => 'application/vnd.sun.xml.impress', 'sxm' => 'application/vnd.sun.xml.math', 'sxw' => 'application/vnd.sun.xml.writer', 't' => 'text/troff', 't3' => 'application/x-t3vm-image', 'taglet' => 'application/vnd.mynfc', 'tao' => 'application/vnd.tao.intent-module-archive', 'tar' => 'application/x-tar', 'tcap' => 'application/vnd.3gpp2.tcap', 'tcl' => 'application/x-tcl', 'teacher' => 'application/vnd.smart.teacher', 'tei' => 'application/tei+xml', 'teicorpus' => 'application/tei+xml', 'tex' => 'application/x-tex', 'texi' => 'application/x-texinfo', 'texinfo' => 'application/x-texinfo', 'text' => 'text/plain', 'tfi' => 'application/thraud+xml', 'tfm' => 'application/x-tex-tfm', 'tga' => 'image/x-tga', 'thmx' => 'application/vnd.ms-officetheme', 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'tmo' => 'application/vnd.tmobile-livetv', 'torrent' => 'application/x-bittorrent', 'tpl' => 'application/vnd.groove-tool-template', 'tpt' => 'application/vnd.trid.tpt', 'tr' => 'text/troff', 'tra' => 'application/vnd.trueapp', 'trm' => 'application/x-msterminal', 'ts' => 'video/MP2T', 'tsd' => 'application/timestamped-data', 'tsv' => 'text/tab-separated-values', 'ttc' => 'application/x-font-ttf', 'ttf' => 'application/x-font-ttf', 'ttl' => 'text/turtle', 'twd' => 'application/vnd.simtech-mindmapper', 'twds' => 'application/vnd.simtech-mindmapper', 'txd' => 'application/vnd.genomatix.tuxedo', 'txf' => 'application/vnd.mobius.txf', 'txt' => 'text/plain', 'u32' => 'application/x-authorware-bin', 'udeb' => 'application/x-debian-package', 'ufd' => 'application/vnd.ufdl', 'ufdl' => 'application/vnd.ufdl', 'ulx' => 'application/x-glulx', 'umj' => 'application/vnd.umajin', 'unityweb' => 'application/vnd.unity', 'uoml' => 'application/vnd.uoml+xml', 'uri' => 'text/uri-list', 'uris' => 'text/uri-list', 'urls' => 'text/uri-list', 'ustar' => 'application/x-ustar', 'utz' => 'application/vnd.uiq.theme', 'uu' => 'text/x-uuencode', 'uva' => 'audio/vnd.dece.audio', 'uvd' => 'application/vnd.dece.data', 'uvf' => 'application/vnd.dece.data', 'uvg' => 'image/vnd.dece.graphic', 'uvh' => 'video/vnd.dece.hd', 'uvi' => 'image/vnd.dece.graphic', 'uvm' => 'video/vnd.dece.mobile', 'uvp' => 'video/vnd.dece.pd', 'uvs' => 'video/vnd.dece.sd', 'uvt' => 'application/vnd.dece.ttml+xml', 'uvu' => 'video/vnd.uvvu.mp4', 'uvv' => 'video/vnd.dece.video', 'uvva' => 'audio/vnd.dece.audio', 'uvvd' => 'application/vnd.dece.data', 'uvvf' => 'application/vnd.dece.data', 'uvvg' => 'image/vnd.dece.graphic', 'uvvh' => 'video/vnd.dece.hd', 'uvvi' => 'image/vnd.dece.graphic', 'uvvm' => 'video/vnd.dece.mobile', 'uvvp' => 'video/vnd.dece.pd', 'uvvs' => 'video/vnd.dece.sd', 'uvvt' => 'application/vnd.dece.ttml+xml', 'uvvu' => 'video/vnd.uvvu.mp4', 'uvvv' => 'video/vnd.dece.video', 'uvvx' => 'application/vnd.dece.unspecified', 'uvvz' => 'application/vnd.dece.zip', 'uvx' => 'application/vnd.dece.unspecified', 'uvz' => 'application/vnd.dece.zip', 'vcard' => 'text/vcard', 'vcd' => 'application/x-cdlink', 'vcf' => 'text/x-vcard', 'vcg' => 'application/vnd.groove-vcard', 'vcs' => 'text/x-vcalendar', 'vcx' => 'application/vnd.vcx', 'vis' => 'application/vnd.visionary', 'viv' => 'video/vnd.vivo', 'vob' => 'video/x-ms-vob', 'vor' => 'application/vnd.stardivision.writer', 'vox' => 'application/x-authorware-bin', 'vrml' => 'model/vrml', 'vsd' => 'application/vnd.visio', 'vsf' => 'application/vnd.vsf', 'vss' => 'application/vnd.visio', 'vst' => 'application/vnd.visio', 'vsw' => 'application/vnd.visio', 'vtt' => 'text/vtt', 'vtu' => 'model/vnd.vtu', 'vxml' => 'application/voicexml+xml', 'w3d' => 'application/x-director', 'wad' => 'application/x-doom', 'wav' => 'audio/x-wav', 'wax' => 'audio/x-ms-wax', 'wbmp' => 'image/vnd.wap.wbmp', 'wbs' => 'application/vnd.criticaltools.wbs+xml', 'wbxml' => 'application/vnd.wap.wbxml', 'wcm' => 'application/vnd.ms-works', 'wdb' => 'application/vnd.ms-works', 'wdp' => 'image/vnd.ms-photo', 'weba' => 'audio/webm', 'webapp' => 'application/x-web-app-manifest+json', 'webm' => 'video/webm', 'webp' => 'image/webp', 'wg' => 'application/vnd.pmi.widget', 'wgt' => 'application/widget', 'wks' => 'application/vnd.ms-works', 'wm' => 'video/x-ms-wm', 'wma' => 'audio/x-ms-wma', 'wmd' => 'application/x-ms-wmd', 'wmf' => 'application/x-msmetafile', 'wml' => 'text/vnd.wap.wml', 'wmlc' => 'application/vnd.wap.wmlc', 'wmls' => 'text/vnd.wap.wmlscript', 'wmlsc' => 'application/vnd.wap.wmlscriptc', 'wmv' => 'video/x-ms-wmv', 'wmx' => 'video/x-ms-wmx', 'wmz' => 'application/x-msmetafile', 'woff' => 'application/x-font-woff', 'wpd' => 'application/vnd.wordperfect', 'wpl' => 'application/vnd.ms-wpl', 'wps' => 'application/vnd.ms-works', 'wqd' => 'application/vnd.wqd', 'wri' => 'application/x-mswrite', 'wrl' => 'model/vrml', 'wsdl' => 'application/wsdl+xml', 'wspolicy' => 'application/wspolicy+xml', 'wtb' => 'application/vnd.webturbo', 'wvx' => 'video/x-ms-wvx', 'x32' => 'application/x-authorware-bin', 'x3d' => 'model/x3d+xml', 'x3db' => 'model/x3d+binary', 'x3dbz' => 'model/x3d+binary', 'x3dv' => 'model/x3d+vrml', 'x3dvz' => 'model/x3d+vrml', 'x3dz' => 'model/x3d+xml', 'xaml' => 'application/xaml+xml', 'xap' => 'application/x-silverlight-app', 'xar' => 'application/vnd.xara', 'xbap' => 'application/x-ms-xbap', 'xbd' => 'application/vnd.fujixerox.docuworks.binder', 'xbm' => 'image/x-xbitmap', 'xdf' => 'application/xcap-diff+xml', 'xdm' => 'application/vnd.syncml.dm+xml', 'xdp' => 'application/vnd.adobe.xdp+xml', 'xdssc' => 'application/dssc+xml', 'xdw' => 'application/vnd.fujixerox.docuworks', 'xenc' => 'application/xenc+xml', 'xer' => 'application/patch-ops-error+xml', 'xfdf' => 'application/vnd.adobe.xfdf', 'xfdl' => 'application/vnd.xfdl', 'xht' => 'application/xhtml+xml', 'xhtml' => 'application/xhtml+xml', 'xhvml' => 'application/xv+xml', 'xif' => 'image/vnd.xiff', 'xla' => 'application/vnd.ms-excel', 'xlam' => 'application/vnd.ms-excel.addin.macroenabled.12', 'xlc' => 'application/vnd.ms-excel', 'xlf' => 'application/x-xliff+xml', 'xlm' => 'application/vnd.ms-excel', 'xls' => 'application/vnd.ms-excel', 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroenabled.12', 'xlsm' => 'application/vnd.ms-excel.sheet.macroenabled.12', 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xlt' => 'application/vnd.ms-excel', 'xltm' => 'application/vnd.ms-excel.template.macroenabled.12', 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'xlw' => 'application/vnd.ms-excel', 'xm' => 'audio/xm', 'xml' => 'application/xml', 'xo' => 'application/vnd.olpc-sugar', 'xop' => 'application/xop+xml', 'xpi' => 'application/x-xpinstall', 'xpl' => 'application/xproc+xml', 'xpm' => 'image/x-xpixmap', 'xpr' => 'application/vnd.is-xpr', 'xps' => 'application/vnd.ms-xpsdocument', 'xpw' => 'application/vnd.intercon.formnet', 'xpx' => 'application/vnd.intercon.formnet', 'xsl' => 'application/xml', 'xslt' => 'application/xslt+xml', 'xsm' => 'application/vnd.syncml+xml', 'xspf' => 'application/xspf+xml', 'xul' => 'application/vnd.mozilla.xul+xml', 'xvm' => 'application/xv+xml', 'xvml' => 'application/xv+xml', 'xwd' => 'image/x-xwindowdump', 'xyz' => 'chemical/x-xyz', 'xz' => 'application/x-xz', 'yang' => 'application/yang', 'yin' => 'application/yin+xml', 'z1' => 'application/x-zmachine', 'z2' => 'application/x-zmachine', 'z3' => 'application/x-zmachine', 'z4' => 'application/x-zmachine', 'z5' => 'application/x-zmachine', 'z6' => 'application/x-zmachine', 'z7' => 'application/x-zmachine', 'z8' => 'application/x-zmachine', 'zaz' => 'application/vnd.zzazz.deck+xml', 'zip' => 'application/zip', 'zip' => 'application/x-zip-compressed', 'zir' => 'application/vnd.zul', 'zirz' => 'application/vnd.zul', 'zmm' => 'application/vnd.handheld-entertainment+xml' ); } }
{ "content_hash": "3aea5e3bd678f34400715eddf27e9043", "timestamp": "", "source": "github", "line_count": 1135, "max_line_length": 160, "avg_line_length": 39.202643171806166, "alnum_prop": 0.5990560737161479, "repo_name": "zuha/FileStorage-Zuha-Cakephp-Plugin", "id": "1354e418ad77f2db67450e15c9e0ea31e948f796", "size": "44646", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Lib/Utility/FileStorageUtils.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "301581" }, { "name": "JavaScript", "bytes": "116" }, { "name": "PHP", "bytes": "215033" } ], "symlink_target": "" }
namespace Microsoft.Azure.CognitiveServices.Vision.Face { using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for PersonGroupOperations. /// </summary> public static partial class PersonGroupOperationsExtensions { /// <summary> /// Create a new person group with specified personGroupId, name, user-provided /// userData and recognitionModel. /// &lt;br /&gt; A person group is the container of the uploaded person data, /// including face recognition features. /// &lt;br /&gt; After creation, use [PersonGroup Person - /// Create](/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f3039523c) /// to add persons into the group, and then call [PersonGroup - /// Train](/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395249) /// to get this group ready for [Face - /// Identify](/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395239). /// &lt;br /&gt; No image will be stored. Only the person's extracted face /// features and userData will be stored on server until [PersonGroup Person - /// Delete](/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f3039523d) /// or [PersonGroup - /// Delete](/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395245) /// is called. /// &lt;br/&gt;'recognitionModel' should be specified to associate with this /// person group. The default value for 'recognitionModel' is 'recognition_01', /// if the latest model needed, please explicitly specify the model you need in /// this parameter. New faces that are added to an existing person group will /// use the recognition model that's already associated with the collection. /// Existing face features in a person group can't be updated to features /// extracted by another version of recognition model. /// * 'recognition_01': The default recognition model for [PersonGroup - /// Create](/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395244). /// All those person groups created before 2019 March are bonded with this /// recognition model. /// * 'recognition_02': Recognition model released in 2019 March. /// 'recognition_02' is recommended since its overall accuracy is improved /// compared with 'recognition_01'. /// /// Person group quota: /// * Free-tier subscription quota: 1,000 person groups. Each holds up to 1,000 /// persons. /// * S0-tier subscription quota: 1,000,000 person groups. Each holds up to /// 10,000 persons. /// * to handle larger scale face identification problem, please consider using /// [LargePersonGroup](/docs/services/563879b61984550e40cbbe8d/operations/599acdee6ac60f11b48b5a9d). /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Id referencing a particular person group. /// </param> /// <param name='name'> /// User defined name, maximum length is 128. /// </param> /// <param name='userData'> /// User specified data. Length should not exceed 16KB. /// </param> /// <param name='recognitionModel'> /// Possible values include: 'recognition_01', 'recognition_02' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CreateAsync(this IPersonGroupOperations operations, string personGroupId, string name = default(string), string userData = default(string), string recognitionModel = default(string), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.CreateWithHttpMessagesAsync(personGroupId, name, userData, recognitionModel, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Delete an existing person group. Persisted face features of all people in /// the person group will also be deleted. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Id referencing a particular person group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IPersonGroupOperations operations, string personGroupId, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(personGroupId, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Retrieve person group name, userData and recognitionModel. To get person /// information under this personGroup, use [PersonGroup Person - /// List](/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395241). /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Id referencing a particular person group. /// </param> /// <param name='returnRecognitionModel'> /// A value indicating whether the operation should return 'recognitionModel' /// in response. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PersonGroup> GetAsync(this IPersonGroupOperations operations, string personGroupId, bool? returnRecognitionModel = false, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(personGroupId, returnRecognitionModel, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Update an existing person group's display name and userData. The properties /// which does not appear in request body will not be updated. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Id referencing a particular person group. /// </param> /// <param name='name'> /// User defined name, maximum length is 128. /// </param> /// <param name='userData'> /// User specified data. Length should not exceed 16KB. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateAsync(this IPersonGroupOperations operations, string personGroupId, string name = default(string), string userData = default(string), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.UpdateWithHttpMessagesAsync(personGroupId, name, userData, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Retrieve the training status of a person group (completed or ongoing). /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Id referencing a particular person group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<TrainingStatus> GetTrainingStatusAsync(this IPersonGroupOperations operations, string personGroupId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetTrainingStatusWithHttpMessagesAsync(personGroupId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// List person groups’ personGroupId, name, userData and /// recognitionModel.&lt;br /&gt; /// * Person groups are stored in alphabetical order of personGroupId. /// * "start" parameter (string, optional) is a user-provided personGroupId /// value that returned entries have larger ids by string comparison. "start" /// set to empty to indicate return from the first item. /// * "top" parameter (int, optional) specifies the number of entries to /// return. A maximal of 1000 entries can be returned in one call. To fetch /// more, you can specify "start" with the last returned entry’s Id of the /// current call. /// &lt;br /&gt; /// For example, total 5 person groups: "group1", ..., "group5". /// &lt;br /&gt; "start=&amp;top=" will return all 5 groups. /// &lt;br /&gt; "start=&amp;top=2" will return "group1", "group2". /// &lt;br /&gt; "start=group2&amp;top=3" will return "group3", "group4", /// "group5". /// /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='start'> /// List person groups from the least personGroupId greater than the "start". /// </param> /// <param name='top'> /// The number of person groups to list. /// </param> /// <param name='returnRecognitionModel'> /// A value indicating whether the operation should return 'recognitionModel' /// in response. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<PersonGroup>> ListAsync(this IPersonGroupOperations operations, string start = default(string), int? top = 1000, bool? returnRecognitionModel = false, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(start, top, returnRecognitionModel, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Queue a person group training task, the training task may not be started /// immediately. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Id referencing a particular person group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task TrainAsync(this IPersonGroupOperations operations, string personGroupId, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.TrainWithHttpMessagesAsync(personGroupId, null, cancellationToken).ConfigureAwait(false)).Dispose(); } } }
{ "content_hash": "a9938b285081f551b7d5caf3c122a1b1", "timestamp": "", "source": "github", "line_count": 227, "max_line_length": 285, "avg_line_length": 54.54625550660793, "alnum_prop": 0.5903731222742691, "repo_name": "stankovski/azure-sdk-for-net", "id": "46b59d755701837b8791a83802dd9cc4522f2244", "size": "12740", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sdk/cognitiveservices/Vision.Face/src/Generated/PersonGroupOperationsExtensions.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "33972632" }, { "name": "Cucumber", "bytes": "89597" }, { "name": "Shell", "bytes": "675" } ], "symlink_target": "" }
package org.apache.ambari.server.controller.internal; import static org.easymock.EasyMock.createMock; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.ambari.server.controller.ivory.IvoryService; import org.apache.ambari.server.controller.spi.Resource; import org.junit.Test; import junit.framework.Assert; /** * Tests for AbstractDRResourceProvider. */ public class AbstractDRResourceProviderTest { @Test public void testGetResourceProvider() throws Exception { Set<String> propertyIds = new HashSet<>(); propertyIds.add("foo"); propertyIds.add("cat1/foo"); propertyIds.add("cat2/bar"); propertyIds.add("cat2/baz"); propertyIds.add("cat3/sub1/bam"); propertyIds.add("cat4/sub2/sub3/bat"); propertyIds.add("cat5/subcat5/map"); Map<Resource.Type, String> keyPropertyIds = new HashMap<>(); IvoryService ivoryService = createMock(IvoryService.class); AbstractResourceProvider provider = (AbstractResourceProvider) AbstractDRResourceProvider.getResourceProvider( Resource.Type.DRFeed, ivoryService); Assert.assertTrue(provider instanceof FeedResourceProvider); } }
{ "content_hash": "5fc5c62e673e67ca7ce1fc1d9e3d0e35", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 82, "avg_line_length": 27.84090909090909, "alnum_prop": 0.7420408163265306, "repo_name": "sekikn/ambari", "id": "2aa6efabbdeea4b8276fd904d05165323458d630", "size": "2030", "binary": false, "copies": "2", "ref": "refs/heads/trunk", "path": "ambari-server/src/test/java/org/apache/ambari/server/controller/internal/AbstractDRResourceProviderTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "22734" }, { "name": "C", "bytes": "109499" }, { "name": "C#", "bytes": "182799" }, { "name": "CSS", "bytes": "616806" }, { "name": "CoffeeScript", "bytes": "4323" }, { "name": "Dockerfile", "bytes": "8117" }, { "name": "HTML", "bytes": "3725781" }, { "name": "Handlebars", "bytes": "1594385" }, { "name": "Java", "bytes": "26670585" }, { "name": "JavaScript", "bytes": "14647486" }, { "name": "Jinja", "bytes": "147938" }, { "name": "Less", "bytes": "303080" }, { "name": "Makefile", "bytes": "2407" }, { "name": "PHP", "bytes": "149648" }, { "name": "PLpgSQL", "bytes": "298247" }, { "name": "PowerShell", "bytes": "2047735" }, { "name": "Python", "bytes": "7226684" }, { "name": "R", "bytes": "1457" }, { "name": "Shell", "bytes": "350773" }, { "name": "TSQL", "bytes": "42351" }, { "name": "Vim Script", "bytes": "5813" }, { "name": "sed", "bytes": "1133" } ], "symlink_target": "" }
'use strict'; var $ = require('../internals/export'); var createHTML = require('../internals/create-html'); var forcedStringHTMLMethod = require('../internals/string-html-forced'); // `String.prototype.fontcolor` method // https://tc39.es/ecma262/#sec-string.prototype.fontcolor $({ target: 'String', proto: true, forced: forcedStringHTMLMethod('fontcolor') }, { fontcolor: function fontcolor(color) { return createHTML(this, 'font', 'color', color); } });
{ "content_hash": "a124bd695cd80e859c506725278e2903", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 83, "avg_line_length": 38.833333333333336, "alnum_prop": 0.703862660944206, "repo_name": "BigBoss424/portfolio", "id": "f96ebb4eb55a2ed3541292537a10d651c0d055db", "size": "466", "binary": false, "copies": "15", "ref": "refs/heads/master", "path": "v8/development/node_modules/core-js-pure/modules/es.string.fontcolor.js", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
(function(){ var /* jStorage version */ JSTORAGE_VERSION = "0.3.2", /* detect a dollar object or create one if not found */ $ = window.jQuery || window.$ || (window.$ = {}), /* check for a JSON handling support */ JSON = { parse: window.JSON && (window.JSON.parse || window.JSON.decode) || String.prototype.evalJSON && function(str){return String(str).evalJSON();} || $.parseJSON || $.evalJSON, stringify: Object.toJSON || window.JSON && (window.JSON.stringify || window.JSON.encode) || $.toJSON }; // Break if no JSON support was found if(!JSON.parse || !JSON.stringify){ throw new Error("No JSON support found, include //cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js to page"); } var /* This is the object, that holds the cached values */ _storage = {__jstorage_meta:{CRC32:{}}}, /* Actual browser storage (localStorage or globalStorage['domain']) */ _storage_service = {jStorage:"{}"}, /* DOM element for older IE versions, holds userData behavior */ _storage_elm = null, /* How much space does the storage take */ _storage_size = 0, /* which backend is currently used */ _backend = false, /* onchange observers */ _observers = {}, /* timeout to wait after onchange event */ _observer_timeout = false, /* last update time */ _observer_update = 0, /* pubsub observers */ _pubsub_observers = {}, /* skip published items older than current timestamp */ _pubsub_last = +new Date(), /* Next check for TTL */ _ttl_timeout, /** * XML encoding and decoding as XML nodes can't be JSON'ized * XML nodes are encoded and decoded if the node is the value to be saved * but not if it's as a property of another object * Eg. - * $.jStorage.set("key", xmlNode); // IS OK * $.jStorage.set("key", {xml: xmlNode}); // NOT OK */ _XMLService = { /** * Validates a XML node to be XML * based on jQuery.isXML function */ isXML: function(elm){ var documentElement = (elm ? elm.ownerDocument || elm : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }, /** * Encodes a XML node to string * based on http://www.mercurytide.co.uk/news/article/issues-when-working-ajax/ */ encode: function(xmlNode) { if(!this.isXML(xmlNode)){ return false; } try{ // Mozilla, Webkit, Opera return new XMLSerializer().serializeToString(xmlNode); }catch(E1) { try { // IE return xmlNode.xml; }catch(E2){} } return false; }, /** * Decodes a XML node from string * loosely based on http://outwestmedia.com/jquery-plugins/xmldom/ */ decode: function(xmlString){ var dom_parser = ("DOMParser" in window && (new DOMParser()).parseFromString) || (window.ActiveXObject && function(_xmlString) { var xml_doc = new ActiveXObject('Microsoft.XMLDOM'); xml_doc.async = 'false'; xml_doc.loadXML(_xmlString); return xml_doc; }), resultXML; if(!dom_parser){ return false; } resultXML = dom_parser.call("DOMParser" in window && (new DOMParser()) || window, xmlString, 'text/xml'); return this.isXML(resultXML)?resultXML:false; } }, _localStoragePolyfillSetKey = function(){}; ////////////////////////// PRIVATE METHODS //////////////////////// /** * Initialization function. Detects if the browser supports DOM Storage * or userData behavior and behaves accordingly. */ function _init(){ /* Check if browser supports localStorage */ var localStorageReallyWorks = false; if("localStorage" in window){ try { window.localStorage.setItem('_tmptest', 'tmpval'); localStorageReallyWorks = true; window.localStorage.removeItem('_tmptest'); } catch(BogusQuotaExceededErrorOnIos5) { // Thanks be to iOS5 Private Browsing mode which throws // QUOTA_EXCEEDED_ERRROR DOM Exception 22. } } if(localStorageReallyWorks){ try { if(window.localStorage) { _storage_service = window.localStorage; _backend = "localStorage"; _observer_update = _storage_service.jStorage_update; } } catch(E3) {/* Firefox fails when touching localStorage and cookies are disabled */} } /* Check if browser supports globalStorage */ else if("globalStorage" in window){ try { if(window.globalStorage) { _storage_service = window.globalStorage[window.location.hostname]; _backend = "globalStorage"; _observer_update = _storage_service.jStorage_update; } } catch(E4) {/* Firefox fails when touching localStorage and cookies are disabled */} } /* Check if browser supports userData behavior */ else { _storage_elm = document.createElement('link'); if(_storage_elm.addBehavior){ /* Use a DOM element to act as userData storage */ _storage_elm.style.behavior = 'url(#default#userData)'; /* userData element needs to be inserted into the DOM! */ document.getElementsByTagName('head')[0].appendChild(_storage_elm); try{ _storage_elm.load("jStorage"); }catch(E){ // try to reset cache _storage_elm.setAttribute("jStorage", "{}"); _storage_elm.save("jStorage"); _storage_elm.load("jStorage"); } var data = "{}"; try{ data = _storage_elm.getAttribute("jStorage"); }catch(E5){} try{ _observer_update = _storage_elm.getAttribute("jStorage_update"); }catch(E6){} _storage_service.jStorage = data; _backend = "userDataBehavior"; }else{ _storage_elm = null; return; } } // Load data from storage _load_storage(); // remove dead keys _handleTTL(); // create localStorage and sessionStorage polyfills if needed _createPolyfillStorage("local"); _createPolyfillStorage("session"); // start listening for changes _setupObserver(); // initialize publish-subscribe service _handlePubSub(); // handle cached navigation if("addEventListener" in window){ window.addEventListener("pageshow", function(event){ if(event.persisted){ _storageObserver(); } }, false); } } /** * Create a polyfill for localStorage (type="local") or sessionStorage (type="session") * * @param {String} type Either "local" or "session" * @param {Boolean} forceCreate If set to true, recreate the polyfill (needed with flush) */ function _createPolyfillStorage(type, forceCreate){ var _skipSave = false, _length = 0, i, storage, storage_source = {}; var rand = Math.random(); if(!forceCreate && typeof window[type+"Storage"] != "undefined"){ return; } // Use globalStorage for localStorage if available if(type == "local" && window.globalStorage){ localStorage = window.globalStorage[window.location.hostname]; return; } // only IE6/7 from this point on if(_backend != "userDataBehavior"){ return; } // Remove existing storage element if available if(forceCreate && window[type+"Storage"] && window[type+"Storage"].parentNode){ window[type+"Storage"].parentNode.removeChild(window[type+"Storage"]); } storage = document.createElement("button"); document.getElementsByTagName('head')[0].appendChild(storage); if(type == "local"){ storage_source = _storage; }else if(type == "session"){ _sessionStoragePolyfillUpdate(); } for(i in storage_source){ if(storage_source.hasOwnProperty(i) && i != "__jstorage_meta" && i != "length" && typeof storage_source[i] != "undefined"){ if(!(i in storage)){ _length++; } storage[i] = storage_source[i]; } } // Polyfill API /** * Indicates how many keys are stored in the storage */ storage.length = _length; /** * Returns the key of the nth stored value * * @param {Number} n Index position * @return {String} Key name of the nth stored value */ storage.key = function(n){ var count = 0, i; _sessionStoragePolyfillUpdate(); for(i in storage_source){ if(storage_source.hasOwnProperty(i) && i != "__jstorage_meta" && i!="length" && typeof storage_source[i] != "undefined"){ if(count == n){ return i; } count++; } } } /** * Returns the current value associated with the given key * * @param {String} key key name * @return {Mixed} Stored value */ storage.getItem = function(key){ _sessionStoragePolyfillUpdate(); if(type == "session"){ return storage_source[key]; } return $.jStorage.get(key); } /** * Sets or updates value for a give key * * @param {String} key Key name to be updated * @param {String} value String value to be stored */ storage.setItem = function(key, value){ if(typeof value == "undefined"){ return; } storage[key] = (value || "").toString(); } /** * Removes key from the storage * * @param {String} key Key name to be removed */ storage.removeItem = function(key){ if(type == "local"){ return $.jStorage.deleteKey(key); } storage[key] = undefined; _skipSave = true; if(key in storage){ storage.removeAttribute(key); } _skipSave = false; } /** * Clear storage */ storage.clear = function(){ if(type == "session"){ window.name = ""; _createPolyfillStorage("session", true); return; } $.jStorage.flush(); } if(type == "local"){ _localStoragePolyfillSetKey = function(key, value){ if(key == "length"){ return; } _skipSave = true; if(typeof value == "undefined"){ if(key in storage){ _length--; storage.removeAttribute(key); } }else{ if(!(key in storage)){ _length++; } storage[key] = (value || "").toString(); } storage.length = _length; _skipSave = false; } } function _sessionStoragePolyfillUpdate(){ if(type != "session"){ return; } try{ storage_source = JSON.parse(window.name || "{}"); }catch(E){ storage_source = {}; } } function _sessionStoragePolyfillSave(){ if(type != "session"){ return; } window.name = JSON.stringify(storage_source); }; storage.attachEvent("onpropertychange", function(e){ if(e.propertyName == "length"){ return; } if(_skipSave || e.propertyName == "length"){ return; } if(type == "local"){ if(!(e.propertyName in storage_source) && typeof storage[e.propertyName] != "undefined"){ _length ++; } }else if(type == "session"){ _sessionStoragePolyfillUpdate(); if(typeof storage[e.propertyName] != "undefined" && !(e.propertyName in storage_source)){ storage_source[e.propertyName] = storage[e.propertyName]; _length++; }else if(typeof storage[e.propertyName] == "undefined" && e.propertyName in storage_source){ delete storage_source[e.propertyName]; _length--; }else{ storage_source[e.propertyName] = storage[e.propertyName]; } _sessionStoragePolyfillSave(); storage.length = _length; return; } $.jStorage.set(e.propertyName, storage[e.propertyName]); storage.length = _length; }); window[type+"Storage"] = storage; } /** * Reload data from storage when needed */ function _reloadData(){ var data = "{}"; if(_backend == "userDataBehavior"){ _storage_elm.load("jStorage"); try{ data = _storage_elm.getAttribute("jStorage"); }catch(E5){} try{ _observer_update = _storage_elm.getAttribute("jStorage_update"); }catch(E6){} _storage_service.jStorage = data; } _load_storage(); // remove dead keys _handleTTL(); _handlePubSub(); } /** * Sets up a storage change observer */ function _setupObserver(){ if(_backend == "localStorage" || _backend == "globalStorage"){ if("addEventListener" in window){ window.addEventListener("storage", _storageObserver, false); }else{ document.attachEvent("onstorage", _storageObserver); } }else if(_backend == "userDataBehavior"){ setInterval(_storageObserver, 1000); } } /** * Fired on any kind of data change, needs to check if anything has * really been changed */ function _storageObserver(){ var updateTime; // cumulate change notifications with timeout clearTimeout(_observer_timeout); _observer_timeout = setTimeout(function(){ if(_backend == "localStorage" || _backend == "globalStorage"){ updateTime = _storage_service.jStorage_update; }else if(_backend == "userDataBehavior"){ _storage_elm.load("jStorage"); try{ updateTime = _storage_elm.getAttribute("jStorage_update"); }catch(E5){} } if(updateTime && updateTime != _observer_update){ _observer_update = updateTime; _checkUpdatedKeys(); } }, 25); } /** * Reloads the data and checks if any keys are changed */ function _checkUpdatedKeys(){ var oldCrc32List = JSON.parse(JSON.stringify(_storage.__jstorage_meta.CRC32)), newCrc32List; _reloadData(); newCrc32List = JSON.parse(JSON.stringify(_storage.__jstorage_meta.CRC32)); var key, updated = [], removed = []; for(key in oldCrc32List){ if(oldCrc32List.hasOwnProperty(key)){ if(!newCrc32List[key]){ removed.push(key); continue; } if(oldCrc32List[key] != newCrc32List[key] && String(oldCrc32List[key]).substr(0,2) == "2."){ updated.push(key); } } } for(key in newCrc32List){ if(newCrc32List.hasOwnProperty(key)){ if(!oldCrc32List[key]){ updated.push(key); } } } _fireObservers(updated, "updated"); _fireObservers(removed, "deleted"); } /** * Fires observers for updated keys * * @param {Array|String} keys Array of key names or a key * @param {String} action What happened with the value (updated, deleted, flushed) */ function _fireObservers(keys, action){ keys = [].concat(keys || []); if(action == "flushed"){ keys = []; for(var key in _observers){ if(_observers.hasOwnProperty(key)){ keys.push(key); } } action = "deleted"; } for(var i=0, len = keys.length; i<len; i++){ if(_observers[keys[i]]){ for(var j=0, jlen = _observers[keys[i]].length; j<jlen; j++){ _observers[keys[i]][j](keys[i], action); } } } } /** * Publishes key change to listeners */ function _publishChange(){ var updateTime = (+new Date()).toString(); if(_backend == "localStorage" || _backend == "globalStorage"){ _storage_service.jStorage_update = updateTime; }else if(_backend == "userDataBehavior"){ _storage_elm.setAttribute("jStorage_update", updateTime); _storage_elm.save("jStorage"); } _storageObserver(); } /** * Loads the data from the storage based on the supported mechanism */ function _load_storage(){ /* if jStorage string is retrieved, then decode it */ if(_storage_service.jStorage){ try{ _storage = JSON.parse(String(_storage_service.jStorage)); }catch(E6){_storage_service.jStorage = "{}";} }else{ _storage_service.jStorage = "{}"; } _storage_size = _storage_service.jStorage?String(_storage_service.jStorage).length:0; if(!_storage.__jstorage_meta){ _storage.__jstorage_meta = {}; } if(!_storage.__jstorage_meta.CRC32){ _storage.__jstorage_meta.CRC32 = {}; } } /** * This functions provides the "save" mechanism to store the jStorage object */ function _save(){ _dropOldEvents(); // remove expired events try{ _storage_service.jStorage = JSON.stringify(_storage); // If userData is used as the storage engine, additional if(_storage_elm) { _storage_elm.setAttribute("jStorage",_storage_service.jStorage); _storage_elm.save("jStorage"); } _storage_size = _storage_service.jStorage?String(_storage_service.jStorage).length:0; }catch(E7){/* probably cache is full, nothing is saved this way*/} } /** * Function checks if a key is set and is string or numberic * * @param {String} key Key name */ function _checkKey(key){ if(!key || (typeof key != "string" && typeof key != "number")){ throw new TypeError('Key name must be string or numeric'); } if(key == "__jstorage_meta"){ throw new TypeError('Reserved key name'); } return true; } /** * Removes expired keys */ function _handleTTL(){ var curtime, i, TTL, CRC32, nextExpire = Infinity, changed = false, deleted = []; clearTimeout(_ttl_timeout); if(!_storage.__jstorage_meta || typeof _storage.__jstorage_meta.TTL != "object"){ // nothing to do here return; } curtime = +new Date(); TTL = _storage.__jstorage_meta.TTL; CRC32 = _storage.__jstorage_meta.CRC32; for(i in TTL){ if(TTL.hasOwnProperty(i)){ if(TTL[i] <= curtime){ delete TTL[i]; delete CRC32[i]; delete _storage[i]; changed = true; deleted.push(i); }else if(TTL[i] < nextExpire){ nextExpire = TTL[i]; } } } // set next check if(nextExpire != Infinity){ _ttl_timeout = setTimeout(_handleTTL, nextExpire - curtime); } // save changes if(changed){ _save(); _publishChange(); _fireObservers(deleted, "deleted"); } } /** * Checks if there's any events on hold to be fired to listeners */ function _handlePubSub(){ if(!_storage.__jstorage_meta.PubSub){ return; } var pubelm, _pubsubCurrent = _pubsub_last; for(var i=len=_storage.__jstorage_meta.PubSub.length-1; i>=0; i--){ pubelm = _storage.__jstorage_meta.PubSub[i]; if(pubelm[0] > _pubsub_last){ _pubsubCurrent = pubelm[0]; _fireSubscribers(pubelm[1], pubelm[2]); } } _pubsub_last = _pubsubCurrent; } /** * Fires all subscriber listeners for a pubsub channel * * @param {String} channel Channel name * @param {Mixed} payload Payload data to deliver */ function _fireSubscribers(channel, payload){ if(_pubsub_observers[channel]){ for(var i=0, len = _pubsub_observers[channel].length; i<len; i++){ // send immutable data that can't be modified by listeners _pubsub_observers[channel][i](channel, JSON.parse(JSON.stringify(payload))); } } } /** * Remove old events from the publish stream (at least 2sec old) */ function _dropOldEvents(){ if(!_storage.__jstorage_meta.PubSub){ return; } var retire = +new Date() - 2000; for(var i=0, len = _storage.__jstorage_meta.PubSub.length; i<len; i++){ if(_storage.__jstorage_meta.PubSub[i][0] <= retire){ // deleteCount is needed for IE6 _storage.__jstorage_meta.PubSub.splice(i, _storage.__jstorage_meta.PubSub.length - i); break; } } if(!_storage.__jstorage_meta.PubSub.length){ delete _storage.__jstorage_meta.PubSub; } } /** * Publish payload to a channel * * @param {String} channel Channel name * @param {Mixed} payload Payload to send to the subscribers */ function _publish(channel, payload){ if(!_storage.__jstorage_meta){ _storage.__jstorage_meta = {}; } if(!_storage.__jstorage_meta.PubSub){ _storage.__jstorage_meta.PubSub = []; } _storage.__jstorage_meta.PubSub.unshift([+new Date, channel, payload]); _save(); _publishChange(); } /** * JS Implementation of MurmurHash2 * * SOURCE: https://github.com/garycourt/murmurhash-js (MIT licensed) * * @author <a href="mailto:gary.court@gmail.com">Gary Court</a> * @see http://github.com/garycourt/murmurhash-js * @author <a href="mailto:aappleby@gmail.com">Austin Appleby</a> * @see http://sites.google.com/site/murmurhash/ * * @param {string} str ASCII only * @param {number} seed Positive integer only * @return {number} 32-bit positive integer hash */ function murmurhash2_32_gc(str, seed) { var l = str.length, h = seed ^ l, i = 0, k; while (l >= 4) { k = ((str.charCodeAt(i) & 0xff)) | ((str.charCodeAt(++i) & 0xff) << 8) | ((str.charCodeAt(++i) & 0xff) << 16) | ((str.charCodeAt(++i) & 0xff) << 24); k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); k ^= k >>> 24; k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)) ^ k; l -= 4; ++i; } switch (l) { case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16; case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8; case 1: h ^= (str.charCodeAt(i) & 0xff); h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); } h ^= h >>> 13; h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); h ^= h >>> 15; return h >>> 0; } ////////////////////////// PUBLIC INTERFACE ///////////////////////// $.jStorage = { /* Version number */ version: JSTORAGE_VERSION, /** * Sets a key's value. * * @param {String} key Key to set. If this value is not set or not * a string an exception is raised. * @param {Mixed} value Value to set. This can be any value that is JSON * compatible (Numbers, Strings, Objects etc.). * @param {Object} [options] - possible options to use * @param {Number} [options.TTL] - optional TTL value * @return {Mixed} the used value */ set: function(key, value, options){ _checkKey(key); options = options || {}; // undefined values are deleted automatically if(typeof value == "undefined"){ this.deleteKey(key); return value; } if(_XMLService.isXML(value)){ value = {_is_xml:true,xml:_XMLService.encode(value)}; }else if(typeof value == "function"){ return undefined; // functions can't be saved! }else if(value && typeof value == "object"){ // clone the object before saving to _storage tree value = JSON.parse(JSON.stringify(value)); } _storage[key] = value; _storage.__jstorage_meta.CRC32[key] = "2."+murmurhash2_32_gc(JSON.stringify(value)); this.setTTL(key, options.TTL || 0); // also handles saving and _publishChange _localStoragePolyfillSetKey(key, value); _fireObservers(key, "updated"); return value; }, /** * Looks up a key in cache * * @param {String} key - Key to look up. * @param {mixed} def - Default value to return, if key didn't exist. * @return {Mixed} the key value, default value or null */ get: function(key, def){ _checkKey(key); if(key in _storage){ if(_storage[key] && typeof _storage[key] == "object" && _storage[key]._is_xml) { return _XMLService.decode(_storage[key].xml); }else{ return _storage[key]; } } return typeof(def) == 'undefined' ? null : def; }, /** * Deletes a key from cache. * * @param {String} key - Key to delete. * @return {Boolean} true if key existed or false if it didn't */ deleteKey: function(key){ _checkKey(key); if(key in _storage){ delete _storage[key]; // remove from TTL list if(typeof _storage.__jstorage_meta.TTL == "object" && key in _storage.__jstorage_meta.TTL){ delete _storage.__jstorage_meta.TTL[key]; } delete _storage.__jstorage_meta.CRC32[key]; _localStoragePolyfillSetKey(key, undefined); _save(); _publishChange(); _fireObservers(key, "deleted"); return true; } return false; }, /** * Sets a TTL for a key, or remove it if ttl value is 0 or below * * @param {String} key - key to set the TTL for * @param {Number} ttl - TTL timeout in milliseconds * @return {Boolean} true if key existed or false if it didn't */ setTTL: function(key, ttl){ var curtime = +new Date(); _checkKey(key); ttl = Number(ttl) || 0; if(key in _storage){ if(!_storage.__jstorage_meta.TTL){ _storage.__jstorage_meta.TTL = {}; } // Set TTL value for the key if(ttl>0){ _storage.__jstorage_meta.TTL[key] = curtime + ttl; }else{ delete _storage.__jstorage_meta.TTL[key]; } _save(); _handleTTL(); _publishChange(); return true; } return false; }, /** * Gets remaining TTL (in milliseconds) for a key or 0 when no TTL has been set * * @param {String} key Key to check * @return {Number} Remaining TTL in milliseconds */ getTTL: function(key){ var curtime = +new Date(), ttl; _checkKey(key); if(key in _storage && _storage.__jstorage_meta.TTL && _storage.__jstorage_meta.TTL[key]){ ttl = _storage.__jstorage_meta.TTL[key] - curtime; return ttl || 0; } return 0; }, /** * Deletes everything in cache. * * @return {Boolean} Always true */ flush: function(){ _storage = {__jstorage_meta:{CRC32:{}}}; _createPolyfillStorage("local", true); _save(); _publishChange(); _fireObservers(null, "flushed"); return true; }, /** * Returns a read-only copy of _storage * * @return {Object} Read-only copy of _storage */ storageObj: function(){ function F() {} F.prototype = _storage; return new F(); }, /** * Returns an index of all used keys as an array * ['key1', 'key2',..'keyN'] * * @return {Array} Used keys */ index: function(){ var index = [], i; for(i in _storage){ if(_storage.hasOwnProperty(i) && i != "__jstorage_meta"){ index.push(i); } } return index; }, /** * How much space in bytes does the storage take? * * @return {Number} Storage size in chars (not the same as in bytes, * since some chars may take several bytes) */ storageSize: function(){ return _storage_size; }, /** * Which backend is currently in use? * * @return {String} Backend name */ currentBackend: function(){ return _backend; }, /** * Test if storage is available * * @return {Boolean} True if storage can be used */ storageAvailable: function(){ return !!_backend; }, /** * Register change listeners * * @param {String} key Key name * @param {Function} callback Function to run when the key changes */ listenKeyChange: function(key, callback){ _checkKey(key); if(!_observers[key]){ _observers[key] = []; } _observers[key].push(callback); }, /** * Remove change listeners * * @param {String} key Key name to unregister listeners against * @param {Function} [callback] If set, unregister the callback, if not - unregister all */ stopListening: function(key, callback){ _checkKey(key); if(!_observers[key]){ return; } if(!callback){ delete _observers[key]; return; } for(var i = _observers[key].length - 1; i>=0; i--){ if(_observers[key][i] == callback){ _observers[key].splice(i,1); } } }, /** * Subscribe to a Publish/Subscribe event stream * * @param {String} channel Channel name * @param {Function} callback Function to run when the something is published to the channel */ subscribe: function(channel, callback){ channel = (channel || "").toString(); if(!channel){ throw new TypeError('Channel not defined'); } if(!_pubsub_observers[channel]){ _pubsub_observers[channel] = []; } _pubsub_observers[channel].push(callback); }, /** * Publish data to an event stream * * @param {String} channel Channel name * @param {Mixed} payload Payload to deliver */ publish: function(channel, payload){ channel = (channel || "").toString(); if(!channel){ throw new TypeError('Channel not defined'); } _publish(channel, payload); }, /** * Reloads the data from browser storage */ reInit: function(){ _reloadData(); } }; // Initialize jStorage _init(); })();
{ "content_hash": "c5518de816713a936bad41d7a9171700", "timestamp": "", "source": "github", "line_count": 1119, "max_line_length": 137, "avg_line_length": 31.483467381590707, "alnum_prop": 0.48021572523417544, "repo_name": "Karpec/gizd", "id": "07c499225118fd92bda0f4bdd02696aba26c168d", "size": "36560", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jscript/jstorage.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "95" }, { "name": "C++", "bytes": "18108" }, { "name": "CSS", "bytes": "314353" }, { "name": "HTML", "bytes": "300046" }, { "name": "JavaScript", "bytes": "850407" }, { "name": "Makefile", "bytes": "1751" }, { "name": "PHP", "bytes": "12960783" }, { "name": "Shell", "bytes": "199" }, { "name": "Smarty", "bytes": "624186" } ], "symlink_target": "" }
using HarshPoint; using HarshPoint.ShellployGenerator.Builders; using HarshPoint.ShellployGenerator.CodeGen; using HarshPoint.Tests; using System; using System.CodeDom; using Xunit; using Xunit.Abstractions; namespace CodeGen { public class Fixed_property_assignment : SeriloggedTest { private readonly CodeAssignStatement _assign; public Fixed_property_assignment(ITestOutputHelper output) : base(output) { var builder = new NewObjectCommandBuilder<Test>(); builder.Parameter(x => x.Param).SetFixedValue("42"); var command = builder.ToCommand(); var visitor = new NewObjectAssignmentVisitor(TargetObject); visitor.Visit(command.Properties); var statements = visitor.Statements; var stmt = Assert.Single(statements); _assign = Assert.IsType<CodeAssignStatement>(stmt); } [Fact] public void Right_is_fixed_value() { var rhs = Assert.IsType<CodePrimitiveExpression>( _assign.Right ); Assert.Equal("42", rhs.Value); } private static readonly CodeExpression TargetObject = new CodeVariableReferenceExpression("target"); private class Test { [Parameter] public String Param { get; set; } } } }
{ "content_hash": "1228a54d79437b6f96dc98f16029e281", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 81, "avg_line_length": 27.294117647058822, "alnum_prop": 0.6221264367816092, "repo_name": "NaseUkolyCZ/HarshPoint", "id": "4eddf348e2de45dee44fde91db15f57d3b049aef", "size": "1394", "binary": false, "copies": "3", "ref": "refs/heads/development", "path": "test/HarshPoint.Shellploy.Generator.Tests/CodeGen/Fixed_property_assignment.cs", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C#", "bytes": "852235" }, { "name": "PowerShell", "bytes": "8864" } ], "symlink_target": "" }
package net.brennheit.mcashapi.listener; import net.brennheit.mcashapi.resource.ShortlinkLastScan; /** * * @author fiLLLip */ public interface IListenForShortlinkScan { public void shortlinkScanned(ShortlinkLastScan shortlinkScan); }
{ "content_hash": "fe226a48a1686b51703dc1da21b652d9", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 66, "avg_line_length": 18.846153846153847, "alnum_prop": 0.7877551020408163, "repo_name": "fiLLLip/java-mapi-client", "id": "8a0965630d3f43d2a500a38a5d5540d78653cf60", "size": "1606", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/net/brennheit/mcashapi/listener/IListenForShortlinkScan.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Java", "bytes": "84846" } ], "symlink_target": "" }
import { HeroListComponent } from './hero-list.component'; import { HeroDetailComponent } from './hero-detail.component'; export const HeroesRoutes = [ { path: '/heroes', component: HeroListComponent }, { path: '/hero/:id', component: HeroDetailComponent } ];
{ "content_hash": "c10ea8540d877e24327ce91d7c52c4e5", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 64, "avg_line_length": 30.444444444444443, "alnum_prop": 0.6897810218978102, "repo_name": "born2net/ng2-minimal", "id": "a46525ac47a02bcbab26928bcc9b1e182824af2e", "size": "454", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/heroes/heroes.routes.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2639" }, { "name": "HTML", "bytes": "1438" }, { "name": "JavaScript", "bytes": "1773" }, { "name": "TypeScript", "bytes": "14738" } ], "symlink_target": "" }
The `testserver` package helps running cockroachDB binary with tests. It automatically downloads the latest stable cockroach binary for your runtimeOS (Linux-amd64 and Darwin-amd64 only for now), or attempts to run "cockroach" from your PATH. ### Example To run the test server, call `NewTestServer(opts)` and with test server options. Here's an example of starting a test server without server options (i.e. in `Insecure` mode). ```go import "github.com/cockroachdb/cockroach-go/v2/testserver" import "testing" import "time" func TestRunServer(t *testing.T) { ts, err := testserver.NewTestServer() if err != nil { t.Fatal(err) } defer ts.Stop() db, err := sql.Open("postgres", ts.PGURL().String()) if err != nil { t.Fatal(err) } } ``` **Note: please always use `testserver.NewTestServer()` to start a test server. Never use `testserver.Start()`.** ### Test Server Options The default configuration is : - in insecure mode, so not using TLS certificates to encrypt network; - storing data to memory, with 20% of hard drive space assigned to the node; - auto-downloading the latest stable release of cockroachDB. You can also choose from the following options and pass them to `testserver. NewTestServer()`. - **Secure Mode**: run a secure multi-node cluster locally, using TLS certificates to encrypt network communication. See also https://www.cockroachlabs.com/docs/stable/secure-a-cluster.html. - Usage: ```NewTestServer(testserver.SecureOpt())``` - **Set Root User's Password**: set the given password for the root user for the PostgreSQL server, so to avoid having to use client certificates. This option can only be passed under secure mode. - Usage: ```NewTestServer(testserver.RootPasswordOpt (your_password))``` - **Store On Disk**: store the database to the local disk. By default, the database is saved at `/tmp/cockroach-testserverxxxxxxxx`, with randomly generated `xxxxxxxx` postfix. - Usage: ```NewTestServer(testserver.StoreOnDiskOpt())``` - **Set Memory Allocation for Databse Storage**: set the maximum percentage of total memory space assigned to store the database. See also https://www.cockroachlabs. com/docs/stable/cockroach-start.html. - Usage: ```NewTestServer(testserver.SetStoreMemSizeOpt(0.3))``` ### Test Server for Multi Tenants The usage of test server as a tenant server is still under development. Please check `testserver/tenant.go` for more information.
{ "content_hash": "5e60f59c1ae5eadfa89d1b844d0d8330", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 116, "avg_line_length": 39.171875, "alnum_prop": 0.7267650578380535, "repo_name": "cockroachdb/cockroach-go", "id": "3a11dd4d414e6c4fbffae53890a2acbbd460b868", "size": "2534", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "testserver/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "116871" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>samples - neotoma Database</title> <!-- Tell the browser to be responsive to screen width --> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <link rel="icon" type="image/png" sizes="16x16" href="../favicon.png"> <!-- Bootstrap 3.3.5 --> <link rel="stylesheet" href="../bower/admin-lte/bootstrap/css/bootstrap.min.css"> <!-- Font Awesome --> <link rel="stylesheet" href="../bower/font-awesome/css/font-awesome.min.css"> <!-- Ionicons --> <link rel="stylesheet" href="../bower/ionicons/css/ionicons.min.css"> <!-- DataTables --> <link rel="stylesheet" href="../bower/datatables.net-bs/css/dataTables.bootstrap.min.css"> <link rel="stylesheet" href="../bower/datatables.net-buttons-bs/css/buttons.bootstrap.min.css"> <!-- Code Mirror --> <link rel="stylesheet" href="../bower/codemirror/codemirror.css"> <!-- Fonts --> <link href='../fonts/indieflower/indie-flower.css' rel='stylesheet' type='text/css'> <link href='../fonts/source-sans-pro/source-sans-pro.css' rel='stylesheet' type='text/css'> <!-- Theme style --> <link rel="stylesheet" href="../bower/admin-lte/dist/css/AdminLTE.min.css"> <!-- Salvattore --> <link rel="stylesheet" href="../bower/salvattore/salvattore.css"> <!-- AdminLTE Skins. Choose a skin from the css/skins folder instead of downloading all of them to reduce the load. --> <link rel="stylesheet" href="../bower/admin-lte/dist/css/skins/_all-skins.min.css"> <!-- SchemaSpy --> <link rel="stylesheet" href="../schemaSpy.css"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="../bower/html5shiv/html5shiv.min.js"></script> <script src="../bower/respond/respond.min.js"></script> <![endif]--> </head> <!-- ADD THE CLASS layout-top-nav TO REMOVE THE SIDEBAR. --> <body class="hold-transition skin-blue layout-top-nav"> <div class="wrapper"> <header class="main-header"> <nav class="navbar navbar-static-top"> <div class="container"> <div class="navbar-header"> <a href="../index.html" class="navbar-brand"><b>neotoma</b> Database</a> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse"><i class="fa fa-bars"></i></button> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse pull-left" id="navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../index.html">Tables <span class="sr-only">(current)</span></a></li> <li><a href="../columns.html" title="All of the columns in the schema">Columns</a></li> <li><a href="../constraints.html" title="Useful for diagnosing error messages that just give constraint name or number">Constraints</a></li> <li><a href="../relationships.html" title="Diagram of table relationships">Relationships</a></li> <li><a href="../orphans.html" title="View of tables with neither parents nor children">Orphan&nbsp;Tables</a></li> <li><a href="../anomalies.html" title="Things that might not be quite right">Anomalies</a></li> <li><a href="../routines.html" title="Procedures and functions">Routines</a></li> </ul> </div> <!-- /.navbar-collapse --> <!-- Navbar Right Menu --> </div> <!-- /.container-fluid --> </nav> </header> <!-- Main content --> <!-- Full Width Column --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1>samples</h1><p><span id="recordNumber">446718</span> rows</p><br /> <div class="box box-primary"> <div class="box-header with-border"> <i class="fa fa-file-text-o"></i> <h3 id="Description" class="box-title">Description</h3> <div class="box-tools pull-right"> <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button> <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button> </div> </div><!-- /.box-header --> <div class="box-body clearfix"> <p>This table stores sample data. Samples belong to Analysis Units, which belong to Collection Units, which belong to Sites. Samples also belong to a Dataset, and the Dataset determines the type of sample. Thus, there could be two different samples from the same Analysis Unit, one belonging to a pollen dataset, the other to a plant macrofossil dataset.</p> </div><!-- /.box-body --> </div> </section> <!-- Main content --> <section class="content"> <div class="box box-primary"> <div class="box-header with-border"> <span class="glyphicon glyphicon-list-alt" aria-hidden="true"></span> <h3 id="Columns" class="box-title">Columns</h3> <div class="box-tools pull-right"> <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button> <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button> </div> </div> <div class="box-body"> <table id="standard_table" class="table table-bordered table-striped dataTable" role="grid"> <thead align='left'> <tr> <th>Column</th> <th>Type</th> <th>Size</th> <th title='Are nulls allowed?'>Nulls</th> <th title='Is column automatically updated?'>Auto</th> <th title='Default value'>Default</th> <th title='Columns in tables that reference this column'>Children</th> <th title='Columns in tables that are referenced by this column'>Parents</th> <th title='Comments' class="toggle"><span>Comments</span></th> </tr> </thead> <tbody> <tr> <td class='primaryKey' title='Primary Key'><i class='icon ion-key iconkey' style='padding-left: 5px;'></i><span id="sampleid">sampleid</span></td> <td>serial</td> <td>10</td> <td title=''></td> <td title='Automatically updated by the database'>√</td> <td>nextval(&#39;ndb.seq_samples_sampleid&#39;::regclass)</td> <td> <table border='0' cellspacing='0' cellpadding='0'> <tr> <td title="aggregatesamples.sampleid references samples.sampleid via fk_aggregatesamples_samples"><a href='aggregatesamples.html'>aggregatesamples</a><span class='relatedKey'>.sampleid</span></td> <td class="constraint detail">fk_aggregatesamples_samples<span title='Cascade on delete:&#10;Deletion of parent deletes child'>C</span></td> </tr> <tr> <td title="data.sampleid references samples.sampleid via fk_data_samples"><a href='data.html'>data</a><span class='relatedKey'>.sampleid</span></td> <td class="constraint detail">fk_data_samples<span title='Cascade on delete:&#10;Deletion of parent deletes child'>C</span></td> </tr> <tr> <td title="dsdatasample.sampleid&#39;s name implies that it&#39;s a child of samples.sampleid, but it doesn&#39;t reference that column."><a href='dsdatasample.html'>dsdatasample</a><span class='relatedKey'>.sampleid</span></td> <td class="constraint detail">Implied Constraint<span title='Restrict delete:&#10;Parent cannot be deleted if children exist'>R</span></td> </tr> <tr> <td title="geochronology.sampleid references samples.sampleid via fk_geochronology_samples"><a href='geochronology.html'>geochronology</a><span class='relatedKey'>.sampleid</span></td> <td class="constraint detail">fk_geochronology_samples<span title='Cascade on delete:&#10;Deletion of parent deletes child'>C</span></td> </tr> <tr> <td title="sampleages.sampleid references samples.sampleid via fk_sampleages_samples"><a href='sampleages.html'>sampleages</a><span class='relatedKey'>.sampleid</span></td> <td class="constraint detail">fk_sampleages_samples<span title='Cascade on delete:&#10;Deletion of parent deletes child'>C</span></td> </tr> <tr> <td title="sampleanalysts.sampleid references samples.sampleid via fk_sampleanalysts_samples"><a href='sampleanalysts.html'>sampleanalysts</a><span class='relatedKey'>.sampleid</span></td> <td class="constraint detail">fk_sampleanalysts_samples<span title='Cascade on delete:&#10;Deletion of parent deletes child'>C</span></td> </tr> <tr> <td title="samplekeywords.sampleid references samples.sampleid via fk_samplekeywords_samples"><a href='samplekeywords.html'>samplekeywords</a><span class='relatedKey'>.sampleid</span></td> <td class="constraint detail">fk_samplekeywords_samples<span title='Cascade on delete:&#10;Deletion of parent deletes child'>C</span></td> </tr> <tr> <td title="specimendates.sampleid references samples.sampleid via sd_smpid"><a href='specimendates.html'>specimendates</a><span class='relatedKey'>.sampleid</span></td> <td class="constraint detail">sd_smpid<span title='Restrict delete:&#10;Parent cannot be deleted if children exist'>R</span></td> </tr> </table> </td> <td> <table border='0' cellspacing='0' cellpadding='0'> </table> </td> <td><p>An arbitrary Sample identification number.</p></td> </tr> <tr> <td class='foreignKey' title='Foreign Key'><i class='icon ion-key iconkey' style='padding-left: 5px;'></i><span id="analysisunitid">analysisunitid</span></td> <td>int4</td> <td>10</td> <td title=''></td> <td title=''></td> <td>null</td> <td> <table border='0' cellspacing='0' cellpadding='0'> </table> </td> <td> <table border='0' cellspacing='0' cellpadding='0'> <tr> <td title="samples.analysisunitid references analysisunits.analysisunitid via fk_samples_analysisunits"><a href='analysisunits.html'>analysisunits</a><span class='relatedKey'>.analysisunitid</span></td> <td class="constraint detail">fk_samples_analysisunits<span title='Restrict delete:&#10;Parent cannot be deleted if children exist'>R</span></td> </tr> </table> </td> <td><p>Analysis Unit identification number. Field links to the AnalysisUnits table.</p></td> </tr> <tr> <td class='foreignKey' title='Foreign Key'><i class='icon ion-key iconkey' style='padding-left: 5px;'></i><span id="datasetid">datasetid</span></td> <td>int4</td> <td>10</td> <td title=''></td> <td title=''></td> <td>null</td> <td> <table border='0' cellspacing='0' cellpadding='0'> </table> </td> <td> <table border='0' cellspacing='0' cellpadding='0'> <tr> <td title="samples.datasetid references datasets.datasetid via fk_samples_datasets"><a href='datasets.html'>datasets</a><span class='relatedKey'>.datasetid</span></td> <td class="constraint detail">fk_samples_datasets<span title='Restrict delete:&#10;Parent cannot be deleted if children exist'>R</span></td> </tr> </table> </td> <td><p>Dataset identification number. Field links to the Datasets table.</p></td> </tr> <tr> <td><span id="samplename">samplename</span></td> <td>varchar</td> <td>80</td> <td title='nullable'>√</td> <td title=''></td> <td>null</td> <td> <table border='0' cellspacing='0' cellpadding='0'> </table> </td> <td> <table border='0' cellspacing='0' cellpadding='0'> </table> </td> <td><p>Sample name if any.</p></td> </tr> <tr> <td><span id="analysisdate">analysisdate</span></td> <td>date</td> <td>13</td> <td title='nullable'>√</td> <td title=''></td> <td>null</td> <td> <table border='0' cellspacing='0' cellpadding='0'> </table> </td> <td> <table border='0' cellspacing='0' cellpadding='0'> </table> </td> <td><p>Date of analysis.</p></td> </tr> <tr> <td><span id="labnumber">labnumber</span></td> <td>varchar</td> <td>40</td> <td title='nullable'>√</td> <td title=''></td> <td>null</td> <td> <table border='0' cellspacing='0' cellpadding='0'> </table> </td> <td> <table border='0' cellspacing='0' cellpadding='0'> </table> </td> <td><p>Laboratory number for the sample. A special case regards geochronologic samples, for which the LabNumber is the number, if any, assigned by the submitter, not the number assigned by the radiocarbon laboratory, which is in the Geochronology table.</p></td> </tr> <tr> <td><span id="preparationmethod">preparationmethod</span></td> <td>text</td> <td>2147483647</td> <td title='nullable'>√</td> <td title=''></td> <td>null</td> <td> <table border='0' cellspacing='0' cellpadding='0'> </table> </td> <td> <table border='0' cellspacing='0' cellpadding='0'> </table> </td> <td><p>Description, notes, or comments on preparation methods. For faunal samples, notes on screening methods or screen size are stored here.</p></td> </tr> <tr> <td><span id="notes">notes</span></td> <td>text</td> <td>2147483647</td> <td title='nullable'>√</td> <td title=''></td> <td>null</td> <td> <table border='0' cellspacing='0' cellpadding='0'> </table> </td> <td> <table border='0' cellspacing='0' cellpadding='0'> </table> </td> <td><p>Free form note or comments about the sample.</p></td> </tr> <tr> <td><span id="recdatecreated">recdatecreated</span></td> <td>timestamp</td> <td>22</td> <td title=''></td> <td title=''></td> <td>timezone(&#39;UTC&#39;::text, now())</td> <td> <table border='0' cellspacing='0' cellpadding='0'> </table> </td> <td> <table border='0' cellspacing='0' cellpadding='0'> </table> </td> <td></td> </tr> <tr> <td><span id="recdatemodified">recdatemodified</span></td> <td>timestamp</td> <td>22</td> <td title=''></td> <td title=''></td> <td>null</td> <td> <table border='0' cellspacing='0' cellpadding='0'> </table> </td> <td> <table border='0' cellspacing='0' cellpadding='0'> </table> </td> <td></td> </tr> <tr> <td><span id="sampledate">sampledate</span></td> <td>date</td> <td>13</td> <td title='nullable'>√</td> <td title=''></td> <td>null</td> <td> <table border='0' cellspacing='0' cellpadding='0'> </table> </td> <td> <table border='0' cellspacing='0' cellpadding='0'> </table> </td> <td></td> </tr> <tr> <td class='foreignKey' title='Foreign Key'><i class='icon ion-key iconkey' style='padding-left: 5px;'></i><span id="taxonid">taxonid</span></td> <td>int4</td> <td>10</td> <td title='nullable'>√</td> <td title=''></td> <td>null</td> <td> <table border='0' cellspacing='0' cellpadding='0'> </table> </td> <td> <table border='0' cellspacing='0' cellpadding='0'> <tr> <td title="samples.taxonid references taxa.taxonid via fk_samples_taxa"><a href='taxa.html'>taxa</a><span class='relatedKey'>.taxonid</span></td> <td class="constraint detail">fk_samples_taxa<span title='Restrict delete:&#10;Parent cannot be deleted if children exist'>R</span></td> </tr> </table> </td> <td></td> </tr> </tbody> </table> </div> </div> <div class="box box-primary"> <div class="box-header with-border"> <i class="fa fa-sitemap"></i> <h3 id="Indexes" class="box-title">Indexes</h3> <div class="box-tools pull-right"> <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button> <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button> </div> </div> <div class="box-body"> <table id="indexes_table" class="table table-bordered table-striped dataTable" role="grid"> <thead> <tr> <th>Constraint Name</th> <th>Type</th> <th>Sort</th> <th>Column(s)</th> </tr> </thead> <tbody> <tr> <td class='primaryKey' title='Primary Key'><i class='icon ion-key iconkey'></i> samples_pkey</td> <td>Primary key</td> <td><span title='Ascending'>Asc</span></td> <td>sampleid</td> </tr> <tr> <td title='Indexed'>ix_analysisunitid_samples</td> <td>Performance</td> <td><span title='Ascending'>Asc</span></td> <td>analysisunitid</td> </tr> <tr> <td title='Indexed'>ix_datasetid_samples</td> <td>Performance</td> <td><span title='Ascending'>Asc</span></td> <td>datasetid</td> </tr> <tr> <td title='Indexed'>sample_taxon_idx</td> <td>Performance</td> <td><span title='Ascending'>Asc</span></td> <td>taxonid</td> </tr> </tbody> </table> </div><!-- /.box-body --> </div> <div class="box box-primary"> <div class="box-header with-border"> <i class="fa fa-code-fork"></i> <h3 id="Relationships" class="box-title">Relationships</h3> <div class="box-tools pull-right"> <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button> <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button> </div> </div> <div class="box-body"> <div class="nav-tabs-custom"><!-- Tabs within a box --> <h5>Close relationships within degrees of separation</h5> <ul class="nav nav-tabs pull-left ui-sortable-handle"> <li class="active"><a href="#oneDegreeImg-chart" data-toggle="tab" aria-expanded="true">One</a></li> <li class=""><a href="#twodegreesDegreeImg-chart" data-toggle="tab" aria-expanded="true">Two degrees</a></li> <li class=""><a href="#oneimpliedDegreeImg-chart" data-toggle="tab" aria-expanded="true">One implied</a></li> <li class=""><a href="#twoimpliedDegreeImg-chart" data-toggle="tab" aria-expanded="true">Two implied</a></li> </ul> <div class="tab-content no-padding"> <div class="chart tab-pane active" id="oneDegreeImg-chart" style="position: relative; overflow-x:auto;"> <map id="oneDegreeRelationshipsDiagram" name="oneDegreeRelationshipsDiagram"> <area shape="rect" id="node1" href="aggregatesamples.html" target="_top" title="aggregatesamples" alt="" coords="672,293,915,440"> <area shape="rect" id="node2" href="samples.html" target="_top" title="samples" alt="" coords="257,581,628,1003"> <area shape="rect" id="node8" href="analysisunits.html" target="_top" title="analysisunits" alt="" coords="5,552,213,728"> <area shape="rect" id="node9" href="datasets.html" target="_top" title="datasets" alt="" coords="10,745,209,951"> <area shape="rect" id="node10" href="taxa.html" target="_top" title="taxa" alt="" coords="10,1060,209,1324"> <area shape="rect" id="node3" href="data.html" target="_top" title="data" alt="" coords="687,457,899,633"> <area shape="rect" id="node4" href="geochronology.html" target="_top" title="geochronology" alt="" coords="688,5,899,240"> <area shape="rect" id="node5" href="sampleages.html" target="_top" title="sampleages" alt="" coords="694,651,893,915"> <area shape="rect" id="node6" href="sampleanalysts.html" target="_top" title="sampleanalysts" alt="" coords="684,932,903,1108"> <area shape="rect" id="node7" href="samplekeywords.html" target="_top" title="samplekeywords" alt="" coords="679,1125,907,1272"> <area shape="rect" id="node11" href="specimendates.html" target="_top" title="specimendates" alt="" coords="959,100,1173,393"> </map> <a name='diagram'><img id="oneDegreeImg" src="../diagrams/tables/samples.1degree.png" usemap="#oneDegreeRelationshipsDiagram" class="diagram" border="0" align="left"></a> </div> <div class="chart tab-pane " id="twodegreesDegreeImg-chart" style="position: relative; overflow-x:auto;"> <map id="twoDegreesRelationshipsDiagram" name="twoDegreesRelationshipsDiagram"> <area shape="rect" id="node1" href="accumulationrates.html" target="_top" title="accumulationrates" alt="" coords="584,548,827,636"> <area shape="rect" id="node2" href="analysisunits.html" target="_top" title="analysisunits" alt="" coords="268,439,476,615"> <area shape="rect" id="node3" href="chronologies.html" target="_top" title="chronologies" alt="" coords="275,915,469,1003"> <area shape="rect" id="node11" href="collectionunits.html" target="_top" title="collectionunits" alt="" coords="9,923,220,1011"> <area shape="rect" id="node12" href="faciestypes.html" target="_top" title="faciestypes" alt="" coords="22,500,207,588"> <area shape="rect" id="node14" href="agetypes.html" target="_top" title="agetypes" alt="" coords="31,817,198,905"> <area shape="rect" id="node15" href="contacts.html" target="_top" title="contacts" alt="" coords="15,1332,214,1420"> <area shape="rect" id="node4" href="aggregatesampleages.html" target="_top" title="aggregatesampleages" alt="" coords="1237,956,1509,1044"> <area shape="rect" id="node5" href="aggregatedatasets.html" target="_top" title="aggregatedatasets" alt="" coords="935,1149,1181,1237"> <area shape="rect" id="node6" href="sampleages.html" target="_top" title="sampleages" alt="" coords="959,868,1157,1132"> <area shape="rect" id="node8" href="samples.html" target="_top" title="samples" alt="" coords="520,1595,891,2016"> <area shape="rect" id="node7" href="aggregatesamples.html" target="_top" title="aggregatesamples" alt="" coords="1251,1180,1494,1327"> <area shape="rect" id="node19" href="datasets.html" target="_top" title="datasets" alt="" coords="273,2117,471,2323"> <area shape="rect" id="node28" href="taxa.html" target="_top" title="taxa" alt="" coords="273,2843,471,3107"> <area shape="rect" id="node9" href="analysisunitaltdepths.html" target="_top" title="analysisunitaltdepths" alt="" coords="571,91,839,179"> <area shape="rect" id="node10" href="analysisunitlithostrat.html" target="_top" title="analysisunitlithostrat" alt="" coords="572,196,839,284"> <area shape="rect" id="node13" href="chroncontrols.html" target="_top" title="chroncontrols" alt="" coords="604,653,807,741"> <area shape="rect" id="node16" href="data.html" target="_top" title="data" alt="" coords="952,2300,1164,2476"> <area shape="rect" id="node17" href="variables.html" target="_top" title="variables" alt="" coords="611,3267,800,3355"> <area shape="rect" id="node18" href="dataprocessors.html" target="_top" title="dataprocessors" alt="" coords="597,1279,814,1367"> <area shape="rect" id="node24" href="datasettypes.html" target="_top" title="datasettypes" alt="" coords="15,2141,214,2229"> <area shape="rect" id="node25" href="embargo.html" target="_top" title="embargo" alt="" coords="33,2247,196,2335"> <area shape="rect" id="node20" href="datasetdatabases.html" target="_top" title="datasetdatabases" alt="" coords="586,2211,825,2299"> <area shape="rect" id="node21" href="datasetpis.html" target="_top" title="datasetpis" alt="" coords="614,1384,797,1472"> <area shape="rect" id="node22" href="datasetpublications.html" target="_top" title="datasetpublications" alt="" coords="579,2388,832,2476"> <area shape="rect" id="node23" href="publications.html" target="_top" title="publications" alt="" coords="15,3001,214,3089"> <area shape="rect" id="node26" href="datasetsubmissions.html" target="_top" title="datasetsubmissions" alt="" coords="578,1489,833,1577"> <area shape="rect" id="node27" href="datasettaxonnotes.html" target="_top" title="datasettaxonnotes" alt="" coords="583,2493,828,2581"> <area shape="rect" id="node60" href="taxagrouptypes.html" target="_top" title="taxagrouptypes" alt="" coords="5,2896,224,2984"> <area shape="rect" id="node29" href="datasetvariables.html" target="_top" title="datasetvariables" alt="" coords="943,2493,1173,2581"> <area shape="rect" id="node30" href="datataxonnotes.html" target="_top" title="datataxonnotes" alt="" coords="1263,1411,1482,1499"> <area shape="rect" id="node31" href="depagents.html" target="_top" title="depagents" alt="" coords="617,301,793,389"> <area shape="rect" id="node32" href="ecolgroups.html" target="_top" title="ecolgroups" alt="" coords="615,3056,795,3144"> <area shape="rect" id="node33" href="eventchronology.html" target="_top" title="eventchronology" alt="" coords="944,193,1172,281"> <area shape="rect" id="node34" href="externaltaxa.html" target="_top" title="externaltaxa" alt="" coords="608,3161,803,3249"> <area shape="rect" id="node35" href="formtaxa.html" target="_top" title="formtaxa" alt="" coords="623,3408,787,3496"> <area shape="rect" id="node36" href="geochroncontrols.html" target="_top" title="geochroncontrols" alt="" coords="1256,581,1489,669"> <area shape="rect" id="node37" href="geochronology.html" target="_top" title="geochronology" alt="" coords="953,616,1163,851"> <area shape="rect" id="node38" href="geochrontypes.html" target="_top" title="geochrontypes" alt="" coords="599,759,811,847"> <area shape="rect" id="node39" href="geochronpublications.html" target="_top" title="geochronpublications" alt="" coords="1239,1649,1506,1737"> <area shape="rect" id="node40" href="isoinstrumentation.html" target="_top" title="isoinstrumentation" alt="" coords="935,2599,1181,2687"> <area shape="rect" id="node41" href="isometadata.html" target="_top" title="isometadata" alt="" coords="1276,2020,1469,2108"> <area shape="rect" id="node42" href="isosamplepretreatments.html" target="_top" title="isosamplepretreatments" alt="" coords="1227,2301,1519,2389"> <area shape="rect" id="node43" href="isospecimendata.html" target="_top" title="isospecimendata" alt="" coords="1564,2677,1793,2765"> <area shape="rect" id="node44" href="specimens.html" target="_top" title="specimens" alt="" coords="1283,2881,1463,2969"> <area shape="rect" id="node48" href="elementtypes.html" target="_top" title="elementtypes" alt="" coords="957,3496,1159,3584"> <area shape="rect" id="node45" href="isosrmetadata.html" target="_top" title="isosrmetadata" alt="" coords="953,2845,1163,2933"> <area shape="rect" id="node46" href="isostandards.html" target="_top" title="isostandards" alt="" coords="960,3161,1156,3249"> <area shape="rect" id="node47" href="isostratdata.html" target="_top" title="isostratdata" alt="" coords="1277,2740,1468,2828"> <area shape="rect" id="node49" href="relativechronology.html" target="_top" title="relativechronology" alt="" coords="935,475,1181,563"> <area shape="rect" id="node50" href="repositoryspecimens.html" target="_top" title="repositoryspecimens" alt="" coords="574,2033,837,2121"> <area shape="rect" id="node51" href="sampleanalysts.html" target="_top" title="sampleanalysts" alt="" coords="949,1491,1167,1667"> <area shape="rect" id="node52" href="samplekeywords.html" target="_top" title="samplekeywords" alt="" coords="944,1327,1172,1473"> <area shape="rect" id="node53" href="keywords.html" target="_top" title="keywords" alt="" coords="621,1137,790,1225"> <area shape="rect" id="node54" href="specimendates.html" target="_top" title="specimendates" alt="" coords="1571,2237,1786,2531"> <area shape="rect" id="node55" href="fractiondated.html" target="_top" title="fractiondated" alt="" coords="1272,2159,1473,2247"> <area shape="rect" id="node56" href="specimendatescal.html" target="_top" title="specimendatescal" alt="" coords="1837,2240,2076,2328"> <area shape="rect" id="node57" href="summarydatataphonomy.html" target="_top" title="summarydatataphonomy" alt="" coords="1225,2407,1520,2495"> <area shape="rect" id="node58" href="synonyms.html" target="_top" title="synonyms" alt="" coords="619,2740,792,2828"> <area shape="rect" id="node59" href="synonymy.html" target="_top" title="synonymy" alt="" coords="618,2599,793,2687"> <area shape="rect" id="node61" href="taxaalthierarchy.html" target="_top" title="taxaalthierarchy" alt="" coords="592,2845,819,2933"> <area shape="rect" id="node62" href="taxonpaths.html" target="_top" title="taxonpaths" alt="" coords="614,2951,797,3039"> <area shape="rect" id="node63" href="tephras.html" target="_top" title="tephras" alt="" coords="629,407,782,495"> </map> <a name='diagram'><img id="twodegreesDegreeImg" src="../diagrams/tables/samples.2degrees.png" usemap="#twoDegreesRelationshipsDiagram" class="diagram" border="0" align="left"></a> </div> <div class="chart tab-pane " id="oneimpliedDegreeImg-chart" style="position: relative; overflow-x:auto;"> <map id="oneDegreeRelationshipsDiagramImplied" name="oneDegreeRelationshipsDiagramImplied"> <area shape="rect" id="node1" href="aggregatesamples.html" target="_top" title="aggregatesamples" alt="" coords="672,1065,915,1212"> <area shape="rect" id="node2" href="samples.html" target="_top" title="samples" alt="" coords="257,817,628,1239"> <area shape="rect" id="node5" href="datasets.html" target="_top" title="datasets" alt="" coords="10,879,209,1084"> <area shape="rect" id="node10" href="analysisunits.html" target="_top" title="analysisunits" alt="" coords="5,685,213,861"> <area shape="rect" id="node11" href="taxa.html" target="_top" title="taxa" alt="" coords="10,1221,209,1485"> <area shape="rect" id="node3" href="data.html" target="_top" title="data" alt="" coords="687,1229,899,1405"> <area shape="rect" id="node4" href="dsdatasample.html" target="_top" title="dsdatasample" alt="" coords="692,5,895,157"> <area shape="rect" id="node6" href="geochronology.html" target="_top" title="geochronology" alt="" coords="688,456,899,691"> <area shape="rect" id="node7" href="sampleages.html" target="_top" title="sampleages" alt="" coords="694,175,893,439"> <area shape="rect" id="node8" href="sampleanalysts.html" target="_top" title="sampleanalysts" alt="" coords="684,708,903,884"> <area shape="rect" id="node9" href="samplekeywords.html" target="_top" title="samplekeywords" alt="" coords="679,901,907,1048"> <area shape="rect" id="node12" href="specimendates.html" target="_top" title="specimendates" alt="" coords="959,1301,1173,1595"> </map> <a name='diagram'><img id="oneimpliedDegreeImg" src="../diagrams/tables/samples.implied1degrees.png" usemap="#oneDegreeRelationshipsDiagramImplied" class="diagram" border="0" align="left"></a> </div> <div class="chart tab-pane " id="twoimpliedDegreeImg-chart" style="position: relative; overflow-x:auto;"> <map id="twoDegreesRelationshipsDiagramImplied" name="twoDegreesRelationshipsDiagramImplied"> <area shape="rect" id="node1" href="accumulationrates.html" target="_top" title="accumulationrates" alt="" coords="584,604,827,692"> <area shape="rect" id="node2" href="analysisunits.html" target="_top" title="analysisunits" alt="" coords="268,405,476,581"> <area shape="rect" id="node3" href="chronologies.html" target="_top" title="chronologies" alt="" coords="275,851,469,939"> <area shape="rect" id="node11" href="collectionunits.html" target="_top" title="collectionunits" alt="" coords="9,955,220,1043"> <area shape="rect" id="node12" href="faciestypes.html" target="_top" title="faciestypes" alt="" coords="22,467,207,555"> <area shape="rect" id="node14" href="agetypes.html" target="_top" title="agetypes" alt="" coords="31,813,198,901"> <area shape="rect" id="node15" href="contacts.html" target="_top" title="contacts" alt="" coords="15,1393,214,1481"> <area shape="rect" id="node4" href="aggregatesampleages.html" target="_top" title="aggregatesampleages" alt="" coords="1237,976,1509,1064"> <area shape="rect" id="node5" href="aggregatedatasets.html" target="_top" title="aggregatedatasets" alt="" coords="935,1169,1181,1257"> <area shape="rect" id="node6" href="sampleages.html" target="_top" title="sampleages" alt="" coords="959,888,1157,1152"> <area shape="rect" id="node8" href="samples.html" target="_top" title="samples" alt="" coords="520,1940,891,2361"> <area shape="rect" id="node7" href="aggregatesamples.html" target="_top" title="aggregatesamples" alt="" coords="1251,1201,1494,1348"> <area shape="rect" id="node19" href="datasets.html" target="_top" title="datasets" alt="" coords="273,1916,471,2121"> <area shape="rect" id="node28" href="taxa.html" target="_top" title="taxa" alt="" coords="273,3067,471,3331"> <area shape="rect" id="node9" href="analysisunitaltdepths.html" target="_top" title="analysisunitaltdepths" alt="" coords="571,5,839,93"> <area shape="rect" id="node10" href="analysisunitlithostrat.html" target="_top" title="analysisunitlithostrat" alt="" coords="572,111,839,199"> <area shape="rect" id="node13" href="chroncontrols.html" target="_top" title="chroncontrols" alt="" coords="604,499,807,587"> <area shape="rect" id="node16" href="data.html" target="_top" title="data" alt="" coords="952,2544,1164,2720"> <area shape="rect" id="node17" href="variables.html" target="_top" title="variables" alt="" coords="611,2911,800,2999"> <area shape="rect" id="node18" href="dataprocessors.html" target="_top" title="dataprocessors" alt="" coords="597,1437,814,1525"> <area shape="rect" id="node24" href="datasettypes.html" target="_top" title="datasettypes" alt="" coords="15,1940,214,2028"> <area shape="rect" id="node25" href="embargo.html" target="_top" title="embargo" alt="" coords="33,2045,196,2133"> <area shape="rect" id="node20" href="datasetdatabases.html" target="_top" title="datasetdatabases" alt="" coords="586,1648,825,1736"> <area shape="rect" id="node21" href="datasetpis.html" target="_top" title="datasetpis" alt="" coords="614,1543,797,1631"> <area shape="rect" id="node22" href="datasetpublications.html" target="_top" title="datasetpublications" alt="" coords="579,2559,832,2647"> <area shape="rect" id="node23" href="publications.html" target="_top" title="publications" alt="" coords="15,2805,214,2893"> <area shape="rect" id="node26" href="datasetsubmissions.html" target="_top" title="datasetsubmissions" alt="" coords="578,1332,833,1420"> <area shape="rect" id="node27" href="datasettaxonnotes.html" target="_top" title="datasettaxonnotes" alt="" coords="583,2664,828,2752"> <area shape="rect" id="node64" href="taxagrouptypes.html" target="_top" title="taxagrouptypes" alt="" coords="5,3157,224,3245"> <area shape="rect" id="node29" href="datasetvariables.html" target="_top" title="datasetvariables" alt="" coords="943,2737,1173,2825"> <area shape="rect" id="node30" href="datataxonnotes.html" target="_top" title="datataxonnotes" alt="" coords="1263,1780,1482,1868"> <area shape="rect" id="node31" href="depagents.html" target="_top" title="depagents" alt="" coords="617,216,793,304"> <area shape="rect" id="node32" href="dsageranges.html" target="_top" title="dsageranges" alt="" coords="609,1169,801,1233"> <area shape="rect" id="node33" href="dsdatasample.html" target="_top" title="dsdatasample" alt="" coords="957,2339,1159,2491"> <area shape="rect" id="node34" href="dslinks.html" target="_top" title="dslinks" alt="" coords="633,1251,778,1315"> <area shape="rect" id="node35" href="dssampdata.html" target="_top" title="dssampdata" alt="" coords="611,1753,799,1817"> <area shape="rect" id="node36" href="ecolgroups.html" target="_top" title="ecolgroups" alt="" coords="615,3368,795,3456"> <area shape="rect" id="node37" href="eventchronology.html" target="_top" title="eventchronology" alt="" coords="944,389,1172,477"> <area shape="rect" id="node38" href="externaltaxa.html" target="_top" title="externaltaxa" alt="" coords="608,3473,803,3561"> <area shape="rect" id="node39" href="formtaxa.html" target="_top" title="formtaxa" alt="" coords="623,3615,787,3703"> <area shape="rect" id="node40" href="geochroncontrols.html" target="_top" title="geochroncontrols" alt="" coords="1256,601,1489,689"> <area shape="rect" id="node41" href="geochronology.html" target="_top" title="geochronology" alt="" coords="953,636,1163,871"> <area shape="rect" id="node42" href="geochrontypes.html" target="_top" title="geochrontypes" alt="" coords="599,709,811,797"> <area shape="rect" id="node43" href="geochronpublications.html" target="_top" title="geochronpublications" alt="" coords="1239,1400,1506,1488"> <area shape="rect" id="node44" href="isoinstrumentation.html" target="_top" title="isoinstrumentation" alt="" coords="935,2948,1181,3036"> <area shape="rect" id="node45" href="isometadata.html" target="_top" title="isometadata" alt="" coords="1276,2023,1469,2111"> <area shape="rect" id="node46" href="isosamplepretreatments.html" target="_top" title="isosamplepretreatments" alt="" coords="1227,2495,1519,2583"> <area shape="rect" id="node47" href="isospecimendata.html" target="_top" title="isospecimendata" alt="" coords="1564,3001,1793,3089"> <area shape="rect" id="node48" href="specimens.html" target="_top" title="specimens" alt="" coords="1283,3143,1463,3231"> <area shape="rect" id="node52" href="elementtypes.html" target="_top" title="elementtypes" alt="" coords="957,3195,1159,3283"> <area shape="rect" id="node49" href="isosrmetadata.html" target="_top" title="isosrmetadata" alt="" coords="953,3053,1163,3141"> <area shape="rect" id="node50" href="isostandards.html" target="_top" title="isostandards" alt="" coords="960,2843,1156,2931"> <area shape="rect" id="node51" href="isostratdata.html" target="_top" title="isostratdata" alt="" coords="1277,3248,1468,3336"> <area shape="rect" id="node53" href="relativechronology.html" target="_top" title="relativechronology" alt="" coords="935,495,1181,583"> <area shape="rect" id="node54" href="repositoryspecimens.html" target="_top" title="repositoryspecimens" alt="" coords="574,1835,837,1923"> <area shape="rect" id="node55" href="sampleanalysts.html" target="_top" title="sampleanalysts" alt="" coords="949,1485,1167,1661"> <area shape="rect" id="node56" href="samplekeywords.html" target="_top" title="samplekeywords" alt="" coords="944,1748,1172,1895"> <area shape="rect" id="node57" href="keywords.html" target="_top" title="keywords" alt="" coords="621,1064,790,1152"> <area shape="rect" id="node58" href="specimendates.html" target="_top" title="specimendates" alt="" coords="1571,2348,1786,2641"> <area shape="rect" id="node59" href="fractiondated.html" target="_top" title="fractiondated" alt="" coords="1272,2197,1473,2285"> <area shape="rect" id="node60" href="specimendatescal.html" target="_top" title="specimendatescal" alt="" coords="1837,2351,2076,2439"> <area shape="rect" id="node61" href="summarydatataphonomy.html" target="_top" title="summarydatataphonomy" alt="" coords="1225,2600,1520,2688"> <area shape="rect" id="node62" href="synonyms.html" target="_top" title="synonyms" alt="" coords="619,3016,792,3104"> <area shape="rect" id="node63" href="synonymy.html" target="_top" title="synonymy" alt="" coords="618,2805,793,2893"> <area shape="rect" id="node65" href="taxaalthierarchy.html" target="_top" title="taxaalthierarchy" alt="" coords="592,3121,819,3209"> <area shape="rect" id="node66" href="taxonpaths.html" target="_top" title="taxonpaths" alt="" coords="614,3263,797,3351"> <area shape="rect" id="node67" href="tephras.html" target="_top" title="tephras" alt="" coords="629,321,782,409"> </map> <a name='diagram'><img id="twoimpliedDegreeImg" src="../diagrams/tables/samples.implied2degrees.png" usemap="#twoDegreesRelationshipsDiagramImplied" class="diagram" border="0" align="left"></a> </div> </div> </div> </div><!-- /.box-body --> </div> </section> <script> var config = { pagination: true } </script> </div> <!-- /.content-wrapper --> <footer class="main-footer"> <div> <div class="pull-right hidden-xs"> <a href="https://github.com/schemaspy/schemaspy" title="GitHub for SchemaSpy"><i class="fa fa-github-square fa-2x"></i></a> <a href="http://stackoverflow.com/questions/tagged/schemaspy" title="StackOverflow for SchemaSpy"><i class="fa fa-stack-overflow fa-2x"></i></a> </div> <strong>Generated by <a href="http://schemaspy.org/" class="logo-text"><i class="fa fa-database"></i> SchemaSpy 6.1.0</a></strong> </div> <!-- /.container --> </footer> </div> <!-- ./wrapper --> <!-- jQuery 2.2.3 --> <script src="../bower/admin-lte/plugins/jQuery/jquery-2.2.3.min.js"></script> <script src="../bower/admin-lte/plugins/jQueryUI/jquery-ui.min.js"></script> <!-- Bootstrap 3.3.5 --> <script src="../bower/admin-lte/bootstrap/js/bootstrap.min.js"></script> <!-- DataTables --> <script src="../bower/datatables.net/jquery.dataTables.min.js"></script> <script src="../bower/datatables.net-bs/js/dataTables.bootstrap.min.js"></script> <script src="../bower/datatables.net-buttons/dataTables.buttons.min.js"></script> <script src="../bower/datatables.net-buttons-bs/js/buttons.bootstrap.min.js"></script> <script src="../bower/datatables.net-buttons/buttons.html5.min.js"></script> <script src="../bower/datatables.net-buttons/buttons.print.min.js"></script> <script src="../bower/datatables.net-buttons/buttons.colVis.min.js"></script> <!-- SheetJS --> <script src="../bower/js-xlsx/xlsx.full.min.js"></script> <!-- pdfmake --> <script src="../bower/pdfmake/pdfmake.min.js"></script> <script src="../bower/pdfmake/vfs_fonts.js"></script> <!-- SlimScroll --> <script src="../bower/admin-lte/plugins/slimScroll/jquery.slimscroll.min.js"></script> <!-- FastClick --> <script src="../bower/admin-lte/plugins/fastclick/fastclick.js"></script> <!-- Salvattore --> <script src="../bower/salvattore/salvattore.min.js"></script> <!-- AnchorJS --> <script src="../bower/anchor-js/anchor.min.js"></script> <!-- CodeMirror --> <script src="../bower/codemirror/codemirror.js"></script> <script src="../bower/codemirror/sql.js"></script> <!-- AdminLTE App --> <script src="../bower/admin-lte/dist/js/app.min.js"></script> <script src="table.js"></script> <script src="../schemaSpy.js"></script> </body> </html>
{ "content_hash": "7d26d606e6994c8950e4ec3cb1c13873", "timestamp": "", "source": "github", "line_count": 669, "max_line_length": 386, "avg_line_length": 82.14200298953662, "alnum_prop": 0.5111822830418722, "repo_name": "NeotomaDB/neotomadb.github.io", "id": "53dfe06f4b7a3f68bf60f249352e8fe0497bdd93", "size": "54969", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dbschema/tables/samples.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "400217" }, { "name": "HTML", "bytes": "16454034" }, { "name": "JavaScript", "bytes": "734721" }, { "name": "Ruby", "bytes": "134" }, { "name": "SCSS", "bytes": "19400" } ], "symlink_target": "" }
from __future__ import absolute_import from traits.api import List, Str, HasTraits, Float, Int # =============standard library imports ======================== from numpy import random, char import time # =============local library imports ========================== from pychron.hardware.gauges.base_controller import BaseGaugeController class BaseMicroIonController(BaseGaugeController): address = '01' mode = 'rs485' def load_additional_args(self, config, *args, **kw): self.address = self.config_get(config, 'General', 'address', optional=False) self.display_name = self.config_get(config, 'General', 'display_name', default=self.name) self.mode = self.config_get(config, 'Communications', 'mode', default='rs485') self._load_gauges(config) return True def get_pressures(self, verbose=False): kw = {'verbose': verbose, 'force': True} b = self.get_convectron_b_pressure(**kw) self._set_gauge_pressure('CG2', b) time.sleep(0.05) a = self.get_convectron_a_pressure(**kw) self._set_gauge_pressure('CG1', a) time.sleep(0.05) ig = self.get_ion_pressure(**kw) self._set_gauge_pressure('IG', ig) return ig, a, b def set_degas(self, state): key = 'DG' value = 'ON' if state else 'OFF' cmd = self._build_command(key, value) r = self.ask(cmd) r = self._parse_response(r) return r def get_degas(self): key = 'DGS' cmd = self._build_command(key) r = self.ask(cmd) r = self._parse_response(r) return r def get_ion_pressure(self, **kw): name = 'IG' return self._get_pressure(name, **kw) def get_convectron_a_pressure(self, **kw): name = 'CG1' return self._get_pressure(name, **kw) def get_convectron_b_pressure(self, **kw): name = 'CG2' return self._get_pressure(name, **kw) def set_ion_gauge_state(self, state): key = 'IG1' value = 'ON' if state else 'OFF' cmd = self._build_command(key, value) r = self.ask(cmd) r = self._parse_response(r) return r def get_process_control_status(self, channel=None): key = 'PCS' cmd = self._build_command(key, channel) r = self.ask(cmd) r = self._parse_response(r) if channel is None: if r is None: # from numpy import random,char r = random.randint(0, 2, 6) r = ','.join(char.array(r)) r = r.split(',') return r def _read_pressure(self, gauge, verbose=False): if isinstance(gauge, str): name = gauge else: name = gauge.name key = 'DS' cmd = self._build_command(key, name) r = self.ask(cmd, verbose=verbose) r = self._parse_response(r, name) return r def _build_command(self, key, value=None): # prepend key with our address # example of new string formating # see http://docs.python.org/library/string.html#formatspec if self.mode == 'rs485': key = '#{}{}'.format(self.address, key) if value is not None: args = (key, value) else: args = (key,) c = ' '.join(args) return c def _parse_response(self, r, name): if self.simulation or r is None: from numpy.random import normal if name == 'IG': loc, scale = 1e-9, 5e-9 else: loc, scale = 1e-2, 5e-3 return abs(normal(loc, scale)) return r # ============= EOF ====================================
{ "content_hash": "333cca1c5e5718c8173106421dbef65d", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 97, "avg_line_length": 28.671755725190838, "alnum_prop": 0.5332800851970181, "repo_name": "UManPychron/pychron", "id": "2cea69e0db6cd4bd09e2dca6fedda43d106aa17a", "size": "4553", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "pychron/hardware/gauges/granville_phillips/base_micro_ion_controller.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "131" }, { "name": "C++", "bytes": "3706" }, { "name": "CSS", "bytes": "279" }, { "name": "Fortran", "bytes": "455875" }, { "name": "HTML", "bytes": "40346" }, { "name": "Mako", "bytes": "412" }, { "name": "Processing", "bytes": "11421" }, { "name": "Python", "bytes": "10234954" }, { "name": "Shell", "bytes": "10753" } ], "symlink_target": "" }
<?php namespace tests\domain\domain\RssItem; use vsc\domain\domain\RssItem; /** * @covers \vsc\domain\domain\RssItem::buildObj() */ class buildObj extends \BaseUnitTest { public function testBuildRssItemFromString() { $domdoc = new \DOMDocument('1.0'); $domdoc->load(VSC_MOCK_PATH . 'static/sample-rss-2.xml'); $dom = $domdoc->getElementsByTagName('item')->item(0); // <item> // <title>Star City</title> // <link>http://liftoff.msfc.nasa.gov/news/2003/news-starcity.asp</link> // <description>How do Americans get ready to work with Russians aboard the International Space Station? They take a crash course in culture, language and protocol at Russia's &lt;a href="http://howe.iki.rssi.ru/GCTC/gctc_e.htm"&gt;Star City&lt;/a&gt;.</description> // <pubDate>Tue, 03 Jun 2003 09:39:21 GMT</pubDate> // <guid>http://liftoff.msfc.nasa.gov/2003/06/03.html#item573</guid> // </item> $o = new RssItem($dom); $o->buildObj($dom); $title = 'Star City'; $link = 'http://liftoff.msfc.nasa.gov/news/2003/news-starcity.asp'; $description =<<<DESC How do Americans get ready to work with Russians aboard the International Space Station? They take a crash course in culture, language and protocol at Russia's &lt;a href="http://howe.iki.rssi.ru/GCTC/gctc_e.htm"&gt;Star City&lt;/a&gt;. DESC; $pubDate = 'Tue, 03 Jun 2003 09:39:21 GMT'; $guid = 'http://liftoff.msfc.nasa.gov/2003/06/03.html#item573'; $this->assertEquals($title,$o->title); $this->assertEquals($link,$o->link); $this->assertEmpty($o->category); $this->assertEquals(html_entity_decode($description),$o->description); $this->assertEquals($pubDate,$o->pubDate); $this->assertEquals($guid,$o->guid); } }
{ "content_hash": "2b5030eb10ba138032d441e0c5766472", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 274, "avg_line_length": 42.41463414634146, "alnum_prop": 0.6814261069580219, "repo_name": "mariusor/vsc", "id": "e8c74c9bb00b97257a8b4a6fec8d7fcd756e24ee", "size": "1739", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/unit/domain/domain/RssItem/buildObjTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "29" }, { "name": "Hack", "bytes": "230" }, { "name": "JavaScript", "bytes": "15" }, { "name": "PHP", "bytes": "633113" } ], "symlink_target": "" }
<?php namespace Drupal\system\Tests\Entity; use Drupal\language\Entity\ConfigurableLanguage; use Drupal\simpletest\WebTestBase; /** * Tests the entity form. * * @group Entity */ class EntityFormTest extends WebTestBase { /** * Modules to enable. * * @var array */ public static $modules = ['entity_test', 'language']; protected function setUp() { parent::setUp(); $web_user = $this->drupalCreateUser(['administer entity_test content', 'view test entity']); $this->drupalLogin($web_user); // Add a language. ConfigurableLanguage::createFromLangcode('ro')->save(); } /** * Tests basic form CRUD functionality. */ public function testFormCRUD() { // All entity variations have to have the same results. foreach (entity_test_entity_types() as $entity_type) { $this->doTestFormCRUD($entity_type); } } /** * Tests basic multilingual form CRUD functionality. */ public function testMultilingualFormCRUD() { // All entity variations have to have the same results. foreach (entity_test_entity_types(ENTITY_TEST_TYPES_MULTILINGUAL) as $entity_type) { $this->doTestMultilingualFormCRUD($entity_type); } } /** * Tests hook_entity_form_display_alter(). * * @see entity_test_entity_form_display_alter() */ public function testEntityFormDisplayAlter() { $this->drupalGet('entity_test/add'); $altered_field = $this->xpath('//input[@name="field_test_text[0][value]" and @size="42"]'); $this->assertTrue(count($altered_field) === 1, 'The altered field has the correct size value.'); } /** * Executes the form CRUD tests for the given entity type. * * @param string $entity_type * The entity type to run the tests with. */ protected function doTestFormCRUD($entity_type) { $name1 = $this->randomMachineName(8); $name2 = $this->randomMachineName(10); $edit = [ 'name[0][value]' => $name1, 'field_test_text[0][value]' => $this->randomMachineName(16), ]; $this->drupalPostForm($entity_type . '/add', $edit, t('Save')); $entity = $this->loadEntityByName($entity_type, $name1); $this->assertTrue($entity, format_string('%entity_type: Entity found in the database.', ['%entity_type' => $entity_type])); $edit['name[0][value]'] = $name2; $this->drupalPostForm($entity_type . '/manage/' . $entity->id() . '/edit', $edit, t('Save')); $entity = $this->loadEntityByName($entity_type, $name1); $this->assertFalse($entity, format_string('%entity_type: The entity has been modified.', ['%entity_type' => $entity_type])); $entity = $this->loadEntityByName($entity_type, $name2); $this->assertTrue($entity, format_string('%entity_type: Modified entity found in the database.', ['%entity_type' => $entity_type])); $this->assertNotEqual($entity->name->value, $name1, format_string('%entity_type: The entity name has been modified.', ['%entity_type' => $entity_type])); $this->drupalGet($entity_type . '/manage/' . $entity->id() . '/edit'); $this->clickLink(t('Delete')); $this->drupalPostForm(NULL, [], t('Delete')); $entity = $this->loadEntityByName($entity_type, $name2); $this->assertFalse($entity, format_string('%entity_type: Entity not found in the database.', ['%entity_type' => $entity_type])); } /** * Executes the multilingual form CRUD tests for the given entity type ID. * * @param string $entity_type_id * The ID of entity type to run the tests with. */ protected function doTestMultilingualFormCRUD($entity_type_id) { $name1 = $this->randomMachineName(8); $name1_ro = $this->randomMachineName(9); $name2_ro = $this->randomMachineName(11); $edit = [ 'name[0][value]' => $name1, 'field_test_text[0][value]' => $this->randomMachineName(16), ]; $this->drupalPostForm($entity_type_id . '/add', $edit, t('Save')); $entity = $this->loadEntityByName($entity_type_id, $name1); $this->assertTrue($entity, format_string('%entity_type: Entity found in the database.', ['%entity_type' => $entity_type_id])); // Add a translation to the newly created entity without using the Content // translation module. $entity->addTranslation('ro', ['name' => $name1_ro])->save(); $translated_entity = $this->loadEntityByName($entity_type_id, $name1)->getTranslation('ro'); $this->assertEqual($translated_entity->name->value, $name1_ro, format_string('%entity_type: The translation has been added.', ['%entity_type' => $entity_type_id])); $edit['name[0][value]'] = $name2_ro; $this->drupalPostForm('ro/' . $entity_type_id . '/manage/' . $entity->id() . '/edit', $edit, t('Save')); $translated_entity = $this->loadEntityByName($entity_type_id, $name1)->getTranslation('ro'); $this->assertTrue($translated_entity, format_string('%entity_type: Modified translation found in the database.', ['%entity_type' => $entity_type_id])); $this->assertEqual($translated_entity->name->value, $name2_ro, format_string('%entity_type: The name of the translation has been modified.', ['%entity_type' => $entity_type_id])); $this->drupalGet('ro/' . $entity_type_id . '/manage/' . $entity->id() . '/edit'); $this->clickLink(t('Delete')); $this->drupalPostForm(NULL, [], t('Delete Romanian translation')); $entity = $this->loadEntityByName($entity_type_id, $name1); $this->assertNotNull($entity, format_string('%entity_type: The original entity still exists.', ['%entity_type' => $entity_type_id])); $this->assertFalse($entity->hasTranslation('ro'), format_string('%entity_type: Entity translation does not exist anymore.', ['%entity_type' => $entity_type_id])); } /** * Loads a test entity by name always resetting the storage cache. */ protected function loadEntityByName($entity_type, $name) { // Always load the entity from the database to ensure that changes are // correctly picked up. $entity_storage = $this->container->get('entity.manager')->getStorage($entity_type); $entity_storage->resetCache(); $entities = $entity_storage->loadByProperties(['name' => $name]); return $entities ? current($entities) : NULL; } /** * Checks that validation handlers works as expected. */ public function testValidationHandlers() { /** @var \Drupal\Core\State\StateInterface $state */ $state = $this->container->get('state'); // Check that from-level validation handlers can be defined and can alter // the form array. $state->set('entity_test.form.validate.test', 'form-level'); $this->drupalPostForm('entity_test/add', [], 'Save'); $this->assertTrue($state->get('entity_test.form.validate.result'), 'Form-level validation handlers behave correctly.'); // Check that defining a button-level validation handler causes an exception // to be thrown. $state->set('entity_test.form.validate.test', 'button-level'); $this->drupalPostForm('entity_test/add', [], 'Save'); $this->assertEqual($state->get('entity_test.form.save.exception'), 'Drupal\Core\Entity\EntityStorageException: Entity validation was skipped.', 'Button-level validation handlers behave correctly.'); } }
{ "content_hash": "bc757d383242e689ad0bf03286801fdf", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 202, "avg_line_length": 42.791666666666664, "alnum_prop": 0.6585060509111142, "repo_name": "IrvinAyala/fase2hdp", "id": "2ebc35061782bebc71f06d3f3dabd6afeeeb7463", "size": "7189", "binary": false, "copies": "244", "ref": "refs/heads/master", "path": "hdpDrupal/core/modules/system/src/Tests/Entity/EntityFormTest.php", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "240941" }, { "name": "CSS", "bytes": "1109994" }, { "name": "HTML", "bytes": "1612921" }, { "name": "JavaScript", "bytes": "3776072" }, { "name": "PHP", "bytes": "35433295" }, { "name": "Ruby", "bytes": "909" }, { "name": "Shell", "bytes": "52706" } ], "symlink_target": "" }
var redis = require('redis'); exports.redis={ name: 'redis', group: 'redis', title:'Redis', units: '', slope: 'zero', type: 'uint32', description:'Metrics for Redis Info', interval:15000, tmax:90, dmax:120, run:function(api,metric,send){ var client = redis.createClient(api.config.metrics.redis); client.on('error', function (err) { api.log(err.message,'error'); client.end(); }); client.on('ready',function(){ var info = client.server_info; var version = api.utils.objClone(metric); version.name = 'redis_version'; version.title = metric.title + ' Version'; version.value = info.redis_version; version.type='string'; version.slope='zero'; send(version); var role = api.utils.objClone(metric); role.name = 'redis_role'; role.title = metric.title + ' Redis role'; role.value = info.role; role.type='string'; role.slope='zero'; send(role); var sha1 = api.utils.objClone(metric); sha1.name = 'redis_git_sha1'; sha1.title = metric.title + ' Redis git sha1'; sha1.value = info[sha1.name]; sha1.type='string'; sha1.slope='zero'; send(sha1); var uptime = api.utils.objClone(metric); uptime.name = 'redis_uptime_in_seconds'; uptime.title = metric.title + ' Uptime In Seconds'; uptime.value = info.uptime_in_seconds; uptime.type='uint32'; uptime.slope='zero'; send(uptime); var uptime = api.utils.objClone(metric); uptime.name = 'redis_uptime_in_days'; uptime.title = metric.title + ' Uptime In Days'; uptime.value = info.uptime_in_days; uptime.type='uint32'; uptime.slope='zero'; send(uptime); var memory = api.utils.objClone(metric); memory.name = 'redis_used_memory'; memory.title = metric.title + ' Used Memory'; memory.units='KB'; memory.value = parseFloat(info.used_memory/1000); memory.type='float'; memory.slope='both'; send(memory); var connections = api.utils.objClone(metric); connections.name = 'redis_connected_clients'; connections.title = metric.title + ' Connected Clients'; connections.units='clients'; connections.value = info.connected_clients; connections.type='uint16'; connections.slope='both'; send(connections); var slaves = api.utils.objClone(metric); slaves.name = 'redis_connected_slaves'; slaves.title = metric.title + ' Connected Slaves'; slaves.units='slaves'; slaves.value = info.connected_slaves; slaves.type='uint16'; slaves.slope='both'; send(slaves); var blocked = api.utils.objClone(metric); blocked.name = 'redis_blocked_clients'; blocked.title = metric.title + ' Blocked Clients'; blocked.units='clients'; blocked.value = info.blocked_clients; blocked.type='uint32'; blocked.slope='both'; send(blocked); var channels = api.utils.objClone(metric); channels.name = 'redis_pubsub_channels'; channels.title = metric.title + ' PUB/SUB Channels'; channels.units='channels'; channels.value = info.pubsub_channels; channels.type='uint16'; channels.slope='both'; send(channels); var patterns = api.utils.objClone(metric); patterns.name = 'redis_pubsub_patterns'; patterns.title = metric.title + ' PUB/SUB Patterns'; patterns.units='patterns'; patterns.value = info.pubsub_patterns; patterns.type='uint16'; patterns.slope='both'; send(patterns); var totalConnections = api.utils.objClone(metric); totalConnections.name = 'redis_total_connections_received'; totalConnections.title = metric.title + ' Total Connections'; totalConnections.units='connections'; totalConnections.value = info.total_connections_received; totalConnections.type='uint32'; totalConnections.slope='zero'; send(totalConnections); var totalCommands = api.utils.objClone(metric); totalCommands.name = 'redis_total_commands_processed'; totalCommands.title = metric.title + ' Total Commands Processed'; totalCommands.units='commands'; totalCommands.value = info.total_commands_processed; totalCommands.type='uint32'; totalCommands.slope='zero'; send(totalCommands); var expiredKeys = api.utils.objClone(metric); expiredKeys.name = 'redis_expired_keys'; expiredKeys.title = metric.title + ' Expired Keys'; expiredKeys.units='keys'; expiredKeys.value = info.expired_keys; expiredKeys.type='uint32'; expiredKeys.slope='both'; send(expiredKeys); var keyspaceHits = api.utils.objClone(metric); keyspaceHits.name = 'redis_keyspace_hits'; keyspaceHits.title = metric.title + ' Keyspace Hits'; keyspaceHits.units='keys'; keyspaceHits.value = info.keyspace_hits; keyspaceHits.type='uint32'; keyspaceHits.slope='both'; send(keyspaceHits); var keyspaceMisses = api.utils.objClone(metric); keyspaceMisses.name = 'redis_keyspace_misses'; keyspaceMisses.title = metric.title + ' Keyspace Misses'; keyspaceMisses.units='keys'; keyspaceMisses.value = info.keyspace_misses; keyspaceMisses.type='uint32'; keyspaceMisses.slope='both'; send(keyspaceMisses); client.end(); }); } };
{ "content_hash": "5fa7583471914d9be8a9e92d549ae553", "timestamp": "", "source": "github", "line_count": 165, "max_line_length": 75, "avg_line_length": 36.41818181818182, "alnum_prop": 0.581461141620902, "repo_name": "alligator-io/alligator-metrics", "id": "b413f372eebbe2f030bb375d211f354991694d1f", "size": "6009", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "metrics/redis.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "47182" } ], "symlink_target": "" }
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. /*=========================================================================== C++ class header boilerplate exported from UnrealHeaderTool. This is automatically generated by the tools. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ PRAGMA_DISABLE_DEPRECATION_WARNINGS struct FRotator; #ifdef MULTIUSERTOOL_NetPawn_generated_h #error "NetPawn.generated.h already included, missing '#pragma once' in NetPawn.h" #endif #define MULTIUSERTOOL_NetPawn_generated_h #define MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h_12_RPC_WRAPPERS \ virtual bool ServerMoveTop_Validate(float , FRotator ); \ virtual void ServerMoveTop_Implementation(float Value, FRotator Rotation); \ virtual bool ServerMoveRight_Validate(float , FRotator ); \ virtual void ServerMoveRight_Implementation(float Value, FRotator Rotation); \ virtual bool ServerMoveForward_Validate(float , FRotator ); \ virtual void ServerMoveForward_Implementation(float Value, FRotator Rotation); \ \ DECLARE_FUNCTION(execOnRep_RotChange) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ this->OnRep_RotChange(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execOnRep_PosChange) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ this->OnRep_PosChange(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execServerMoveTop) \ { \ P_GET_PROPERTY(UFloatProperty,Z_Param_Value); \ P_GET_STRUCT(FRotator,Z_Param_Rotation); \ P_FINISH; \ P_NATIVE_BEGIN; \ if (!this->ServerMoveTop_Validate(Z_Param_Value,Z_Param_Rotation)) \ { \ RPC_ValidateFailed(TEXT("ServerMoveTop_Validate")); \ return; \ } \ this->ServerMoveTop_Implementation(Z_Param_Value,Z_Param_Rotation); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execServerMoveRight) \ { \ P_GET_PROPERTY(UFloatProperty,Z_Param_Value); \ P_GET_STRUCT(FRotator,Z_Param_Rotation); \ P_FINISH; \ P_NATIVE_BEGIN; \ if (!this->ServerMoveRight_Validate(Z_Param_Value,Z_Param_Rotation)) \ { \ RPC_ValidateFailed(TEXT("ServerMoveRight_Validate")); \ return; \ } \ this->ServerMoveRight_Implementation(Z_Param_Value,Z_Param_Rotation); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execServerMoveForward) \ { \ P_GET_PROPERTY(UFloatProperty,Z_Param_Value); \ P_GET_STRUCT(FRotator,Z_Param_Rotation); \ P_FINISH; \ P_NATIVE_BEGIN; \ if (!this->ServerMoveForward_Validate(Z_Param_Value,Z_Param_Rotation)) \ { \ RPC_ValidateFailed(TEXT("ServerMoveForward_Validate")); \ return; \ } \ this->ServerMoveForward_Implementation(Z_Param_Value,Z_Param_Rotation); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execMoveTop) \ { \ P_GET_PROPERTY(UFloatProperty,Z_Param_Value); \ P_FINISH; \ P_NATIVE_BEGIN; \ this->MoveTop(Z_Param_Value); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execMoveRight) \ { \ P_GET_PROPERTY(UFloatProperty,Z_Param_Value); \ P_FINISH; \ P_NATIVE_BEGIN; \ this->MoveRight(Z_Param_Value); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execMoveForward) \ { \ P_GET_PROPERTY(UFloatProperty,Z_Param_Value); \ P_FINISH; \ P_NATIVE_BEGIN; \ this->MoveForward(Z_Param_Value); \ P_NATIVE_END; \ } #define MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h_12_RPC_WRAPPERS_NO_PURE_DECLS \ virtual bool ServerMoveTop_Validate(float , FRotator ); \ virtual void ServerMoveTop_Implementation(float Value, FRotator Rotation); \ virtual bool ServerMoveRight_Validate(float , FRotator ); \ virtual void ServerMoveRight_Implementation(float Value, FRotator Rotation); \ virtual bool ServerMoveForward_Validate(float , FRotator ); \ virtual void ServerMoveForward_Implementation(float Value, FRotator Rotation); \ \ DECLARE_FUNCTION(execOnRep_RotChange) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ this->OnRep_RotChange(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execOnRep_PosChange) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ this->OnRep_PosChange(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execServerMoveTop) \ { \ P_GET_PROPERTY(UFloatProperty,Z_Param_Value); \ P_GET_STRUCT(FRotator,Z_Param_Rotation); \ P_FINISH; \ P_NATIVE_BEGIN; \ if (!this->ServerMoveTop_Validate(Z_Param_Value,Z_Param_Rotation)) \ { \ RPC_ValidateFailed(TEXT("ServerMoveTop_Validate")); \ return; \ } \ this->ServerMoveTop_Implementation(Z_Param_Value,Z_Param_Rotation); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execServerMoveRight) \ { \ P_GET_PROPERTY(UFloatProperty,Z_Param_Value); \ P_GET_STRUCT(FRotator,Z_Param_Rotation); \ P_FINISH; \ P_NATIVE_BEGIN; \ if (!this->ServerMoveRight_Validate(Z_Param_Value,Z_Param_Rotation)) \ { \ RPC_ValidateFailed(TEXT("ServerMoveRight_Validate")); \ return; \ } \ this->ServerMoveRight_Implementation(Z_Param_Value,Z_Param_Rotation); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execServerMoveForward) \ { \ P_GET_PROPERTY(UFloatProperty,Z_Param_Value); \ P_GET_STRUCT(FRotator,Z_Param_Rotation); \ P_FINISH; \ P_NATIVE_BEGIN; \ if (!this->ServerMoveForward_Validate(Z_Param_Value,Z_Param_Rotation)) \ { \ RPC_ValidateFailed(TEXT("ServerMoveForward_Validate")); \ return; \ } \ this->ServerMoveForward_Implementation(Z_Param_Value,Z_Param_Rotation); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execMoveTop) \ { \ P_GET_PROPERTY(UFloatProperty,Z_Param_Value); \ P_FINISH; \ P_NATIVE_BEGIN; \ this->MoveTop(Z_Param_Value); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execMoveRight) \ { \ P_GET_PROPERTY(UFloatProperty,Z_Param_Value); \ P_FINISH; \ P_NATIVE_BEGIN; \ this->MoveRight(Z_Param_Value); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execMoveForward) \ { \ P_GET_PROPERTY(UFloatProperty,Z_Param_Value); \ P_FINISH; \ P_NATIVE_BEGIN; \ this->MoveForward(Z_Param_Value); \ P_NATIVE_END; \ } #define MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h_12_EVENT_PARMS \ struct NetPawn_eventServerMoveForward_Parms \ { \ float Value; \ FRotator Rotation; \ }; \ struct NetPawn_eventServerMoveRight_Parms \ { \ float Value; \ FRotator Rotation; \ }; \ struct NetPawn_eventServerMoveTop_Parms \ { \ float Value; \ FRotator Rotation; \ }; extern MULTIUSERTOOL_API FName MULTIUSERTOOL_ServerMoveForward; extern MULTIUSERTOOL_API FName MULTIUSERTOOL_ServerMoveRight; extern MULTIUSERTOOL_API FName MULTIUSERTOOL_ServerMoveTop; #define MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h_12_CALLBACK_WRAPPERS #define MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h_12_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesANetPawn(); \ friend MULTIUSERTOOL_API class UClass* Z_Construct_UClass_ANetPawn(); \ public: \ DECLARE_CLASS(ANetPawn, APawn, COMPILED_IN_FLAGS(0), 0, TEXT("/Script/MultiUserTool"), NO_API) \ DECLARE_SERIALIZER(ANetPawn) \ /** Indicates whether the class is compiled into the engine */ \ enum {IsIntrinsic=COMPILED_IN_INTRINSIC}; \ void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override; #define MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h_12_INCLASS \ private: \ static void StaticRegisterNativesANetPawn(); \ friend MULTIUSERTOOL_API class UClass* Z_Construct_UClass_ANetPawn(); \ public: \ DECLARE_CLASS(ANetPawn, APawn, COMPILED_IN_FLAGS(0), 0, TEXT("/Script/MultiUserTool"), NO_API) \ DECLARE_SERIALIZER(ANetPawn) \ /** Indicates whether the class is compiled into the engine */ \ enum {IsIntrinsic=COMPILED_IN_INTRINSIC}; \ void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override; #define MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h_12_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API ANetPawn(const FObjectInitializer& ObjectInitializer); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(ANetPawn) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, ANetPawn); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ANetPawn); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API ANetPawn(ANetPawn&&); \ NO_API ANetPawn(const ANetPawn&); \ public: #define MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h_12_ENHANCED_CONSTRUCTORS \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API ANetPawn(ANetPawn&&); \ NO_API ANetPawn(const ANetPawn&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, ANetPawn); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ANetPawn); \ DEFINE_DEFAULT_CONSTRUCTOR_CALL(ANetPawn) #define MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h_12_PRIVATE_PROPERTY_OFFSET #define MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h_9_PROLOG \ MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h_12_EVENT_PARMS #define MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h_12_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h_12_PRIVATE_PROPERTY_OFFSET \ MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h_12_RPC_WRAPPERS \ MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h_12_CALLBACK_WRAPPERS \ MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h_12_INCLASS \ MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h_12_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h_12_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h_12_PRIVATE_PROPERTY_OFFSET \ MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h_12_RPC_WRAPPERS_NO_PURE_DECLS \ MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h_12_CALLBACK_WRAPPERS \ MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h_12_INCLASS_NO_PURE_DECLS \ MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h_12_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #undef CURRENT_FILE_ID #define CURRENT_FILE_ID MultiUserToolrotoNew_4_15_Source_MultiUserTool_Public_NetPawn_h PRAGMA_ENABLE_DEPRECATION_WARNINGS
{ "content_hash": "3fbc99be8999b13fe01aa1647e7d0182", "timestamp": "", "source": "github", "line_count": 312, "max_line_length": 103, "avg_line_length": 34.32051282051282, "alnum_prop": 0.7065745237205827, "repo_name": "Aitordev/MultiUserTool", "id": "84b79e0749e42b32a25ef176673c231993bd1bf0", "size": "10708", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Intermediate/Build/Win64/UE4Editor/Inc/MultiUserTool/NetPawn.generated.h", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "48454" }, { "name": "C#", "bytes": "6004" }, { "name": "C++", "bytes": "9099775" }, { "name": "GLSL", "bytes": "28496" }, { "name": "HLSL", "bytes": "27928" }, { "name": "Objective-C", "bytes": "2912" }, { "name": "PLSQL", "bytes": "11660" } ], "symlink_target": "" }
% test_IsSameScene_BIN_SURF_imagePair_Oxford- testing IsSameScene_BIN_SURF % function for comparision if 2 images are of the % same scene (Oxford dataset) %************************************************************************** % author: Elena Ranguelova, NLeSc % date created: 08-05-2017 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % last modification date: % modification details: %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: %************************************************************************** % REFERENCES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% parameters [ exec_flags, exec_params, ~, cc_params, ... match_params, vis_params, paths] = config(mfilename, 'oxford'); v2struct(exec_flags) v2struct(paths) disp('******************************************************************************************************'); disp(' Demo: are 2 images from the Oxford dataset of the same scene (smart binarization + SURF descriptor)?'); disp('******************************************************************************************************'); %% visualize the test dataset if visualize_dataset if verbose disp('Displaying the test dataset...'); end display_oxford_dataset_structured(data_path_or); pause(5); end %% load test data if publish disp('Enter base test case [graffiti|leuven|boat|bikes] for the first image: '); disp('Enter the transformation degree [1(no transformation)|2|3|4|5|6]: '); test_case1 = 'leuven'; trans_deg1 = 1; test_case1 = 'graffiti'; trans_deg1 = 1; test_case1 = 'boat'; trans_deg1 = 3; test_case1 = 'bikes'; trans_deg1 = 1; test_case1 = 'bikes'; trans_deg1 = 2; test_case1 = 'boat'; trans_deg1 = 2; test_case1 = 'graffiti'; trans_deg1 = 4; test_case1 = 'leuven'; trans_deg1 = 2; disp([test_case1 num2str(trans_deg1)]); disp('Enter base test case [graffiti|leuven|boat|bikes] for the second image: '); disp('Enter the transformation degree [1(no transformation)|2|3|4|5|6]: '); test_case2 = 'leuven'; trans_deg2 = 4; test_case2 = 'graffiti'; trans_deg2 = 3; test_case2 = 'boat'; trans_deg2 = 5; test_case2 = 'bikes'; trans_deg2 = 6; test_case2 = 'boat'; trans_deg2 = 1; test_case2 = 'leuven'; trans_deg2 = 3; test_case2 = 'boat'; trans_deg2 = 4; est_case2 = 'bikes'; trans_deg2 = 2; disp([test_case2 num2str(trans_deg2)]); else % image one test_case1 = input('Enter base test case [graffiti|leuven|boat|bikes] for the first image: ','s'); trans_deg1 = input('Enter the transformation degree [1(no transformation)|2|3|4|5|6]: '); % image two test_case2 = input('Enter base test case [graffiti|leuven|boat|bikes] for the second image: ','s'); trans_deg2 = input('Enter the transformation degree [1(no transformation)|2|3|4|5|6]: '); end if verbose disp('Loading the 2 test images...'); if binarized disp('Already binarized images are used.'); end end test_path1 = fullfile(data_path_or,test_case1); test_path2 = fullfile(data_path_or,test_case2); test_image1 = fullfile(test_path1,[test_case1 num2str(trans_deg1) ext_or]); test_image2 = fullfile(test_path2,[test_case2 num2str(trans_deg2) ext_or]); im1 = imread(test_image1); im2 = imread(test_image2); bw1 = []; bw2 = []; if binarized test_bin_path1 = fullfile(data_path_bin,test_case1); test_bin_path2 = fullfile(data_path_bin,test_case2); test_bin_image1 = fullfile(test_bin_path1,[test_case1 num2str(trans_deg1) ext_bin]); test_bin_image2 = fullfile(test_bin_path2,[test_case2 num2str(trans_deg2) ext_bin]); bw1 = imread(test_bin_image1); bw2 = imread(test_bin_image2); end % visualize the choice if visualize_test if verbose disp('Displaying the test images'); end; fig_scrnsz = get(0, 'Screensize'); offset = 0.25 * fig_scrnsz(4); fig_scrnsz(2) = fig_scrnsz(2) + offset; fig_scrnsz(4) = fig_scrnsz(4) - offset; ff = figure; set(gcf, 'Position', fig_scrnsz); subplot(121);imshow(im1); title(['First image: ' test_case1 num2str(trans_deg1)]); subplot(122);imshow(im2); title(['Second image: ' test_case2 num2str(trans_deg2)]); pause(0.5); end %% compare if the 2 images show the same scene if verbose disp('Comparing the 2 test images...'); end disp('*****************************************************************'); if verbose disp('Comparing the 2 test images...'); end disp('*****************************************************************'); if not(binarized) if verbose disp('Data-driven binarization 1 (before comparision)...'); end [bw1,~] = data_driven_binarizer(im1); if verbose disp('Data-driven binarization 2 (before comparision)...'); end [bw2,~] = data_driven_binarizer(im2); end [is_same, num_matches, mean_cost, transf_sim] = IsSameScene_BIN_SURF(im1, im2,... bw1, bw2, cc_params, match_params, vis_params, exec_params); if verbose disp('*********************** DONE ************************'); end
{ "content_hash": "556a10471493fd0f6b37fccdb659f4b0", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 111, "avg_line_length": 37.514084507042256, "alnum_prop": 0.5397033977848695, "repo_name": "NLeSC/LargeScaleImaging", "id": "7535cb83df4cbce20d58bc33a8115df3931b3d9f", "size": "5327", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Software/MATLAB/Testing/comparision/test_IsSameScene_BIN_SURF_imagePair_Oxford.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "19591" }, { "name": "HTML", "bytes": "11833" }, { "name": "Matlab", "bytes": "818619" }, { "name": "PostScript", "bytes": "269112" }, { "name": "TeX", "bytes": "1387750" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta content="Python元类" name="description"> <meta name="keywords" content="Python,metaclass"> <meta name="author" content="Li"> <title> LTY|Python 元类 </title> <!-- favicon --> <link rel="shortcut icon" href="/static/img/1616.ico"> <!-- Third-party CSS --> <link href="/bower_components/normalize-css/normalize.min.css" rel="stylesheet"> <link href="/bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="/bower_components/animate.css/animate.min.css" rel="stylesheet"> <link href="/bower_components/components-font-awesome/css/font-awesome.min.css" rel="stylesheet"> <link href="/static/font-mfizz/font-mfizz.css" rel="stylesheet"> <!-- <link href="/bower_components/toastr/toastr.min.css" rel="stylesheet"> --> <link href="/bower_components/jquery.gritter/css/jquery.gritter.css" rel="stylesheet"> <link rel="stylesheet" href="/search/css/cb-search.css"> <!-- Custom styles for this template --> <link href="/static/css/style.min.css" rel="stylesheet"> <link href="/static/css/pygments.css" rel="stylesheet"> <!-- Scripts --> <script src="/bower_components/jquery/dist/jquery.min.js"></script> <script src="/search/js/bootstrap3-typeahead.min.js"></script> <!-- cb-search --> <script src="/search/js/cb-search.js"></script> <script> $(function(){ $("pre").css('display','block'); }); </script> <!-- Mainly scripts --> <script src="/bower_components/bootstrap/dist/js/bootstrap.min.js"></script> <script src="/bower_components/metisMenu/dist/metisMenu.min.js"></script> <script src="/bower_components/jquery-slimscroll/jquery.slimscroll.min.js"></script> <!-- Peity --> <script src="/bower_components/peity/jquery.peity.min.js"></script> <script src="/bower_components/PACE/pace.min.js"></script> <script src="/bower_components/wow/dist/wow.min.js"></script> <!-- Custom and plugin javascript --> <script src="/static/js/inspinia.js"></script> <!-- Rickshaw --> <script src="/bower_components/rickshaw/vendor/d3.v3.js"></script> <script src="/bower_components/rickshaw/rickshaw.min.js"></script> <!-- jPages --> <script src="/static/js/jPages.js"></script> <script src="/static/js/js.js"></script> <script id="dsq-count-scr" src="//jalpc.disqus.com/count.js" async></script> <script type="text/javascript"> $(function(){ /* initiate the plugin */ $("div.pag-holder").jPages({ containerID : "pag-itemContainer", perPage : 5, /* num of items per page */ startPage : 1, startRange : 1, midRange : 3, endRange : 1 }); }); </script> <!-- GrowingIO --> <script> var _vds = _vds || []; window._vds = _vds; (function(){ _vds.push(['setAccountId', 'a49d4901c7853da9']); (function() { var vds = document.createElement('script'); vds.type='text/javascript'; vds.async = true; vds.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'dn-growing.qbox.me/vds.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(vds, s); })(); })(); </script> </head> <body id="page-top" class="landing-page"> <div class="search-tool" style="position: fixed; top: 0px ; bottom: 0px; left: 0px; right: 0px; opacity: 0.95; background-color: #111111; z-index: 9999; display: none;"> <input type="text" class="form-control search-content" id="search-content" style="position: fixed; top: 60px" placeholder="Search Blog"> <div style="position: fixed; top: 16px; right: 16px; z-index: 9999;"> <img src="/search/img/cb-close.png" id="close-btn"/> </div> </div> <div style="position: fixed; right: 16px; bottom: 20px; z-index: 9999;"> <img src="/search/img/cb-search.png" id="search-btn" title="Double click Ctrl"/> </div> <div class="navbar-wrapper"> <nav class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header page-scroll"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/">LTY</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li><a class="page-scroll" href="/blog/"></a></li> <li> <a class="page-scroll" href="/blog/">Blog</a></li> <li> <a class="page-scroll" href="/python/">Python</a></li> <li> <a class="page-scroll" href="/wechat/">Wechat</a></li> <li> <a class="page-scroll" href="/php/">PHP</a></li> <li> <a class="page-scroll" href="/linux/">Linux</a></li> <li> <a class="page-scroll" href="/html/">HTML</a></li> <li> <a class="page-scroll" href="/database/">Database</a></li> <li> <a class="page-scroll" href="/framework/">Framework</a></li> <li> <a class="page-scroll" href="/mac/">Mac</a></li> <li> <a class="page-scroll" href="/life/">Life</a></li> </ul> </div> </div> </nav> </div> <div id="inSlider" class="carousel carousel-fade" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#inSlider" data-slide-to="0" class="active"></li> <li data-target="#inSlider" data-slide-to="1"></li> </ol> <div class="carousel-inner" role="listbox"> <div class="item active"> <div class="container"> <div class="carousel-caption"> </div> <div class="carousel-image wow zoomIn"> <!-- <img src="static/img/landing/laptop.png" alt="laptop"/> --> </div> </div> <!-- Set background for slide in css --> <div class="header-back one"></div> </div> <div class="item"> <div class="container"> <div class="carousel-caption blank"> </div> </div> <!-- Set background for slide in css --> <div class="header-back two"></div> </div> </div> <a class="left carousel-control" href="#inSlider" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#inSlider" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> <div class="wrapper wrapper-content animated fadeInRight article"> <div class="row"> <div class="col-lg-10 col-lg-offset-1"> <div class="ibox"> <div class="ibox-content"> <div class="pull-right"> <button class="btn btn-white btn-xs" type="button">Python</button> </div> <div class="text-center article-title"> <span class="text-muted"><i class="fa fa-clock-o"></i> 17 Feb 2016</span> <h1> Python 元类 </h1> </div> <h4 id="type">type()</h4> <p>动态语言和静态语言最大的不同,就是函数和类的定义,不是编译时定义的,而是运行时动态创建的。</p> <p>比方说我们要定义一个<code class="highlighter-rouge">Hello</code>的class,就写一个<code class="highlighter-rouge">hello.py</code>模块:</p> <div class="language-python highlighter-rouge"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Hello</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="k">def</span> <span class="nf">hello</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'world'</span><span class="p">):</span> <span class="k">print</span><span class="p">(</span><span class="s">'Hello, </span><span class="si">%</span><span class="s">s.'</span> <span class="o">%</span> <span class="n">name</span><span class="p">)</span> </code></pre> </div> <p>当Python解释器载入<code class="highlighter-rouge">hello</code>模块时,就会依次执行该模块的所有语句,执行结果就是动态创建出一个<code class="highlighter-rouge">Hello</code>的class对象,测试如下:</p> <div class="highlighter-rouge"><pre class="highlight"><code>&gt;&gt;&gt; from hello import Hello &gt;&gt;&gt; h = Hello() &gt;&gt;&gt; h.hello() Hello, world. &gt;&gt;&gt; print(type(Hello)) &lt;type 'type'&gt; &gt;&gt;&gt; print(type(h)) &lt;class 'hello.Hello'&gt; </code></pre> </div> <p><code class="highlighter-rouge">type()</code>函数可以查看一个类型或变量的类型,<code class="highlighter-rouge">Hello</code>是一个class,它的类型就是<code class="highlighter-rouge">type</code>,而<code class="highlighter-rouge">h</code>是一个实例,它的类型就是class <code class="highlighter-rouge">Hello</code>。</p> <p>我们说class的定义是运行时动态创建的,而创建class的方法就是使用<code class="highlighter-rouge">type()</code>函数。</p> <p><code class="highlighter-rouge">type()</code>函数既可以返回一个对象的类型,又可以创建出新的类型,比如,我们可以通过<code class="highlighter-rouge">type()</code>函数创建出<code class="highlighter-rouge">Hello</code>类,而无需通过<code class="highlighter-rouge">class Hello(object)...</code>的定义:</p> <div class="highlighter-rouge"><pre class="highlight"><code>&gt;&gt;&gt; def fn(self, name='world'): # 先定义函数 ... print('Hello, %s.' % name) ... &gt;&gt;&gt; Hello = type('Hello', (object,), dict(hello=fn)) # 创建Hello class &gt;&gt;&gt; h = Hello() &gt;&gt;&gt; h.hello() Hello, world. &gt;&gt;&gt; print(type(Hello)) &lt;type 'type'&gt; &gt;&gt;&gt; print(type(h)) &lt;class '__main__.Hello'&gt; </code></pre> </div> <p>要创建一个class对象,<code class="highlighter-rouge">type()</code>函数依次传入3个参数:</p> <ol> <li> <p>class的名称;</p> </li> <li> <p>继承的父类集合,注意Python支持多重继承,如果只有一个父类,别忘了tuple的单元素写法;</p> </li> <li> <p>class的方法名称与函数绑定,这里我们把函数fn绑定到方法名hello上。</p> </li> </ol> <p>通过<code class="highlighter-rouge">type()</code>函数创建的类和直接写class是完全一样的,因为Python解释器遇到class定义时,仅仅是扫描一下class定义的语法,然后调用<code class="highlighter-rouge">type()</code>函数创建出class。</p> <p>正常情况下,我们都用<code class="highlighter-rouge">class Xxx...</code>来定义类,但是,<code class="highlighter-rouge">type()</code>函数也允许我们动态创建出类来,也就是说,动态语言本身支持运行期动态创建类,这和静态语言有非常大的不同,要在静态语言运行期创建类,必须构造源代码字符串再调用编译器,或者借助一些工具生成字节码实现,本质上都是动态编译,会非常复杂。</p> <h4 id="metaclass">metaclass</h4> <p>除了使用<code class="highlighter-rouge">type()</code>动态创建类以外,要控制类的创建行为,还可以使用metaclass。</p> <p>metaclass,直译为元类,简单的解释就是:</p> <p>当我们定义了类以后,就可以根据这个类创建出实例,所以:先定义类,然后创建实例。</p> <p>但是如果我们想创建出类呢?那就必须根据metaclass创建出类,所以:先定义metaclass,然后创建类。</p> <p>连接起来就是:先定义metaclass,就可以创建类,最后创建实例。</p> <p>所以,metaclass允许你创建类或者修改类。换句话说,你可以把类看成是metaclass创建出来的“实例”。</p> <p>metaclass是Python面向对象里最难理解,也是最难使用的魔术代码。正常情况下,你不会碰到需要使用metaclass的情况,所以,以下内容看不懂也没关系,因为基本上你不会用到。</p> <p>我们先看一个简单的例子,这个metaclass可以给我们自定义的MyList增加一个<code class="highlighter-rouge">add</code>方法:</p> <p>定义<code class="highlighter-rouge">ListMetaclass</code>,按照默认习惯,metaclass的类名总是以Metaclass结尾,以便清楚地表示这是一个metaclass:</p> <div class="language-python highlighter-rouge"><pre class="highlight"><code><span class="c"># metaclass是创建类,所以必须从`type`类型派生:</span> <span class="k">class</span> <span class="nc">ListMetaclass</span><span class="p">(</span><span class="nb">type</span><span class="p">):</span> <span class="k">def</span> <span class="nf">__new__</span><span class="p">(</span><span class="n">cls</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="n">attrs</span><span class="p">):</span> <span class="n">attrs</span><span class="p">[</span><span class="s">'add'</span><span class="p">]</span> <span class="o">=</span> <span class="k">lambda</span> <span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">value</span><span class="p">)</span> <span class="k">return</span> <span class="nb">type</span><span class="o">.</span><span class="n">__new__</span><span class="p">(</span><span class="n">cls</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="n">attrs</span><span class="p">)</span> <span class="k">class</span> <span class="nc">MyList</span><span class="p">(</span><span class="nb">list</span><span class="p">):</span> <span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">ListMetaclass</span> <span class="c"># 指示使用ListMetaclass来定制类</span> </code></pre> </div> <p>当我们写下<code class="highlighter-rouge">__metaclass__ = ListMetaclass</code>语句时,魔术就生效了,它指示Python解释器在创建<code class="highlighter-rouge">MyList</code>时,要通过<code class="highlighter-rouge">ListMetaclass.__new__()</code>来创建,在此,我们可以修改类的定义,比如,加上新的方法,然后,返回修改后的定义。</p> <p><code class="highlighter-rouge">__new__()</code>方法接收到的参数依次是:</p> <ol> <li> <p>当前准备创建的类的对象;</p> </li> <li> <p>类的名字;</p> </li> <li> <p>类继承的父类集合;</p> </li> <li> <p>类的方法集合。</p> </li> </ol> <p>测试一下<code class="highlighter-rouge">MyList</code>是否可以调用<code class="highlighter-rouge">add()</code>方法:</p> <div class="highlighter-rouge"><pre class="highlight"><code>&gt;&gt;&gt; L = MyList() &gt;&gt;&gt; L.add(1) &gt;&gt;&gt; L [1] </code></pre> </div> <p>而普通的<code class="highlighter-rouge">list</code>没有<code class="highlighter-rouge">add()</code>方法:</p> <div class="highlighter-rouge"><pre class="highlight"><code>&gt;&gt;&gt; l = list() &gt;&gt;&gt; l.add(1) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'list' object has no attribute 'add' </code></pre> </div> <p>动态修改有什么意义?直接在<code class="highlighter-rouge">MyList</code>定义中写上<code class="highlighter-rouge">add()</code>方法不是更简单吗?正常情况下,确实应该直接写,通过metaclass修改纯属变态。</p> <p>但是,总会遇到需要通过metaclass修改类定义的。ORM就是一个典型的例子。</p> <p>ORM全称“Object Relational Mapping”,即对象-关系映射,就是把关系数据库的一行映射为一个对象,也就是一个类对应一个表,这样,写代码更简单,不用直接操作SQL语句。</p> <p>要编写一个ORM框架,所有的类都只能动态定义,因为只有使用者才能根据表的结构定义出对应的类来。</p> <p>让我们来尝试编写一个ORM框架。</p> <p>编写底层模块的第一步,就是先把调用接口写出来。比如,使用者如果使用这个ORM框架,想定义一个<code class="highlighter-rouge">User</code>类来操作对应的数据库表<code class="highlighter-rouge">User</code>,我们期待他写出这样的代码:</p> <div class="language-python highlighter-rouge"><pre class="highlight"><code><span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">Model</span><span class="p">):</span> <span class="c"># 定义类的属性到列的映射:</span> <span class="nb">id</span> <span class="o">=</span> <span class="n">IntegerField</span><span class="p">(</span><span class="s">'id'</span><span class="p">)</span> <span class="n">name</span> <span class="o">=</span> <span class="n">StringField</span><span class="p">(</span><span class="s">'username'</span><span class="p">)</span> <span class="n">email</span> <span class="o">=</span> <span class="n">StringField</span><span class="p">(</span><span class="s">'email'</span><span class="p">)</span> <span class="n">password</span> <span class="o">=</span> <span class="n">StringField</span><span class="p">(</span><span class="s">'password'</span><span class="p">)</span> <span class="c"># 创建一个实例:</span> <span class="n">u</span> <span class="o">=</span> <span class="n">User</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">12345</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'Michael'</span><span class="p">,</span> <span class="n">email</span><span class="o">=</span><span class="s">'test@orm.org'</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">'my-pwd'</span><span class="p">)</span> <span class="c"># 保存到数据库:</span> <span class="n">u</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> </code></pre> </div> <p>其中,父类<code class="highlighter-rouge">Model</code>和属性类型<code class="highlighter-rouge">StringField</code>、<code class="highlighter-rouge">IntegerField</code>是由ORM框架提供的,剩下的魔术方法比如<code class="highlighter-rouge">save()</code>全部由metaclass自动完成。虽然metaclass的编写会比较复杂,但ORM的使用者用起来却异常简单。</p> <p>现在,我们就按上面的接口来实现该ORM。</p> <p>首先来定义<code class="highlighter-rouge">Field</code>类,它负责保存数据库表的字段名和字段类型:</p> <div class="language-python highlighter-rouge"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Field</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">column_type</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span> <span class="bp">self</span><span class="o">.</span><span class="n">column_type</span> <span class="o">=</span> <span class="n">column_type</span> <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="s">'&lt;</span><span class="si">%</span><span class="s">s:</span><span class="si">%</span><span class="s">s&gt;'</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">__class__</span><span class="o">.</span><span class="n">__name__</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">)</span> </code></pre> </div> <p>在<code class="highlighter-rouge">Field</code>的基础上,进一步定义各种类型的<code class="highlighter-rouge">Field</code>,比如<code class="highlighter-rouge">StringField</code>,<code class="highlighter-rouge">IntegerField</code>等等:</p> <div class="language-python highlighter-rouge"><pre class="highlight"><code><span class="k">class</span> <span class="nc">StringField</span><span class="p">(</span><span class="n">Field</span><span class="p">):</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span> <span class="nb">super</span><span class="p">(</span><span class="n">StringField</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="s">'varchar(100)'</span><span class="p">)</span> <span class="k">class</span> <span class="nc">IntegerField</span><span class="p">(</span><span class="n">Field</span><span class="p">):</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span> <span class="nb">super</span><span class="p">(</span><span class="n">IntegerField</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="s">'bigint'</span><span class="p">)</span> </code></pre> </div> <p>下一步,就是编写最复杂的<code class="highlighter-rouge">ModelMetaclass</code>了:</p> <div class="language-python highlighter-rouge"><pre class="highlight"><code><span class="k">class</span> <span class="nc">ModelMetaclass</span><span class="p">(</span><span class="nb">type</span><span class="p">):</span> <span class="k">def</span> <span class="nf">__new__</span><span class="p">(</span><span class="n">cls</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="n">attrs</span><span class="p">):</span> <span class="k">if</span> <span class="n">name</span><span class="o">==</span><span class="s">'Model'</span><span class="p">:</span> <span class="k">return</span> <span class="nb">type</span><span class="o">.</span><span class="n">__new__</span><span class="p">(</span><span class="n">cls</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="n">attrs</span><span class="p">)</span> <span class="n">mappings</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">()</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">attrs</span><span class="o">.</span><span class="n">iteritems</span><span class="p">():</span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">v</span><span class="p">,</span> <span class="n">Field</span><span class="p">):</span> <span class="k">print</span><span class="p">(</span><span class="s">'Found mapping: </span><span class="si">%</span><span class="s">s==&gt;</span><span class="si">%</span><span class="s">s'</span> <span class="o">%</span> <span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="n">v</span><span class="p">))</span> <span class="n">mappings</span><span class="p">[</span><span class="n">k</span><span class="p">]</span> <span class="o">=</span> <span class="n">v</span> <span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="n">mappings</span><span class="o">.</span><span class="n">iterkeys</span><span class="p">():</span> <span class="n">attrs</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="n">k</span><span class="p">)</span> <span class="n">attrs</span><span class="p">[</span><span class="s">'__table__'</span><span class="p">]</span> <span class="o">=</span> <span class="n">name</span> <span class="c"># 假设表名和类名一致</span> <span class="n">attrs</span><span class="p">[</span><span class="s">'__mappings__'</span><span class="p">]</span> <span class="o">=</span> <span class="n">mappings</span> <span class="c"># 保存属性和列的映射关系</span> <span class="k">return</span> <span class="nb">type</span><span class="o">.</span><span class="n">__new__</span><span class="p">(</span><span class="n">cls</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="n">attrs</span><span class="p">)</span> </code></pre> </div> <p>以及基类<code class="highlighter-rouge">Model</code>:</p> <div class="language-python highlighter-rouge"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Model</span><span class="p">(</span><span class="nb">dict</span><span class="p">):</span> <span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">ModelMetaclass</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span> <span class="nb">super</span><span class="p">(</span><span class="n">Model</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="o">**</span><span class="n">kw</span><span class="p">)</span> <span class="k">def</span> <span class="nf">__getattr__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span> <span class="k">try</span><span class="p">:</span> <span class="k">return</span> <span class="bp">self</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="k">except</span> <span class="nb">KeyError</span><span class="p">:</span> <span class="k">raise</span> <span class="nb">AttributeError</span><span class="p">(</span><span class="s">r"'Model' object has no attribute '</span><span class="si">%</span><span class="s">s'"</span> <span class="o">%</span> <span class="n">key</span><span class="p">)</span> <span class="k">def</span> <span class="nf">__setattr__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span> <span class="bp">self</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">value</span> <span class="k">def</span> <span class="nf">save</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">fields</span> <span class="o">=</span> <span class="p">[]</span> <span class="n">params</span> <span class="o">=</span> <span class="p">[]</span> <span class="n">args</span> <span class="o">=</span> <span class="p">[]</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">__mappings__</span><span class="o">.</span><span class="n">iteritems</span><span class="p">():</span> <span class="n">fields</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">v</span><span class="o">.</span><span class="n">name</span><span class="p">)</span> <span class="n">params</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s">'?'</span><span class="p">)</span> <span class="n">args</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="nb">getattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">k</span><span class="p">,</span> <span class="bp">None</span><span class="p">))</span> <span class="n">sql</span> <span class="o">=</span> <span class="s">'insert into </span><span class="si">%</span><span class="s">s (</span><span class="si">%</span><span class="s">s) values (</span><span class="si">%</span><span class="s">s)'</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">__table__</span><span class="p">,</span> <span class="s">','</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">fields</span><span class="p">),</span> <span class="s">','</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">params</span><span class="p">))</span> <span class="k">print</span><span class="p">(</span><span class="s">'SQL: </span><span class="si">%</span><span class="s">s'</span> <span class="o">%</span> <span class="n">sql</span><span class="p">)</span> <span class="k">print</span><span class="p">(</span><span class="s">'ARGS: </span><span class="si">%</span><span class="s">s'</span> <span class="o">%</span> <span class="nb">str</span><span class="p">(</span><span class="n">args</span><span class="p">))</span> </code></pre> </div> <p>当用户定义一个<code class="highlighter-rouge">class User(Model)</code>时,Python解释器首先在当前类<code class="highlighter-rouge">User</code>的定义中查找<code class="highlighter-rouge">__metaclass__</code>,如果没有找到,就继续在父类<code class="highlighter-rouge">Model</code>中查找<code class="highlighter-rouge">__metaclass__</code>,找到了,就使用<code class="highlighter-rouge">Model</code>中定义的<code class="highlighter-rouge">__metaclass__</code>的<code class="highlighter-rouge">ModelMetaclass</code>来创建<code class="highlighter-rouge">User</code>类,也就是说,metaclass可以隐式地继承到子类,但子类自己却感觉不到。</p> <p>在<code class="highlighter-rouge">ModelMetaclass</code>中,一共做了几件事情:</p> <ol> <li> <p>排除掉对<code class="highlighter-rouge">Model</code>类的修改;</p> </li> <li> <p>在当前类(比如<code class="highlighter-rouge">User</code>)中查找定义的类的所有属性,如果找到一个Field属性,就把它保存到一个<code class="highlighter-rouge">__mappings__</code>的dict中,同时从类属性中删除该Field属性,否则,容易造成运行时错误;</p> </li> <li> <p>把表名保存到<code class="highlighter-rouge">__table__</code>中,这里简化为表名默认为类名。</p> </li> </ol> <p>在<code class="highlighter-rouge">Model</code>类中,就可以定义各种操作数据库的方法,比如<code class="highlighter-rouge">save()</code>,<code class="highlighter-rouge">delete()</code>,<code class="highlighter-rouge">find()</code>,<code class="highlighter-rouge">update</code>等等。</p> <p>我们实现了<code class="highlighter-rouge">save()</code>方法,把一个实例保存到数据库中。因为有表名,属性到字段的映射和属性值的集合,就可以构造出INSERT语句。</p> <p>编写代码试试:</p> <div class="language-python highlighter-rouge"><pre class="highlight"><code><span class="n">u</span> <span class="o">=</span> <span class="n">User</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">12345</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'Michael'</span><span class="p">,</span> <span class="n">email</span><span class="o">=</span><span class="s">'test@orm.org'</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">'my-pwd'</span><span class="p">)</span> <span class="n">u</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> </code></pre> </div> <p>输出如下:</p> <div class="highlighter-rouge"><pre class="highlight"><code>Found model: User Found mapping: email ==&gt; &lt;StringField:email&gt; Found mapping: password ==&gt; &lt;StringField:password&gt; Found mapping: id ==&gt; &lt;IntegerField:uid&gt; Found mapping: name ==&gt; &lt;StringField:username&gt; SQL: insert into User (password,email,username,uid) values (?,?,?,?) ARGS: ['my-pwd', 'test@orm.org', 'Michael', 12345] </code></pre> </div> <p>可以看到,<code class="highlighter-rouge">save()</code>方法已经打印出了可执行的SQL语句,以及参数列表,只需要真正连接到数据库,执行该SQL语句,就可以完成真正的功能。</p> <p>不到100行代码,我们就通过metaclass实现了一个精简的ORM框架,完整的代码从这里下载:</p> <p><a href="https://github.com/michaelliao/learn-python/blob/master/metaclass/simple_orm.py">https://github.com/michaelliao/learn-python/blob/master/metaclass/simple_orm.py</a></p> <p>最后解释一下类属性和实例属性。直接在class中定义的是类属性:</p> <div class="language-python highlighter-rouge"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Student</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="n">name</span> <span class="o">=</span> <span class="s">'Student'</span> </code></pre> </div> <p>实例属性必须通过实例来绑定,比如<code class="highlighter-rouge">self.name = 'xxx'</code>。来测试一下:</p> <div class="highlighter-rouge"><pre class="highlight"><code>&gt;&gt;&gt; # 创建实例s: &gt;&gt;&gt; s = Student() &gt;&gt;&gt; # 打印name属性,因为实例并没有name属性,所以会继续查找class的name属性: &gt;&gt;&gt; print(s.name) Student &gt;&gt;&gt; # 这和调用Student.name是一样的: &gt;&gt;&gt; print(Student.name) Student &gt;&gt;&gt; # 给实例绑定name属性: &gt;&gt;&gt; s.name = 'Michael' &gt;&gt;&gt; # 由于实例属性优先级比类属性高,因此,它会屏蔽掉类的name属性: &gt;&gt;&gt; print(s.name) Michael &gt;&gt;&gt; # 但是类属性并未消失,用Student.name仍然可以访问: &gt;&gt;&gt; print(Student.name) Student &gt;&gt;&gt; # 如果删除实例的name属性: &gt;&gt;&gt; del s.name &gt;&gt;&gt; # 再次调用s.name,由于实例的name属性没有找到,类的name属性就显示出来了: &gt;&gt;&gt; print(s.name) Student </code></pre> </div> <p>因此,在编写程序的时候,千万不要把实例属性和类属性使用相同的名字。</p> <p>在我们编写的ORM中,<code class="highlighter-rouge">ModelMetaclass</code>会删除掉User类的所有类属性,目的就是避免造成混淆。</p> <p>转自<a href="http://www.liaoxuefeng.com">廖雪峰</a>的网站</p> <hr> <div class="row"> <div class="col-md-6"> <h5 style="display: inline;">Tags:</h5> <button class="btn btn-white btn-xs" type="button">metaclass</button> </div> <div class="col-md-6"> <div class="small text-right"> <h5>Stats:</h5> <div> <i class="fa fa-comments-o"> </i> <span class='disqus-comment-count' data-disqus-url="http://www.ltybr.com//python/2016/02/17/python-class.html">0</span> comments </div> </div> </div> </div> <br> <div class="row"> <div class="col-lg-12"> <!-- donate --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal2"> Donate </button> <div class="modal inmodal" id="myModal2" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content animated flipInY"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> <h4 class="modal-title">Donate Me</h4> <small class="font-bold">Thanks for your support!</small> </div> <div class="modal-body"> <div class="tabbable" id="tabs-960227"> <ul class="nav nav-tabs"> <li class="active"> <a href="#panel-405278" data-toggle="tab">Alipay</a> </li> <li> <a href="#panel-874705" data-toggle="tab">Wechat</a> </li> </ul> <div class="tab-content"> <div class="tab-pane active" id="panel-405278"> <div class="text-center"> <img src="/static/img/pay/alipay.png"" height="250" width="250"> </div> </div> <div class="tab-pane" id="panel-874705"> <div class="text-center"> <img src="/static/img/pay/wechat.png"" height="250" width="250"> </div> </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-white" data-dismiss="modal">Close</button> </div> </div> </div> </div> <br> <!-- share --> <h2>Share:</h2> <div class="bshare-custom"> <a title="分享到微信" class="bshare-weixin"></a> <a title="分享到QQ空间" class="bshare-qzone"></a> <a title="分享到新浪微博" class="bshare-sinaminiblog"></a> <a title="更多平台" class="bshare-more bshare-more-icon more-style-addthis"></a> </div> <script type="text/javascript" charset="utf-8" src="http://static.bshare.cn/b/buttonLite.js#style=-1&amp;uuid=513f778e-a8f7-4c20-9ec2-d29cc2328d75&amp;pophcol=1&amp;lang=zh"></script> <script type="text/javascript" charset="utf-8" src="http://static.bshare.cn/b/bshareC0.js"></script> <br> <!-- comment --> <div id="disqus_thread"></div> <script> /** * RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS. * LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables */ /* var disqus_config = function () { this.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; */ (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = '//jalpc.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript" rel="nofollow">comments powered by Disqus.</a></noscript> </div> </div> </div> </div> </div> </div> </div> <script src="/static/js/scroll.js"></script> <!-- Baidu analytics --> <!-- Google analytics --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-73784599-1', 'auto'); ga('send', 'pageview'); </script> <script type="text/javascript"> var disqusShortName = "jalpc"; var disqusPublicKey = "tj2MPaNlHMONwTH5bGDNSXyaBpW7q282MeUzh5CwcjJerNhK8Kxk3aWo7IckzTX7"; var urlArray = []; $('.disqus-comment-count').each(function () { var url = $(this).attr('data-disqus-url'); urlArray.push('link:' + url); }); $.ajax({ type: 'GET', url: "https://disqus.com/api/3.0/threads/set.jsonp", data: { api_key: disqusPublicKey, forum : disqusShortName, thread : urlArray }, cache: false, dataType: "jsonp", success: function (result) { for (var i in result.response) { var count = result.response[i].posts; if ( count ) { $('.disqus-comment-count[data-disqus-url="' + result.response[i].link + '"]').html(count); } } } }); </script> <script async src="/static/js/count_page.js"></script> </body> </html>
{ "content_hash": "da77154a9774f95218f66ce760cdf4ea", "timestamp": "", "source": "github", "line_count": 744, "max_line_length": 727, "avg_line_length": 54.704301075268816, "alnum_prop": 0.5812776412776413, "repo_name": "ilty/ilty.github.io", "id": "22cf23f55532e4d7e966b505d702a365abe343de", "size": "44888", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_site/python/2016/02/17/python-class.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "777584" }, { "name": "HTML", "bytes": "2108573" }, { "name": "JavaScript", "bytes": "101980" }, { "name": "Shell", "bytes": "1588" } ], "symlink_target": "" }
// Copyright 2011-2016 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. package com.google.security.zynamics.binnavi.Gui.CriteriaDialog.Conditions.NodeColor; import com.google.security.zynamics.binnavi.yfileswrap.zygraph.NaviNode; import java.awt.Color; /** * Used to evaluate color criteria maches. */ public final class CColorEvaluator { /** * You are not supposed to instantiate this class. */ private CColorEvaluator() { } /** * Evaluates a color criterium match on a node. * * @param node The node to check. * @param color The color to compare the node color to. * * @return True, if the node color matches the given color. False, otherwise. */ public static boolean evaluate(final NaviNode node, final Color color) { return node.getRawNode().getColor().equals(color); } }
{ "content_hash": "06097485e2a579fcd14e3a078146bfd1", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 85, "avg_line_length": 31.27906976744186, "alnum_prop": 0.7278810408921933, "repo_name": "google/binnavi", "id": "1b6e0f37aeed430b1dd53ae278925de19ddc5b1f", "size": "1345", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/com/google/security/zynamics/binnavi/Gui/CriteriaDialog/Conditions/NodeColor/CColorEvaluator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1489" }, { "name": "C", "bytes": "8997" }, { "name": "C++", "bytes": "982064" }, { "name": "CMake", "bytes": "1953" }, { "name": "CSS", "bytes": "12843" }, { "name": "GAP", "bytes": "3637" }, { "name": "HTML", "bytes": "437459" }, { "name": "Java", "bytes": "21714625" }, { "name": "Makefile", "bytes": "3498" }, { "name": "PLpgSQL", "bytes": "180849" }, { "name": "Python", "bytes": "23981" }, { "name": "Shell", "bytes": "713" } ], "symlink_target": "" }
package com.sap.hcp.cf.logging.servlet.dynlog; import javax.servlet.ServletException; import com.auth0.jwt.exceptions.JWTVerificationException; public class DynamicLogLevelException extends ServletException { private static final long serialVersionUID = 1L; public DynamicLogLevelException(String message, JWTVerificationException cause) { super(message, cause); } public DynamicLogLevelException(String message) { super(message); } }
{ "content_hash": "bd9db54457c59d6cee7042b0785ebc1e", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 85, "avg_line_length": 26.157894736842106, "alnum_prop": 0.7344064386317908, "repo_name": "ChristophEichhorn/cf-java-logging-support", "id": "b89218cdaca0f8e3aaeb85a7ab5e46060ba56bb0", "size": "497", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cf-java-logging-support-servlet/src/main/java/com/sap/hcp/cf/logging/servlet/dynlog/DynamicLogLevelException.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "271108" }, { "name": "Python", "bytes": "10095" }, { "name": "Ruby", "bytes": "566" } ], "symlink_target": "" }
from __future__ import unicode_literals, division, absolute_import from difflib import SequenceMatcher import logging import re import urllib import requests from sqlalchemy import Table, Column, Integer, String, Unicode, Boolean, func from sqlalchemy.orm import relation from sqlalchemy.schema import ForeignKey from flexget import db_schema as schema from flexget import plugin from flexget.event import event from flexget.plugins.filter.series import normalize_series_name from flexget.utils.database import with_session api_key = '6c228565a45a302e49fb7d2dab066c9ab948b7be/' search_show = 'http://api.trakt.tv/search/shows.json/' episode_summary = 'http://api.trakt.tv/show/episode/summary.json/' show_summary = 'http://api.trakt.tv/show/summary.json/' Base = schema.versioned_base('api_trakt', 2) log = logging.getLogger('api_trakt') class TraktContainer(object): def __init__(self, init_dict=None): if isinstance(init_dict, dict): self.update_from_dict(init_dict) def update_from_dict(self, update_dict): for col in self.__table__.columns: if isinstance(update_dict.get(col.name), (basestring, int, float)): setattr(self, col.name, update_dict[col.name]) genres_table = Table('trakt_series_genres', Base.metadata, Column('tvdb_id', Integer, ForeignKey('trakt_series.tvdb_id')), Column('genre_id', Integer, ForeignKey('trakt_genres.id'))) class TraktGenre(TraktContainer, Base): __tablename__ = 'trakt_genres' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, nullable=True) actors_table = Table('trakt_series_actors', Base.metadata, Column('tvdb_id', Integer, ForeignKey('trakt_series.tvdb_id')), Column('actors_id', Integer, ForeignKey('trakt_actors.id'))) class TraktActors(TraktContainer, Base): __tablename__ = 'trakt_actors' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, nullable=False) class TraktEpisode(TraktContainer, Base): __tablename__ = 'trakt_episodes' tvdb_id = Column(Integer, primary_key=True, autoincrement=False) episode_name = Column(Unicode) season = Column(Integer) number = Column(Integer) overview = Column(Unicode) expired = Column(Boolean) first_aired = Column(Integer) first_aired_iso = Column(Unicode) first_aired_utc = Column(Integer) screen = Column(Unicode) series_id = Column(Integer, ForeignKey('trakt_series.tvdb_id'), nullable=False) class TraktSeries(TraktContainer, Base): __tablename__ = 'trakt_series' tvdb_id = Column(Integer, primary_key=True, autoincrement=False) tvrage_id = Column(Unicode) imdb_id = Column(Unicode) title = Column(Unicode) year = Column(Integer) genre = relation('TraktGenre', secondary=genres_table, backref='series') network = Column(Unicode, nullable=True) certification = Column(Unicode) country = Column(Unicode) overview = Column(Unicode) first_aired = Column(Integer) first_aired_iso = Column(Unicode) first_aired_utc = Column(Integer) air_day = Column(Unicode) air_day_utc = Column(Unicode) air_time = Column(Unicode) air_time_utc = Column(Unicode) runtime = Column(Integer) last_updated = Column(Integer) poster = Column(String) fanart = Column(String) banner = Column(String) status = Column(String) url = Column(Unicode) episodes = relation('TraktEpisode', backref='series', cascade='all, delete, delete-orphan') actors = relation('TraktActors', secondary=actors_table, backref='series') def update(self, session): tvdb_id = self.tvdb_id url = ('%s%s%s' % (show_summary, api_key, tvdb_id)) try: data = requests.get(url).json() except requests.RequestException as e: raise LookupError('Request failed %s' % url) if data: if data['title']: for i in data['images']: data[i] = data['images'][i] if data['genres']: genres = {} for genre in data['genres']: db_genre = session.query(TraktGenre).filter(TraktGenre.name == genre).first() if not db_genre: genres['name'] = genre db_genre = TraktGenre(genres) if db_genre not in self.genre: self.genre.append(db_genre) if data['people']['actors']: series_actors = data['people']['actors'] for i in series_actors: if i['name']: db_character = session.query(TraktActors).filter(TraktActors.name == i['name']).first() if not db_character: db_character = TraktActors(i) if db_character not in self.actors: self.actors.append(db_character) if data['title']: TraktContainer.update_from_dict(self, data) else: raise LookupError('Could not update information to database for Trakt on ') def __repr__(self): return '<Traktv Name=%s, TVDB_ID=%s>' % (self.title, self.tvdb_id) class TraktSearchResult(Base): __tablename__ = 'trakt_search_results' id = Column(Integer, primary_key=True) search = Column(Unicode, nullable=False) series_id = Column(Integer, ForeignKey('trakt_series.tvdb_id'), nullable=True) series = relation(TraktSeries, backref='search_strings') def get_series_id(title): norm_series_name = normalize_series_name(title) series_name = urllib.quote_plus(norm_series_name) url = search_show + api_key + series_name series = None try: response = requests.get(url) except requests.RequestException: log.warning('Request failed %s' % url) return try: data = response.json() except ValueError: log.debug('Error Parsing Traktv Json for %s' % title) return if 'status' in data: log.debug('Returned Status %s' % data['status']) else: for item in data: if normalize_series_name(item['title']) == norm_series_name: series = item['tvdb_id'] if not series: for item in data: title_match = SequenceMatcher(lambda x: x in '\t', normalize_series_name(item['title']), norm_series_name).ratio() if not series and title_match > .9: log.debug('Warning: Using lazy matching because title was not found exactly for %s' % title) series = item['tvdb_id'] if not series: log.debug('Trakt.tv Returns only EXACT Name Matching: %s' % title) return series class ApiTrakt(object): @staticmethod @with_session def lookup_series(title=None, tvdb_id=None, only_cached=False, session=None): if not title and not tvdb_id: raise LookupError('No criteria specified for Trakt.tv Lookup') series = None def id_str(): return '<name=%s, tvdb_id=%s>' % (title, tvdb_id) if tvdb_id: series = session.query(TraktSeries).filter(TraktSeries.tvdb_id == tvdb_id).first() if not series and title: series_filter = session.query(TraktSeries).filter(func.lower(TraktSeries.title) == title.lower()) series = series_filter.first() if not series: found = session.query(TraktSearchResult).filter(func.lower(TraktSearchResult.search) == title.lower()).first() if found and found.series: series = found.series if not series: if only_cached: raise LookupError('Series %s not found from cache' % id_str()) log.debug('Series %s not found in cache, looking up from trakt.' % id_str()) if tvdb_id is not None: series = TraktSeries() series.tvdb_id = tvdb_id series.update(session=session) if series.title: session.add(series) if tvdb_id is None and title is not None: series_lookup = get_series_id(title) if series_lookup: series = session.query(TraktSeries).filter(TraktSeries.tvdb_id == series_lookup).first() if not series and series_lookup: series = TraktSeries() series.tvdb_id = series_lookup series.update(session=session) if series.title: session.add(series) if title.lower() != series.title.lower(): session.add(TraktSearchResult(search=title, series=series)) else: raise LookupError('Unknown Series title from Traktv: %s' % id_str()) if not series: raise LookupError('No results found from traktv for %s' % id_str()) if not series.title: raise LookupError('Nothing Found for %s' % id_str()) if series: series.episodes series.genre series.actors return series @staticmethod @with_session def lookup_episode(title=None, seasonnum=None, episodenum=None, tvdb_id=None, session=None, only_cached=False): series = ApiTrakt.lookup_series(title=title, tvdb_id=tvdb_id, only_cached=only_cached, session=session) if not series: raise LookupError('Could not identify series') if series.tvdb_id: ep_description = '%s.S%sE%s' % (series.title, seasonnum, episodenum) episode = session.query(TraktEpisode).filter(TraktEpisode.series_id == series.tvdb_id).\ filter(TraktEpisode.season == seasonnum).filter(TraktEpisode.number == episodenum).first() url = episode_summary + api_key + '%s/%s/%s' % (series.tvdb_id, seasonnum, episodenum) elif title: title = normalize_series_name(title) title = re.sub(' ', '-', title) ep_description = '%s.S%sE%s' % (series.title, seasonnum, episodenum) episode = session.query(TraktEpisode).filter(title == series.title).\ filter(TraktEpisode.season == seasonnum).\ filter(TraktEpisode.number == episodenum).first() url = episode_summary + api_key + '%s/%s/%s' % (title, seasonnum, episodenum) if not episode: if only_cached: raise LookupError('Episode %s not found in cache' % ep_description) log.debug('Episode %s not found in cache, looking up from trakt.' % ep_description) try: data = requests.get(url) except requests.RequestException: log.debug('Error Retrieving Trakt url: %s' % url) try: data = data.json() except ValueError: log.debug('Error parsing Trakt episode json for %s' % title) if data: if 'status' in data: raise LookupError('Error looking up episode') ep_data = data['episode'] if ep_data: episode = session.query(TraktEpisode).filter(TraktEpisode.tvdb_id == ep_data['tvdb_id']).first() if not episode: ep_data['episode_name'] = ep_data.pop('title') for i in ep_data['images']: ep_data[i] = ep_data['images'][i] del ep_data['images'] episode = TraktEpisode(ep_data) series.episodes.append(episode) session.merge(episode) if episode: return episode else: raise LookupError('No results found for (%s)' % episode) @event('plugin.register') def register_plugin(): plugin.register(ApiTrakt, 'api_trakt', api_ver=2)
{ "content_hash": "581b8fe9051d4ae87553acc22536da66", "timestamp": "", "source": "github", "line_count": 300, "max_line_length": 116, "avg_line_length": 40.89333333333333, "alnum_prop": 0.5841212911640039, "repo_name": "voriux/Flexget", "id": "cc95851925484ee131e00806c713eec4d20d03f4", "size": "12268", "binary": false, "copies": "4", "ref": "refs/heads/develop", "path": "flexget/plugins/api_trakt.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "56725" }, { "name": "JavaScript", "bytes": "455222" }, { "name": "Python", "bytes": "1849035" } ], "symlink_target": "" }
// Copyright 2015 Google Inc. 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. import {LabelKeyNameLengthValidator} from 'deploy/validators/labelkeynamelengthvalidator'; describe('Label key name length validator', () => { /** @type {!LabelValuePatternValidator} */ let labelKeyNameLengthValidator; beforeEach(() => { angular.mock.inject(() => { labelKeyNameLengthValidator = new LabelKeyNameLengthValidator(); }); }); it('should set validity to false when key name exceeds 63 characters ', () => { // given let stringLength = 64; let failNameNoPrefix = (new Array(stringLength + 1).join('x')); let failNameWithPrefix = `validprefix.com/${failNameNoPrefix}`; let failKeyNames = [ failNameNoPrefix, failNameWithPrefix, ]; // then failKeyNames.forEach( (failKeyName) => { expect(labelKeyNameLengthValidator.isValid(failKeyName)).toBeFalsy(); }); }); it('should set validity to true when key name does not exceed 63 characters ', () => { // given let stringLength = 63; let passNameNoPrefix = (new Array(stringLength + 1).join('x')); let passNameWithPrefix = `validprefix.com/${passNameNoPrefix}`; let passKeyNames = [ passNameNoPrefix, passNameWithPrefix, ]; // then passKeyNames.forEach((passKeyName) => { expect(labelKeyNameLengthValidator.isValid(passKeyName)).toBeTruthy(); }); }); });
{ "content_hash": "66742d47a720081fbcf589ea37eaab97", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 100, "avg_line_length": 35.45454545454545, "alnum_prop": 0.6943589743589743, "repo_name": "taimir/dashboard", "id": "c333559215e6d56869be1cbc03d9fa62248a5ca0", "size": "1950", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "src/test/frontend/deploy/validators/labelkeynamelengthvalidator_test.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "43878" }, { "name": "Go", "bytes": "383743" }, { "name": "HTML", "bytes": "193488" }, { "name": "JavaScript", "bytes": "899466" }, { "name": "Shell", "bytes": "4400" } ], "symlink_target": "" }
/* eslint complexity:0 */ import isNumber from 'lodash/fp/isNumber'; import isString from 'lodash/fp/isString'; import isArray from 'lodash/fp/isArray'; import isObject from 'lodash/fp/isObject'; import isEmpty from 'lodash/fp/isEmpty'; import isUndefined from 'lodash/fp/isUndefined'; import defaultsDeep from 'lodash/fp/defaultsDeep'; import pickBy from 'lodash/fp/pickBy'; import map from 'lodash/fp/map'; import flow from 'lodash/fp/flow'; import createClient from './create-client'; const defaults = { operators: 'jsonb', limit: 0, offset: 0, orderBy: 'updatedAt', direction: 'desc', caseInsensitive: false }; const compact = pickBy(x => !isUndefined(x)); const isEmptyObject = flow( compact, isEmpty ); const convertToJson = (column, options = {}) => search => { const [key, val] = search; if (isNumber(val)) { return `("${column}" ->> '${key}')::int = ${val}`; } if (options.caseInsensitive) { return `lower("${column}" ->> '${key}') = lower('${val}')`; } return `"${column}" ->> '${key}' = '${val}'`; }; const getQueryTextJson = ({key, not, columnNames, caseInsensitive}) => { const toJson = convertToJson(columnNames.val, {caseInsensitive}); const search = key || not; if (isArray(search)) { const facets = map(obj => { const statements = map(toJson, Object.entries(obj)); return `(${statements.join(' AND ')})`; }, search); return ` (${facets.join(' OR ')})`; } const statements = map(toJson, Object.entries(search)); return ` (${statements.join(' AND ')})`; }; const convertToJsonb = (column, options = {}) => search => { if (options.caseInsensitive) { return ` (lower("${column}"::text)::jsonb) @> (lower('${JSON.stringify(search)}')::jsonb)`; } return ` "${column}" @> '${JSON.stringify(search)}'`; }; const getQueryTextJsonb = ({key, not, columnNames, caseInsensitive}) => { const toJsonb = convertToJsonb(columnNames.val, {caseInsensitive}); const search = key || not; if (isArray(search)) { const facets = map(toJsonb, search); return ` (${facets.join(' OR ')})`; } return toJsonb(search); }; const getOrderByText = function ({columnNames, field, direction}) { let text = ''; if (columnNames[field]) { text += `"${columnNames[field]}"`; } else { text += `"${columnNames.val}" ->> '${field}'`; } if (direction) { text += ` ${direction.toUpperCase()}`; } return text; }; const mget = async function (params, globals) { const {store, table, options} = params; let {key, not} = params; let {client} = params; let clientCreated = false; const settings = defaultsDeep(defaults, options); const {operators, limit, offset, orderBy, direction, caseInsensitive} = settings; const {columnNames} = store.settings; try { if (!client) { client = await createClient(options, globals); clientCreated = true; } if (isObject(key) && isEmptyObject(key)) { key = undefined; } if (isObject(not) && isEmptyObject(not)) { not = undefined; } if (isUndefined(key) && isUndefined(not)) { throw new Error('incomplete query, key or not params are required'); } let text = `SELECT * FROM "${table}" WHERE`; if (!isUndefined(key)) { if (isString(key) || isNumber(key)) { text += ` "${columnNames.key}" LIKE '${key}'`; } else if (operators === 'json') { text += getQueryTextJson({ key, columnNames, caseInsensitive }); } else { text += getQueryTextJsonb({ key, columnNames, caseInsensitive }); } } if (!isUndefined(not)) { if (!isUndefined(key)) { text += ` AND`; } if (isString(not) || isNumber(not)) { text += ` "${columnNames.key}" NOT LIKE '${not}'`; } else if (operators === 'json') { text += ` NOT`; text += getQueryTextJson({not, columnNames, caseInsensitive}); } else { text += ` NOT`; text += getQueryTextJsonb({not, columnNames, caseInsensitive}); } } if (orderBy) { text += ` ORDER BY `; if (isString(orderBy)) { text += getOrderByText({field: orderBy, direction, columnNames}); } else { text += orderBy .map(o => { if (isArray(o)) { return getOrderByText({field: o[0], direction: o[1], columnNames}); } return getOrderByText({...o, columnNames}); }) .join(', '); } } if (offset > 0) { text += ` OFFSET ${offset}`; } if (limit > 0) { text += ` LIMIT ${limit}`; } text += `;`; const results = await client.query({text}); const rows = results.rows.map(r => ({ table, key: r.key, val: r.val, createdAt: r[columnNames.createdAt], updatedAt: r[columnNames.updatedAt] })); return { client, results, rows }; } catch (error) { throw error; } finally { if (clientCreated) { client.close(); } } }; export default mget;
{ "content_hash": "4c789ec051cd827a432d8dab9c98e916", "timestamp": "", "source": "github", "line_count": 214, "max_line_length": 95, "avg_line_length": 23.97196261682243, "alnum_prop": 0.5693957115009747, "repo_name": "mshick/libpiggy", "id": "111b607836123f3574f847fd1eaff1329db1b62b", "size": "5130", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/mget.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "35317" } ], "symlink_target": "" }
package org.apache.camel.component.platform.http.vertx; import java.util.ArrayList; import java.util.Collections; import java.util.List; import io.vertx.core.Handler; import io.vertx.ext.web.RoutingContext; import org.apache.camel.CamelContext; import org.apache.camel.CamelContextAware; import org.apache.camel.Consumer; import org.apache.camel.Experimental; import org.apache.camel.Processor; import org.apache.camel.component.platform.http.PlatformHttpConstants; import org.apache.camel.component.platform.http.PlatformHttpEndpoint; import org.apache.camel.component.platform.http.spi.PlatformHttpEngine; import org.apache.camel.component.platform.http.spi.UploadAttacher; import org.apache.camel.spi.annotations.JdkService; import org.apache.camel.support.service.ServiceSupport; import org.apache.camel.util.ObjectHelper; /** * Implementation of the {@link PlatformHttpEngine} based on Vert.x Web. */ @Experimental @JdkService(PlatformHttpConstants.PLATFORM_HTTP_ENGINE_FACTORY) public class VertxPlatformHttpEngine extends ServiceSupport implements PlatformHttpEngine, CamelContextAware { private CamelContext camelContext; private VertxPlatformHttp router; private List<Handler<RoutingContext>> handlers; private UploadAttacher uploadAttacher; public VertxPlatformHttpEngine() { this.handlers = Collections.emptyList(); } public VertxPlatformHttp getRouter() { return router; } public void setRouter(VertxPlatformHttp router) { this.router = router; } public List<Handler<RoutingContext>> getHandlers() { return Collections.unmodifiableList(handlers); } public void setHandlers(List<Handler<RoutingContext>> handlers) { if (handlers == null) { this.handlers = new ArrayList<>(handlers); } } public UploadAttacher getUploadAttacher() { return uploadAttacher; } public void setUploadAttacher(UploadAttacher uploadAttacher) { this.uploadAttacher = uploadAttacher; } @Override public CamelContext getCamelContext() { return camelContext; } @Override public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } @Override protected void doStart() throws Exception { if (router == null) { ObjectHelper.notNull(getCamelContext(), "Camel Context"); router = VertxPlatformHttp.lookup(getCamelContext()); } } @Override protected void doStop() throws Exception { // no-op } @Override public Consumer createConsumer(PlatformHttpEndpoint endpoint, Processor processor) { List<Handler<RoutingContext>> handlers = new ArrayList<>(this.handlers.size() + router.handlers().size()); handlers.addAll(this.router.handlers()); handlers.addAll(this.handlers); return new VertxPlatformHttpConsumer( endpoint, processor, router.router(), handlers, uploadAttacher); } }
{ "content_hash": "3a55c722709644e01717496fe53fcdd2", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 114, "avg_line_length": 30.08823529411765, "alnum_prop": 0.7129358097100033, "repo_name": "ullgren/camel", "id": "d0769d6096cf83a4a784007a8d027f2821de2f49", "size": "3871", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "components/camel-platform-http-vertx/src/main/java/org/apache/camel/component/platform/http/vertx/VertxPlatformHttpEngine.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Apex", "bytes": "6519" }, { "name": "Batchfile", "bytes": "1518" }, { "name": "CSS", "bytes": "16394" }, { "name": "Elm", "bytes": "10852" }, { "name": "FreeMarker", "bytes": "11410" }, { "name": "Groovy", "bytes": "14490" }, { "name": "HTML", "bytes": "896075" }, { "name": "Java", "bytes": "69929414" }, { "name": "JavaScript", "bytes": "90399" }, { "name": "Makefile", "bytes": "513" }, { "name": "Shell", "bytes": "17108" }, { "name": "Tcl", "bytes": "4974" }, { "name": "Thrift", "bytes": "6979" }, { "name": "XQuery", "bytes": "546" }, { "name": "XSLT", "bytes": "270186" } ], "symlink_target": "" }
using System; using TweetLib.Browser.CEF.Interfaces; using Xilium.CefGlue; namespace TweetImpl.CefGlue.Adapters { sealed class CefErrorCodeAdapter : IErrorCodeAdapter<CefErrorCode> { public static CefErrorCodeAdapter Instance { get; } = new (); private CefErrorCodeAdapter() {} public bool IsAborted(CefErrorCode errorCode) { return errorCode == CefErrorCode.Aborted; } public string GetName(CefErrorCode errorCode) { return Enum.GetName(typeof(CefErrorCode), errorCode) ?? string.Empty; } } }
{ "content_hash": "941fa0c3d533fbb5b94e3f17a736c2ca", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 72, "avg_line_length": 27.263157894736842, "alnum_prop": 0.7606177606177607, "repo_name": "chylex/TweetDuck", "id": "7f856ce0771fcc9bd6b9f4c07604cc784c094f97", "size": "518", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "linux/TweetImpl.CefGlue/Adapters/CefErrorCodeAdapter.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "122" }, { "name": "C#", "bytes": "568526" }, { "name": "CSS", "bytes": "101678" }, { "name": "F#", "bytes": "43385" }, { "name": "HTML", "bytes": "46603" }, { "name": "Inno Setup", "bytes": "17552" }, { "name": "JavaScript", "bytes": "198552" }, { "name": "PowerShell", "bytes": "1856" }, { "name": "Shell", "bytes": "795" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_95) on Sat Apr 09 08:38:34 CEST 2016 --> <title>PreSetDef.PreSetDefinition (Apache Ant API)</title> <meta name="date" content="2016-04-09"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="PreSetDef.PreSetDefinition (Apache Ant API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/apache/tools/ant/taskdefs/PreSetDef.html" title="class in org.apache.tools.ant.taskdefs"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../org/apache/tools/ant/taskdefs/ProjectHelperTask.html" title="class in org.apache.tools.ant.taskdefs"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/tools/ant/taskdefs/PreSetDef.PreSetDefinition.html" target="_top">Frames</a></li> <li><a href="PreSetDef.PreSetDefinition.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.apache.tools.ant.taskdefs</div> <h2 title="Class PreSetDef.PreSetDefinition" class="title">Class PreSetDef.PreSetDefinition</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html" title="class in org.apache.tools.ant">org.apache.tools.ant.AntTypeDefinition</a></li> <li> <ul class="inheritance"> <li>org.apache.tools.ant.taskdefs.PreSetDef.PreSetDefinition</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>Enclosing class:</dt> <dd><a href="../../../../../org/apache/tools/ant/taskdefs/PreSetDef.html" title="class in org.apache.tools.ant.taskdefs">PreSetDef</a></dd> </dl> <hr> <br> <pre>public static class <span class="strong">PreSetDef.PreSetDefinition</span> extends <a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html" title="class in org.apache.tools.ant">AntTypeDefinition</a></pre> <div class="block">This class contains the unknown element and the object that is predefined.</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html" title="class in org.apache.tools.ant"><code>AntTypeDefinition</code></a></dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../../org/apache/tools/ant/taskdefs/PreSetDef.PreSetDefinition.html#PreSetDef.PreSetDefinition(org.apache.tools.ant.AntTypeDefinition,%20org.apache.tools.ant.UnknownElement)">PreSetDef.PreSetDefinition</a></strong>(<a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html" title="class in org.apache.tools.ant">AntTypeDefinition</a>&nbsp;parent, <a href="../../../../../org/apache/tools/ant/UnknownElement.html" title="class in org.apache.tools.ant">UnknownElement</a>&nbsp;el)</code> <div class="block">Creates a new <code>PresetDefinition</code> instance.</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/taskdefs/PreSetDef.PreSetDefinition.html#checkClass(org.apache.tools.ant.Project)">checkClass</a></strong>(<a href="../../../../../org/apache/tools/ant/Project.html" title="class in org.apache.tools.ant">Project</a>&nbsp;project)</code> <div class="block">Check if the attributes are correct.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.Object</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/taskdefs/PreSetDef.PreSetDefinition.html#create(org.apache.tools.ant.Project)">create</a></strong>(<a href="../../../../../org/apache/tools/ant/Project.html" title="class in org.apache.tools.ant">Project</a>&nbsp;project)</code> <div class="block">Fake create an object, used by IntrospectionHelper and UnknownElement to see that this is a predefined object.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.Object</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/taskdefs/PreSetDef.PreSetDefinition.html#createObject(org.apache.tools.ant.Project)">createObject</a></strong>(<a href="../../../../../org/apache/tools/ant/Project.html" title="class in org.apache.tools.ant">Project</a>&nbsp;project)</code> <div class="block">Create an instance of the definition.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.ClassLoader</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/taskdefs/PreSetDef.PreSetDefinition.html#getClassLoader()">getClassLoader</a></strong>()</code> <div class="block">Get the classloader for this definition.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/taskdefs/PreSetDef.PreSetDefinition.html#getClassName()">getClassName</a></strong>()</code> <div class="block">Get the classname of the definition.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.Class</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/taskdefs/PreSetDef.PreSetDefinition.html#getExposedClass(org.apache.tools.ant.Project)">getExposedClass</a></strong>(<a href="../../../../../org/apache/tools/ant/Project.html" title="class in org.apache.tools.ant">Project</a>&nbsp;project)</code> <div class="block">Get the exposed class for this definition.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../org/apache/tools/ant/UnknownElement.html" title="class in org.apache.tools.ant">UnknownElement</a></code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/taskdefs/PreSetDef.PreSetDefinition.html#getPreSets()">getPreSets</a></strong>()</code> <div class="block">Get the preset values.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.Class</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/taskdefs/PreSetDef.PreSetDefinition.html#getTypeClass(org.apache.tools.ant.Project)">getTypeClass</a></strong>(<a href="../../../../../org/apache/tools/ant/Project.html" title="class in org.apache.tools.ant">Project</a>&nbsp;project)</code> <div class="block">Get the definition class.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/taskdefs/PreSetDef.PreSetDefinition.html#sameDefinition(org.apache.tools.ant.AntTypeDefinition,%20org.apache.tools.ant.Project)">sameDefinition</a></strong>(<a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html" title="class in org.apache.tools.ant">AntTypeDefinition</a>&nbsp;other, <a href="../../../../../org/apache/tools/ant/Project.html" title="class in org.apache.tools.ant">Project</a>&nbsp;project)</code> <div class="block">Equality method for this definition.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/taskdefs/PreSetDef.PreSetDefinition.html#setAdapterClass(java.lang.Class)">setAdapterClass</a></strong>(java.lang.Class&nbsp;adapterClass)</code> <div class="block">Set the adapter class for this definition.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/taskdefs/PreSetDef.PreSetDefinition.html#setAdaptToClass(java.lang.Class)">setAdaptToClass</a></strong>(java.lang.Class&nbsp;adaptToClass)</code> <div class="block">Set the assignable class for this definition.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/taskdefs/PreSetDef.PreSetDefinition.html#setClass(java.lang.Class)">setClass</a></strong>(java.lang.Class&nbsp;clazz)</code> <div class="block">Override so that it is not allowed.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/taskdefs/PreSetDef.PreSetDefinition.html#setClassLoader(java.lang.ClassLoader)">setClassLoader</a></strong>(java.lang.ClassLoader&nbsp;classLoader)</code> <div class="block">Set the classloader to use to create an instance of the definition.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/taskdefs/PreSetDef.PreSetDefinition.html#setClassName(java.lang.String)">setClassName</a></strong>(java.lang.String&nbsp;className)</code> <div class="block">Override so that it is not allowed.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/taskdefs/PreSetDef.PreSetDefinition.html#similarDefinition(org.apache.tools.ant.AntTypeDefinition,%20org.apache.tools.ant.Project)">similarDefinition</a></strong>(<a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html" title="class in org.apache.tools.ant">AntTypeDefinition</a>&nbsp;other, <a href="../../../../../org/apache/tools/ant/Project.html" title="class in org.apache.tools.ant">Project</a>&nbsp;project)</code> <div class="block">Similar method for this definition.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_org.apache.tools.ant.AntTypeDefinition"> <!-- --> </a> <h3>Methods inherited from class&nbsp;org.apache.tools.ant.<a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html" title="class in org.apache.tools.ant">AntTypeDefinition</a></h3> <code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html#getName()">getName</a>, <a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html#innerCreateAndSet(java.lang.Class,%20org.apache.tools.ant.Project)">innerCreateAndSet</a>, <a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html#innerGetTypeClass()">innerGetTypeClass</a>, <a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html#isRestrict()">isRestrict</a>, <a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html#setName(java.lang.String)">setName</a>, <a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html#setRestrict(boolean)">setRestrict</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="PreSetDef.PreSetDefinition(org.apache.tools.ant.AntTypeDefinition, org.apache.tools.ant.UnknownElement)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>PreSetDef.PreSetDefinition</h4> <pre>public&nbsp;PreSetDef.PreSetDefinition(<a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html" title="class in org.apache.tools.ant">AntTypeDefinition</a>&nbsp;parent, <a href="../../../../../org/apache/tools/ant/UnknownElement.html" title="class in org.apache.tools.ant">UnknownElement</a>&nbsp;el)</pre> <div class="block">Creates a new <code>PresetDefinition</code> instance.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>parent</code> - The parent of this predefinition.</dd><dd><code>el</code> - The predefined attributes, nested elements and text.</dd></dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="setClass(java.lang.Class)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setClass</h4> <pre>public&nbsp;void&nbsp;setClass(java.lang.Class&nbsp;clazz)</pre> <div class="block">Override so that it is not allowed.</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html#setClass(java.lang.Class)">setClass</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html" title="class in org.apache.tools.ant">AntTypeDefinition</a></code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>clazz</code> - a <code>Class</code> value.</dd></dl> </li> </ul> <a name="setClassName(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setClassName</h4> <pre>public&nbsp;void&nbsp;setClassName(java.lang.String&nbsp;className)</pre> <div class="block">Override so that it is not allowed.</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html#setClassName(java.lang.String)">setClassName</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html" title="class in org.apache.tools.ant">AntTypeDefinition</a></code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>className</code> - a <code>String</code> value.</dd></dl> </li> </ul> <a name="getClassName()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getClassName</h4> <pre>public&nbsp;java.lang.String&nbsp;getClassName()</pre> <div class="block">Get the classname of the definition.</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html#getClassName()">getClassName</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html" title="class in org.apache.tools.ant">AntTypeDefinition</a></code></dd> <dt><span class="strong">Returns:</span></dt><dd>the name of the class of this definition.</dd></dl> </li> </ul> <a name="setAdapterClass(java.lang.Class)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setAdapterClass</h4> <pre>public&nbsp;void&nbsp;setAdapterClass(java.lang.Class&nbsp;adapterClass)</pre> <div class="block">Set the adapter class for this definition. NOT Supported</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html#setAdapterClass(java.lang.Class)">setAdapterClass</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html" title="class in org.apache.tools.ant">AntTypeDefinition</a></code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>adapterClass</code> - the adapterClass.</dd></dl> </li> </ul> <a name="setAdaptToClass(java.lang.Class)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setAdaptToClass</h4> <pre>public&nbsp;void&nbsp;setAdaptToClass(java.lang.Class&nbsp;adaptToClass)</pre> <div class="block">Set the assignable class for this definition. NOT SUPPORTED</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html#setAdaptToClass(java.lang.Class)">setAdaptToClass</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html" title="class in org.apache.tools.ant">AntTypeDefinition</a></code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>adaptToClass</code> - the assignable class.</dd></dl> </li> </ul> <a name="setClassLoader(java.lang.ClassLoader)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setClassLoader</h4> <pre>public&nbsp;void&nbsp;setClassLoader(java.lang.ClassLoader&nbsp;classLoader)</pre> <div class="block">Set the classloader to use to create an instance of the definition. NOT SUPPORTED</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html#setClassLoader(java.lang.ClassLoader)">setClassLoader</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html" title="class in org.apache.tools.ant">AntTypeDefinition</a></code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>classLoader</code> - the classLoader.</dd></dl> </li> </ul> <a name="getClassLoader()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getClassLoader</h4> <pre>public&nbsp;java.lang.ClassLoader&nbsp;getClassLoader()</pre> <div class="block">Get the classloader for this definition.</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html#getClassLoader()">getClassLoader</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html" title="class in org.apache.tools.ant">AntTypeDefinition</a></code></dd> <dt><span class="strong">Returns:</span></dt><dd>the classloader for this definition.</dd></dl> </li> </ul> <a name="getExposedClass(org.apache.tools.ant.Project)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getExposedClass</h4> <pre>public&nbsp;java.lang.Class&nbsp;getExposedClass(<a href="../../../../../org/apache/tools/ant/Project.html" title="class in org.apache.tools.ant">Project</a>&nbsp;project)</pre> <div class="block">Get the exposed class for this definition.</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html#getExposedClass(org.apache.tools.ant.Project)">getExposedClass</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html" title="class in org.apache.tools.ant">AntTypeDefinition</a></code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>project</code> - the current project.</dd> <dt><span class="strong">Returns:</span></dt><dd>the exposed class.</dd></dl> </li> </ul> <a name="getTypeClass(org.apache.tools.ant.Project)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getTypeClass</h4> <pre>public&nbsp;java.lang.Class&nbsp;getTypeClass(<a href="../../../../../org/apache/tools/ant/Project.html" title="class in org.apache.tools.ant">Project</a>&nbsp;project)</pre> <div class="block">Get the definition class.</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html#getTypeClass(org.apache.tools.ant.Project)">getTypeClass</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html" title="class in org.apache.tools.ant">AntTypeDefinition</a></code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>project</code> - the current project.</dd> <dt><span class="strong">Returns:</span></dt><dd>the type of the definition.</dd></dl> </li> </ul> <a name="checkClass(org.apache.tools.ant.Project)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>checkClass</h4> <pre>public&nbsp;void&nbsp;checkClass(<a href="../../../../../org/apache/tools/ant/Project.html" title="class in org.apache.tools.ant">Project</a>&nbsp;project)</pre> <div class="block">Check if the attributes are correct.</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html#checkClass(org.apache.tools.ant.Project)">checkClass</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html" title="class in org.apache.tools.ant">AntTypeDefinition</a></code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>project</code> - the current project.</dd></dl> </li> </ul> <a name="createObject(org.apache.tools.ant.Project)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>createObject</h4> <pre>public&nbsp;java.lang.Object&nbsp;createObject(<a href="../../../../../org/apache/tools/ant/Project.html" title="class in org.apache.tools.ant">Project</a>&nbsp;project)</pre> <div class="block">Create an instance of the definition. The instance may be wrapped in a proxy class. This is a special version of create for IntrospectionHelper and UnknownElement.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>project</code> - the current project.</dd> <dt><span class="strong">Returns:</span></dt><dd>the created object.</dd></dl> </li> </ul> <a name="getPreSets()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getPreSets</h4> <pre>public&nbsp;<a href="../../../../../org/apache/tools/ant/UnknownElement.html" title="class in org.apache.tools.ant">UnknownElement</a>&nbsp;getPreSets()</pre> <div class="block">Get the preset values.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>the predefined attributes, elements and text as an UnknownElement.</dd></dl> </li> </ul> <a name="create(org.apache.tools.ant.Project)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>create</h4> <pre>public&nbsp;java.lang.Object&nbsp;create(<a href="../../../../../org/apache/tools/ant/Project.html" title="class in org.apache.tools.ant">Project</a>&nbsp;project)</pre> <div class="block">Fake create an object, used by IntrospectionHelper and UnknownElement to see that this is a predefined object.</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html#create(org.apache.tools.ant.Project)">create</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html" title="class in org.apache.tools.ant">AntTypeDefinition</a></code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>project</code> - the current project.</dd> <dt><span class="strong">Returns:</span></dt><dd>this object.</dd></dl> </li> </ul> <a name="sameDefinition(org.apache.tools.ant.AntTypeDefinition, org.apache.tools.ant.Project)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>sameDefinition</h4> <pre>public&nbsp;boolean&nbsp;sameDefinition(<a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html" title="class in org.apache.tools.ant">AntTypeDefinition</a>&nbsp;other, <a href="../../../../../org/apache/tools/ant/Project.html" title="class in org.apache.tools.ant">Project</a>&nbsp;project)</pre> <div class="block">Equality method for this definition.</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html#sameDefinition(org.apache.tools.ant.AntTypeDefinition,%20org.apache.tools.ant.Project)">sameDefinition</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html" title="class in org.apache.tools.ant">AntTypeDefinition</a></code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>other</code> - another definition.</dd><dd><code>project</code> - the current project.</dd> <dt><span class="strong">Returns:</span></dt><dd>true if the definitions are the same.</dd></dl> </li> </ul> <a name="similarDefinition(org.apache.tools.ant.AntTypeDefinition, org.apache.tools.ant.Project)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>similarDefinition</h4> <pre>public&nbsp;boolean&nbsp;similarDefinition(<a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html" title="class in org.apache.tools.ant">AntTypeDefinition</a>&nbsp;other, <a href="../../../../../org/apache/tools/ant/Project.html" title="class in org.apache.tools.ant">Project</a>&nbsp;project)</pre> <div class="block">Similar method for this definition.</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html#similarDefinition(org.apache.tools.ant.AntTypeDefinition,%20org.apache.tools.ant.Project)">similarDefinition</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../org/apache/tools/ant/AntTypeDefinition.html" title="class in org.apache.tools.ant">AntTypeDefinition</a></code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>other</code> - another definition.</dd><dd><code>project</code> - the current project.</dd> <dt><span class="strong">Returns:</span></dt><dd>true if the definitions are similar.</dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/apache/tools/ant/taskdefs/PreSetDef.html" title="class in org.apache.tools.ant.taskdefs"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../org/apache/tools/ant/taskdefs/ProjectHelperTask.html" title="class in org.apache.tools.ant.taskdefs"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/tools/ant/taskdefs/PreSetDef.PreSetDefinition.html" target="_top">Frames</a></li> <li><a href="PreSetDef.PreSetDefinition.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "4430a7644adfa36e4a85ddfeffd7d1df", "timestamp": "", "source": "github", "line_count": 580, "max_line_length": 692, "avg_line_length": 52, "alnum_prop": 0.6735742705570292, "repo_name": "jstrassburg/solr-jenkins-cicd", "id": "8cc1397475aa3b8d4d001c29b68e343bf2b8882e", "size": "30160", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "jenkins_home/tools/hudson.tasks.Ant_AntInstallation/ant/manual/api/org/apache/tools/ant/taskdefs/PreSetDef.PreSetDefinition.html", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "22523" }, { "name": "CSS", "bytes": "356702" }, { "name": "Groovy", "bytes": "7311" }, { "name": "HTML", "bytes": "33253889" }, { "name": "JavaScript", "bytes": "23893409" }, { "name": "Perl", "bytes": "9922" }, { "name": "Python", "bytes": "3385" }, { "name": "Shell", "bytes": "13297" }, { "name": "XSLT", "bytes": "238702" } ], "symlink_target": "" }
package com.cloudera.oryx.app.traffic; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Invocation; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; import java.net.URI; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Pattern; import com.google.common.base.Preconditions; import org.apache.commons.math3.distribution.ExponentialDistribution; import org.apache.commons.math3.random.RandomGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.cloudera.oryx.app.traffic.als.ALSEndpoint; import com.cloudera.oryx.common.lang.LoggingRunnable; import com.cloudera.oryx.common.random.RandomManager; /** * Simple utility class for sending traffic to an Oryx cluster for an extended period of time. * At the moment, it is oriented towards sending traffic to the built-in ALS-based recommender * application. * * <ol> * <li>{@code inputFile} local file containing input to base requests on, one per line.</li> * <li>{@code hosts} comma-separated distinct host:port pairs to send HTTP requests to</li> * <li>{@code requestIntervalMS} average delay between requests in MS</li> * </ol> */ public final class TrafficUtil { private static final Logger log = LoggerFactory.getLogger(TrafficUtil.class); private static final Pattern COMMA = Pattern.compile(","); private TrafficUtil() { } public static void main(String[] args) throws Exception { if (args.length < 3) { System.err.println("usage: TrafficUtil [inputFile] [hosts] [requestIntervalMS]"); return; } Path inputFile = Paths.get(args[0]); Preconditions.checkArgument(Files.exists(inputFile)); String[] hostStrings = COMMA.split(args[1]); Preconditions.checkArgument(hostStrings.length >= 1); int requestIntervalMS = Integer.parseInt(args[2]); Preconditions.checkArgument(requestIntervalMS >= 0); final List<URI> hosts = new ArrayList<>(hostStrings.length); for (String hostString : hostStrings) { hosts.add(URI.create(hostString)); } final List<String> inputLines = Files.readAllLines(inputFile, StandardCharsets.UTF_8); int numThreads = Runtime.getRuntime().availableProcessors(); final int perClientRequestIntervalMS = numThreads * requestIntervalMS; final Endpoints alsEndpoints = new Endpoints(ALSEndpoint.buildALSEndpoints()); final AtomicLong requestCount = new AtomicLong(); final AtomicLong errorCount = new AtomicLong(); ExecutorService executor = Executors.newFixedThreadPool(numThreads); try { for (int i = 0; i < numThreads; i++) { executor.submit(new LoggingRunnable() { @Override public void doRun() throws InterruptedException { RandomGenerator random = RandomManager.getRandom(); ExponentialDistribution msBetweenRequests; if (perClientRequestIntervalMS > 0) { msBetweenRequests = new ExponentialDistribution(random, perClientRequestIntervalMS); } else { msBetweenRequests = null; } Client client = ClientBuilder.newClient(); while (true) { WebTarget target = client.target("http://" + hosts.get(random.nextInt(hosts.size()))); String input = inputLines.get(random.nextInt(inputLines.size())); Endpoint endpoint = alsEndpoints.chooseEndpoint(random); Invocation invocation = endpoint.makeInvocation(target, input); long startTime = System.currentTimeMillis(); Response response = invocation.invoke(); long elapsedMS = System.currentTimeMillis() - startTime; int statusCode = response.getStatusInfo().getStatusCode(); if (statusCode != Response.Status.OK.getStatusCode() && statusCode != Response.Status.NO_CONTENT.getStatusCode()) { //log.warn("Bad response for {}: {}", invocation, response); errorCount.incrementAndGet(); } endpoint.recordTiming(elapsedMS); if (requestCount.incrementAndGet() % 10000 == 0) { log.info("{} requests ({} errors)", requestCount.get(), errorCount.get()); for (Endpoint e : alsEndpoints.getEndpoints()) { log.info("{}", e); } } if (msBetweenRequests != null) { int desiredElapsedMS = (int) Math.round(msBetweenRequests.sample()); if (elapsedMS < desiredElapsedMS) { Thread.sleep(desiredElapsedMS - elapsedMS); } } } } }); } } finally { executor.shutdown(); } } }
{ "content_hash": "ea2e8377aedd2d5e5ef78ed5ceabe463", "timestamp": "", "source": "github", "line_count": 135, "max_line_length": 100, "avg_line_length": 37.525925925925925, "alnum_prop": 0.6650217133833399, "repo_name": "bikash/oryx-1", "id": "8b0c6ecafc9c4b89519c492d0ed003ffdd2fd65b", "size": "5634", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/oryx-app-serving/src/test/java/com/cloudera/oryx/app/traffic/TrafficUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1055680" }, { "name": "Scala", "bytes": "7650" }, { "name": "Shell", "bytes": "10898" } ], "symlink_target": "" }
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class Listcv extends MY_Controller { var $_myData; public function __construct() { parent::__construct(); $this->load->library('form_validation'); $this->load->model('resumes_online_model'); $this->load->helper('url'); } public function index() { $page = $this->uri->segment(3); if ($page == null) { $pageUrl = 1; } else { $pageUrl = ceil($page / 10) + 1; } $listResume = $this->resumes_online_model->getAllOnlineResumeLimit(1, $page, $limit = 10); $this->ocular->set_view_data("listResume", $listResume); $totalAllResume = $this->resumes_online_model->getAllOnlineResumeLimit(0, 0, 0); //pagination $config = array(); $url = base_url() . "listcv/kw"; $config["base_url"] = $url; $config["total_rows"] = isset($totalAllResume) ? $totalAllResume : 0; $config["per_page"] = 10; $config["uri_segment"] = 3; $config['cur_tag_open'] = '<li class="active"><a href="#">'; $config['cur_tag_close'] = '</li>'; $config['num_tag_open'] = '<li>'; $config['num_tag_close'] = '</li>'; $config['next_link'] = 'Sau'; $config['prev_link'] = 'Trước'; $config['next_tag_open'] = '<li>'; $config['next_tag_close'] = '</li>'; $config['prev_tag_open'] = '<li>'; $config['prev_tag_close'] = '</li>'; $config['first_tag_open'] = '<li style = "display:none">'; $config['first_tag_close'] = '</li>'; $config['last_tag_open'] = '<li style = "display:none">'; $config['last_tag_close'] = '</li>'; if (( $config["per_page"] * $pageUrl) > $config["total_rows"]) { $recordInPage = $config["total_rows"]; $valueShowRecord = (($pageUrl - 1) * $config["per_page"] + 1) . " - " . $recordInPage; } else { $recordInPage = $config["per_page"] * $pageUrl; $valueShowRecord = ($recordInPage - $config["per_page"] + 1) . " - " . $recordInPage; } $this->pagination->initialize($config); $this->ocular->set_view_data("valueShowRecord", $valueShowRecord); $this->ocular->set_view_data("totalAllResume", $totalAllResume); $this->ocular->render('blank'); } public function updatepoint() { $email = $this->input->post('email'); $point = $this->input->post('point'); $data = array( 'point' => $point, ); $this->resumes_online_model->updatePointResume($email, $data); echo 'true'; } }
{ "content_hash": "7f980db45b662d21a02abda27be7d0bc", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 98, "avg_line_length": 31.476744186046513, "alnum_prop": 0.51865533801256, "repo_name": "chrisshayan/japanworks", "id": "fcf6265fea11ac9eeeb8391683996501daeae556", "size": "2710", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/controllers/listcv.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "333" }, { "name": "CSS", "bytes": "642070" }, { "name": "HTML", "bytes": "3666" }, { "name": "JavaScript", "bytes": "2055565" }, { "name": "PHP", "bytes": "5094482" } ], "symlink_target": "" }
<?php namespace EloquentSearcher\Test; use Illuminate\Database\Eloquent\Model; use EloquentSearcher\SearchableTrait; class Dummy extends Model { use SearchableTrait; protected $searcher = DummySearcher::class; protected $table = 'dummies'; public $timestamps = false; protected $dates = [ 'date_range', 'datetime_range', ]; protected $fillable = [ 'text_equals', 'text_contains', 'text_startswith', 'text_endswith', 'integer_gt', 'integer_gte', 'integer_lt', 'integer_lte', 'integer_range', 'integer_in', 'integer_is_null', 'integer_is_not_null', 'boolean_is_true', 'boolean_is_not_true', 'boolean_is_false', 'boolean_is_not_false', 'date_range', 'datetime_range', 'text_custom_function', ]; protected $guarded = []; public function parent() { return $this->belongsTo(static::class, 'parent_id'); } }
{ "content_hash": "390fdb8269aa401fe34d85cb48372fc3", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 60, "avg_line_length": 21.081632653061224, "alnum_prop": 0.5614714424007744, "repo_name": "odoku/EloquentSearcher", "id": "dfcc7f773f2a54626558bc42df0c933eabb59162", "size": "1033", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/Dummy.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "35705" } ], "symlink_target": "" }
<?php use Goteo\Core\View, Goteo\Library\Text; $level = (int) $this['level'] ?: 3; $project = $this['project']; ?> <div class="widget project-support collapsable" id="project-support"> <h<?php echo $level + 1 ?> class="supertitle"><?php echo Text::get('project-support-supertitle'); ?></h<?php echo $level + 1 ?>> <?php switch ($project->tagmark) { case 'onrun': // "en marcha" echo '<div class="tagmark green">' . Text::get('regular-onrun_mark') . '</div>'; break; case 'keepiton': // "aun puedes" echo '<div class="tagmark green">' . Text::get('regular-keepiton_mark') . '</div>'; break; case 'onrun-keepiton': // "en marcha" y "aun puedes" echo '<div class="tagmark green twolines"><span class="small"><strong>' . Text::get('regular-onrun_mark') . '</strong><br />' . Text::get('regular-keepiton_mark') . '</span></div>'; break; case 'gotit': // "financiado" echo '<div class="tagmark violet">' . Text::get('regular-gotit_mark') . '</div>'; break; case 'success': // "exitoso" echo '<div class="tagmark red">' . Text::get('regular-success_mark') . '</div>'; break; case 'fail': // "caducado" echo '<div class="tagmark grey">' . Text::get('regular-fail_mark') . '</div>'; break; } ?> <?php echo new View('view/project/meter.html.php', array('project' => $project, 'level' => $level) ) ?> <div class="buttons"> <?php if ($project->status == 3) : // boton apoyar solo si esta en campaña ?> <a class="button violet supportit" href="/project/<?php echo $project->id; ?>/invest"><?php echo Text::get('regular-invest_it'); ?></a> <?php else : ?> <a class="button view" href="/project/<?php echo $project->id ?>/updates"><?php echo Text::get('regular-see_blog'); ?></a> <?php endif; ?> <a class="more" href="/project/<?php echo $project->id; ?>/needs"><?php echo Text::get('regular-see_more'); ?></a> </div> </div>
{ "content_hash": "d84882348af9e5bdb1ea42e31d4009a6", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 193, "avg_line_length": 43.729166666666664, "alnum_prop": 0.5454978561219629, "repo_name": "nguyendev/LoveSharing", "id": "d8029f0de2e0f82b79f648503add6d4b7ddabfdd", "size": "2883", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "goteo/view/project/widget/support.html.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "566" }, { "name": "CSS", "bytes": "325156" }, { "name": "HTML", "bytes": "2954" }, { "name": "JavaScript", "bytes": "63409" }, { "name": "PHP", "bytes": "3599595" }, { "name": "Shell", "bytes": "1359" } ], "symlink_target": "" }
var _ = require('lodash'); var jwt = require('jwt-simple'); var debug = require('debug')('4front:http-host:dev-sandbox'); require('simple-errors'); var defaultDevOptions = { port: '3000', // The localhost port buildType: 'debug', autoReload: '0' }; module.exports = function(options) { options = _.defaults(options || {}, { cookieName: '_dev', queryParam: '_dev', sandboxFlashCookie: '_sandboxPage', showBanner: true }); return function(req, res, next) { debug('executing'); // Bypass simulator if the virtualEnv is not 'local' if (req.ext.virtualEnv !== 'local') return next(); var token; var devOptions; var devCookieName = (req.app.settings.cookiePrefix || '') + options.cookieName; // Special login path used to initialize the developer sandbox. Just copy // the query parameters to the _dev cookie and redirect to the root of the app. // Subsequent requests will read from the _dev cookie. if (req.path === '/__login') { debug('writing devOptions to cookie'); // Clear the sandbox flash cookie res.clearCookie(req.app.settings.cookiePrefix + options.sandboxFlashCookie); devOptions = _.pick(req.query, _.keys(defaultDevOptions).concat('token')); token = validateDevToken(devOptions.token, req.app.settings.jwtTokenSecret); if (_.isError(token)) return next(token); res.cookie(devCookieName, devOptions, {httpOnly: true}); return res.redirect('/'); } // Load the dev options from the dev cookie var devCookie = req.cookies[devCookieName]; if (!devCookie) { return next(Error.http(401, 'No ' + devCookieName + ' cookie set.', { help: 'Try running \'4front dev\' again.', code: 'missingDevCookie', bypassCustomErrorPage: true })); } // Load the developer's personal options from the _dev cookie // Apply the default dev options to the values from the cookie devOptions = _.extend(_.defaults({}, devCookie, defaultDevOptions), { cookieName: options.sandboxFlashCookie }); token = validateDevToken(devOptions.token, req.app.settings.jwtTokenSecret); if (_.isError(token)) return next(token); // Store the 4front userId of the current developer req.ext.developerId = token.iss; req.ext.clientConfig.sandbox = true; // Get the app manifest from cache var manifestCacheKey = req.ext.developerId + '/' + req.ext.virtualApp.appId + '/_manifest'; req.app.settings.cache.get(manifestCacheKey, function(err, manifestJson) { if (err) return next(err); var manifest = null; try { manifest = JSON.parse(manifestJson); } catch (jsonErr) { manifest = null; } if (manifest === null) { return next(Error.http(400, 'Invalid JSON manifest', { bypassCustomErrorPage: true, help: 'Try re-starting the dev sandbox with the command \'4front dev\'', code: 'invalidJsonManifest' })); } _.merge(req.ext, { // Specify custom middleware to handle loading the html page stream. // This will override the default behavior of loading from the // app.settings.storage object. devOptions: devOptions, loadPageMiddleware: require('./dev-sandbox-page')(devOptions), virtualAppVersion: { versionId: 'sandbox', name: 'sandbox', manifest: manifest }, versionAssetPath: '//localhost:' + devOptions.port, buildType: devOptions.buildType, // Override the cache-control. We never want to cache pages served by the dev sandbox cacheControl: 'no-cache', htmlOptions: { autoReload: devOptions.autoReload === '1', // Run autoReload on the same port as the sandbox sandboxPort: devOptions.port, assetPath: '//localhost:' + devOptions.port, inject: {} } }); next(); }); }; // Validate the devOptions are valid function validateDevToken(encodedToken, tokenSecret) { // Validate the auth token if (_.isEmpty(encodedToken)) { return Error.http(401, 'Missing dev token.', { bypassCustomErrorPage: true, code: 'missingDevToken', help: 'Try re-starting the dev sandbox with \'4front dev\'' }); } var token; if (_.isEmpty(encodedToken) === false) { debug('decoding token %s', encodedToken); try { token = jwt.decode(encodedToken, tokenSecret); } catch (err) { return Error.http(401, 'Invalid dev token.', { bypassCustomErrorPage: true, code: 'invalidDevToken', help: 'Try re-starting the dev sandbox with \'4front dev\'' }); } } if (token.exp < Date.now()) { debug('token expired at %s', token.exp); return Error.http(401, 'Token expired', { bypassCustomErrorPage: true, code: 'expiredDevToken', help: 'Please re-start the dev sandbox with the `4front dev` command.' }); } return token; } };
{ "content_hash": "1963e0e409e0b4d6ae4589bec91e68e2", "timestamp": "", "source": "github", "line_count": 158, "max_line_length": 95, "avg_line_length": 32.28481012658228, "alnum_prop": 0.6216428151342874, "repo_name": "4front/apphost", "id": "8297a987236e780b70288e277b23e1016cc179ad", "size": "5101", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/middleware/dev-sandbox.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "193069" } ], "symlink_target": "" }
package org.apache.camel.component.mllp; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests for the class. */ public class MllpNegativeAcknowledgementExceptionTest extends MllpExceptionTestSupport { static final String EXCEPTION_MESSAGE = "Negative Acknowledgement"; MllpNegativeAcknowledgementException instance; /** * Description of test. * */ @Test public void testConstructorOne() { instance = new MllpNegativeAcknowledgementExceptionStub( EXCEPTION_MESSAGE, HL7_MESSAGE_BYTES, HL7_ACKNOWLEDGEMENT_BYTES, LOG_PHI_TRUE); assertTrue(instance.getMessage().startsWith(EXCEPTION_MESSAGE)); assertNull(instance.getCause()); assertArrayEquals(HL7_MESSAGE_BYTES, instance.getHl7MessageBytes()); assertArrayEquals(HL7_ACKNOWLEDGEMENT_BYTES, instance.getHl7AcknowledgementBytes()); } /** * Description of test. * */ @Test public void testConstructorTwo() { instance = new MllpNegativeAcknowledgementExceptionStub( EXCEPTION_MESSAGE, HL7_MESSAGE_BYTES, HL7_ACKNOWLEDGEMENT_BYTES, CAUSE, LOG_PHI_TRUE); assertTrue(instance.getMessage().startsWith(EXCEPTION_MESSAGE)); assertSame(CAUSE, instance.getCause()); assertArrayEquals(HL7_MESSAGE_BYTES, instance.getHl7MessageBytes()); assertArrayEquals(HL7_ACKNOWLEDGEMENT_BYTES, instance.getHl7AcknowledgementBytes()); } /** * Description of test. * */ @Test public void testGetAcknowledgmentType() { instance = new MllpNegativeAcknowledgementExceptionStub( EXCEPTION_MESSAGE, HL7_MESSAGE_BYTES, HL7_ACKNOWLEDGEMENT_BYTES, LOG_PHI_TRUE); assertNull(instance.getAcknowledgmentType()); } static class MllpNegativeAcknowledgementExceptionStub extends MllpNegativeAcknowledgementException { MllpNegativeAcknowledgementExceptionStub(String message, byte[] hl7Message, byte[] hl7Acknowledgement, boolean logPhi) { super(message, hl7Message, hl7Acknowledgement, logPhi); } MllpNegativeAcknowledgementExceptionStub(String message, byte[] hl7Message, byte[] hl7Acknowledgement, Throwable cause, boolean logPhi) { super(message, hl7Message, hl7Acknowledgement, cause, logPhi); } @Override public String getAcknowledgmentType() { return null; } } }
{ "content_hash": "886ddd6f59567d20546fa694d7dacb84", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 128, "avg_line_length": 34.92307692307692, "alnum_prop": 0.697136563876652, "repo_name": "christophd/camel", "id": "2edab4415bf429f23370157857d686011de00117", "size": "3526", "binary": false, "copies": "6", "ref": "refs/heads/main", "path": "components/camel-mllp/src/test/java/org/apache/camel/component/mllp/MllpNegativeAcknowledgementExceptionTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Apex", "bytes": "6695" }, { "name": "Batchfile", "bytes": "2353" }, { "name": "CSS", "bytes": "5472" }, { "name": "Dockerfile", "bytes": "5676" }, { "name": "Elm", "bytes": "10852" }, { "name": "FreeMarker", "bytes": "8015" }, { "name": "Groovy", "bytes": "405043" }, { "name": "HTML", "bytes": "212954" }, { "name": "Java", "bytes": "114730615" }, { "name": "JavaScript", "bytes": "103655" }, { "name": "Jsonnet", "bytes": "1734" }, { "name": "Kotlin", "bytes": "41869" }, { "name": "Mustache", "bytes": "525" }, { "name": "RobotFramework", "bytes": "8461" }, { "name": "Ruby", "bytes": "88" }, { "name": "Shell", "bytes": "15327" }, { "name": "Tcl", "bytes": "4974" }, { "name": "Thrift", "bytes": "6979" }, { "name": "XQuery", "bytes": "699" }, { "name": "XSLT", "bytes": "276597" } ], "symlink_target": "" }
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals # Module API def check_required(constraint, value): if not (constraint and value is None): return True return False
{ "content_hash": "0345ce3353c73e8c3e9c6652eefd893e", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 42, "avg_line_length": 23.666666666666668, "alnum_prop": 0.7183098591549296, "repo_name": "okfn/jsontableschema-py", "id": "c164388dd86443558e614f31a139047c4f9e1e67", "size": "308", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tableschema/constraints/required.py", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "453" }, { "name": "Python", "bytes": "134974" } ], "symlink_target": "" }
```bash git init ``` Transforma el directorio actual en un repositorio Git. Esto agrega una carpeta oculta `.git` en el directorio actual haciendo posible empezar a guardar las reviciones del proyecto.
{ "content_hash": "1dff9b5fe029a30fd7785ace6b658132", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 180, "avg_line_length": 40.4, "alnum_prop": 0.7920792079207921, "repo_name": "sinaptica/curso-git", "id": "15e1a402c2760783dc1e10498c2ece531560d08d", "size": "217", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "slides/comandos-0-bis.md", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "3846" }, { "name": "HTML", "bytes": "7349" }, { "name": "JavaScript", "bytes": "14011" } ], "symlink_target": "" }
import { test } from 'qunit'; import moduleForAcceptance from 'adlet/tests/helpers/module-for-acceptance'; import AWS from 'npm:aws-sdk'; import Ember from 'ember'; let s3Mock = Ember.Service.extend({ listAll(){ return { Contents: [ {Key: "Article1", Body: [77,121,32,83,101,120,121,32,66,101,97,99,104,32,66,111,100,121,33,33,33,33]}, {Key: "Article2", Body: [77,121,32,83,101,120,121,32,66,101,97,99,104,32,66,111,100,121,33,33,33,33]} ]}; } }); moduleForAcceptance('Acceptance | admin login', { beforeEach() { this.application.register('service:s3Mock', s3Mock); this.application.inject('adapter', 's3', 'service:s3Mock'); } }); test('visiting /admin/login', function(assert) { var newCredentials; AWS.config.update = function(params) { newCredentials = params; }; AWS.S3.prototype.listObjects = function(params, callback) { callback.call(undefined, undefined, {}); }; visit('/admin/login'); andThen(function() { assert.equal(currentURL(), '/admin/login'); }); fillIn(".login__access-key-id", "An Access Key ID"); fillIn(".login__secret-access-key", "A Secret Access Key"); click(".login__submit"); andThen(function() { assert.equal(currentURL(), '/admin/articles'); // This asserts that AWS.config was updated with the values entered assert.equal(newCredentials.credentials.accessKeyId, "An Access Key ID"); assert.equal(newCredentials.credentials.secretAccessKey, "A Secret Access Key"); }); });
{ "content_hash": "1ddc2a60fc241dae62cddee20acd218c", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 108, "avg_line_length": 30.612244897959183, "alnum_prop": 0.6713333333333333, "repo_name": "A-Helberg/adlet", "id": "78bc56061d9344e39b79d171ea3a59f847f054de", "size": "1500", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "tests/acceptance/admin-login-test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5009" }, { "name": "HTML", "bytes": "5574" }, { "name": "JavaScript", "bytes": "41903" } ], "symlink_target": "" }
<?php namespace Rcms\Core\Widget; use Rcms\Core\InfoFile; /** * Stores metadata about a widget definition, comes from a widget info file. */ final class WidgetMeta { private $widgetName; /** * @var InfoFile File with metadata of the widget. */ private $infoFile; public function __construct($widgetName, InfoFile $infoFile) { $this->widgetName = $widgetName; $this->infoFile = $infoFile; } public function getDisplayName() { return $this->infoFile->getString("name", $this->widgetName); } public function getDescription() { return $this->infoFile->getString("description", "No description given"); } public function getDirectoryName() { return $this->widgetName; } public function getVersion() { return $this->infoFile->getString("version", "0.0.1"); } public function getAuthor() { return $this->infoFile->getString("author", "Unknown"); } public function getAuthorWebsite() { return $this->infoFile->getString("author.website"); } public function getWidgetWebsite() { return $this->infoFile->getString("website"); } }
{ "content_hash": "4a7299141b68972fd5e1e444065639df", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 81, "avg_line_length": 23.392156862745097, "alnum_prop": 0.6311818943839062, "repo_name": "rutgerkok/rCMS", "id": "d9eecd5255835134cc743c8c8c7d0cd620d2fb8e", "size": "1193", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Core/Widget/WidgetMeta.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "41767" }, { "name": "JavaScript", "bytes": "8088" }, { "name": "PHP", "bytes": "654605" } ], "symlink_target": "" }
package com.sleepycat.je.utilint; /** * A long stat which maintains a minimum value. It is intialized to * Long.MAX_VALUE. The setMin() method assigns the counter to * MIN(counter, new value). */ public class LongMinStat extends LongStat { private static final long serialVersionUID = 1L; public LongMinStat(StatGroup group, StatDefinition definition) { super(group, definition); clear(); } public LongMinStat(StatGroup group, StatDefinition definition, long counter) { super(group, definition); this.counter = counter; } @Override public void clear() { set(Long.MAX_VALUE); } /** * Set stat to MIN(current stat value, newValue). */ public void setMin(long newValue) { counter = (counter > newValue) ? newValue : counter; } @Override public Stat<Long> computeInterval(Stat<Long> base) { return (counter > base.get() ? base.copy() : copy()); } @Override public void negate() { } @Override protected String getFormattedValue() { if (counter == Long.MAX_VALUE) { return "NONE"; } return Stat.FORMAT.format(counter); } }
{ "content_hash": "0e0957ca677cd9debd8278e6fb26db90", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 68, "avg_line_length": 23.333333333333332, "alnum_prop": 0.5944444444444444, "repo_name": "prat0318/dbms", "id": "f79bdec206c79507b93957dae76fc54bf05a6440", "size": "1409", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mini_dbms/je-5.0.103/src/com/sleepycat/je/utilint/LongMinStat.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "10102975" }, { "name": "SQL", "bytes": "1981542" }, { "name": "Scala", "bytes": "4121" }, { "name": "Shell", "bytes": "3212" } ], "symlink_target": "" }
package de.baywa.tecb2bwebgwt.server; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.tuckey.web.filters.urlrewrite.UrlRewriteFilter; /** * configuration of the url filter, it's used to redirect all pushstate urls (which don't realy * exists) to the index.html page. * * @author Manfred Tremmel */ @Configuration public class FilterRegistrationConfig { /** * register filter bean. * * @return FilterRegistrationBean */ @Bean public FilterRegistrationBean<UrlRewriteFilter> filterRegistrationBean() { final FilterRegistrationBean<UrlRewriteFilter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(new UrlRewriteFilter()); registrationBean.addUrlPatterns("*"); registrationBean.addInitParameter("confReloadCheckInterval", "5"); registrationBean.addInitParameter("logLevel", "INFO"); return registrationBean; } }
{ "content_hash": "71eb46fb1984b68eaa70538d50bb768b", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 95, "avg_line_length": 30.735294117647058, "alnum_prop": 0.769377990430622, "repo_name": "ManfredTremmel/gwtp-training", "id": "6cbb29022005673fe531321e7bb98271c31a074b", "size": "1045", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tecb2bwebgwt/src/main/java/de/baywa/tecb2bwebgwt/server/FilterRegistrationConfig.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "744" }, { "name": "Java", "bytes": "64379" } ], "symlink_target": "" }
DOCKER_VERSION="1.9.1" DOCKER_MACHINE_VERSION="0.5.5" #DOCKER_COMPOSE_VERSION="1.5.0rc1" RED='\033[0;31m' GREEN='\033[0;32m' NC='\033[0m' # No Color do_install() { os=$(uname -s) arch=$(uname -m) # Install Docker client docker_bin_url="https://test.docker.com/builds/$os/$arch/docker-$DOCKER_VERSION" echo "${GREEN}>> Download docker client binary ($DOCKER_VERSION)${NC}" echo $docker_bin_url curl --progress-bar -o /usr/local/bin/docker $docker_bin_url chmod +x /usr/local/bin/docker # Install Docker machine docker_machine_bin_url="https://github.com/docker/machine/releases/download/v$DOCKER_MACHINE_VERSION/docker-machine_$(echo $os| tr '[:upper:]' '[:lower:]')-amd64" echo "\n${GREEN}>> Download Docker machine ($DOCKER_MACHINE_VERSION)${NC}" echo $docker_machine_bin_url curl --progress-bar -L $docker_machine_bin_url > /usr/local/bin/docker-machine chmod +x /usr/local/bin/docker-machine # Install Docker Compose docker_compose_bin_url="https://dl.bintray.com/docker-compose/master/docker-compose-$os-$arch" echo "\n${GREEN}>> Download Docker compose (Master)${NC}" echo $docker_compose_bin_url curl --progress-bar -L $docker_compose_bin_url > /usr/local/bin/docker-compose chmod +x /usr/local/bin/docker-compose } do_create_machine() { # Create a Docker machine on virtualbox echo "\n${GREEN}>> Create a dev machine on virtualbox${NC}" docker-machine create --driver virtualbox dev } do_configure_nfs() { ip=$(docker-machine ip dev) vboxnet_name=$(VBoxManage showvminfo dev --machinereadable | grep hostonlyadapter | cut -d= -f2 | sed -e 's/"//g') vboxnet_ip=$(VBoxManage list hostonlyifs|grep -A3 "Name: *$vboxnet_name" | tail -n1|cut -d: -f2|tr -d '[[:space:]]') grep -q DOCKER-LOCAL-BEGIN /etc/exports if [ $? -eq 1 ]; then echo "\n${GREEN}>> Config NFS server on your local machine (need root access)${NC}" nfsexports=$(cat <<EOF # DOCKER-LOCAL-BEGIN /Users {{IP}} -alldirs -mapall=0:80 # DOCKER-LOCAL-END EOF) nfsexports=$(echo "$nfsexports" | sed -e "s/{{IP}}/$ip/g") echo "$nfsexports" | sudo tee -a /etc/exports sudo nfsd restart fi echo "\n${GREEN}>> Config NFS client on the dev machine${NC}" bootsync=$(cat <<EOF #!/bin/sh sudo umount /Users sudo /usr/local/etc/init.d/nfs-client start sleep 1 sudo mount.nfs {{IP}}:/Users /Users -v -o rw,async,noatime,rsize=32768,wsize=32768,proto=udp,udp,nfsvers=3 EOF) bootsync=$(echo "$bootsync" | sed -e "s/{{IP}}/$vboxnet_ip/g") docker-machine ssh dev "echo \"$bootsync\" > /tmp/bootsync.sh" docker-machine ssh dev "sudo mv /tmp/bootsync.sh /var/lib/boot2docker/bootsync.sh" docker-machine restart dev } read -p "Do you want to install docker, docker-machine and docker-compose? (y/n)" answer case ${answer:0:1} in y|Y ) do_install ;; * ) break ;; esac read -p "Do you want to create a new machine? (y/n)" answer case ${answer:0:1} in y|Y ) do_create_machine do_configure_nfs echo "\n\n${GREEN}Done! To see how to connect Docker to this machine, run: docker-machine env dev${NC}" ;; * ) exit ;; esac
{ "content_hash": "001f6e28f63340f8e94f2a6f7fc1d459", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 164, "avg_line_length": 29.714285714285715, "alnum_prop": 0.6717948717948717, "repo_name": "pointcom/docker-local-dev", "id": "10213745c52ae68b8505836ededb27b376cd1ef9", "size": "3315", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "install.sh", "mode": "33261", "license": "mit", "language": [ { "name": "Shell", "bytes": "3315" } ], "symlink_target": "" }
package com.dytech.edge.admin.wizard.walkers; import com.dytech.edge.admin.wizard.model.Control; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** @author Nicholas Read */ public class IterateControls extends ControlTreeWalker { private final List<Control> controls = new ArrayList<Control>(); /** Constructs a new IterateControls. */ public IterateControls() { super(); } /** @return Returns the targets. */ public Iterator<Control> iterate() { return controls.iterator(); } public List<Control> getControls() { return controls; } @Override protected boolean onDescent(Control control) { controls.add(control); return true; } }
{ "content_hash": "1cb56c4f0409841cda9b25295d42bd66", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 66, "avg_line_length": 21.606060606060606, "alnum_prop": 0.7096774193548387, "repo_name": "equella/Equella", "id": "81539cb396fda414fb9f3301890a04b5ed76ed18", "size": "1516", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "Source/Plugins/Core/com.equella.admin/src/com/dytech/edge/admin/wizard/walkers/IterateControls.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "402" }, { "name": "Batchfile", "bytes": "38432" }, { "name": "CSS", "bytes": "648823" }, { "name": "Dockerfile", "bytes": "2055" }, { "name": "FreeMarker", "bytes": "370046" }, { "name": "HTML", "bytes": "865667" }, { "name": "Java", "bytes": "27081020" }, { "name": "JavaScript", "bytes": "1673995" }, { "name": "PHP", "bytes": "821" }, { "name": "PLpgSQL", "bytes": "1363" }, { "name": "PureScript", "bytes": "307610" }, { "name": "Python", "bytes": "79871" }, { "name": "Scala", "bytes": "765981" }, { "name": "Shell", "bytes": "64170" }, { "name": "TypeScript", "bytes": "146564" }, { "name": "XSLT", "bytes": "510113" } ], "symlink_target": "" }
#region Copyright #endregion #region using Autodesk.DesignScript.Runtime; using Dynamo.Models; using System.Collections.Generic; using Dynamo.Nodes; using Dynamo.Graph.Nodes; #endregion namespace Concrete.ACI318 { /// <summary> /// Flexural strength /// Category: Concrete.ACI318_14.Flexure /// </summary> /// [IsDesignScriptCompatible] public partial class Flexure { internal Flexure() { } [IsVisibleInDynamoLibrary(false)] public static Flexure ByInputParameters() { return new Flexure(); } } }
{ "content_hash": "d34199dbbab05d4509df2729514e53d5", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 49, "avg_line_length": 13.909090909090908, "alnum_prop": 0.6258169934640523, "repo_name": "Kodestruct/Kodestruct.Dynamo", "id": "a77699673cf3733179d24b790331b5b2035a56f8", "size": "1207", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Kodestruct/Concrete/ACI318/Section/FlexureAndAxial/Groups/Flexure.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "1690019" }, { "name": "PowerShell", "bytes": "7302" } ], "symlink_target": "" }
using GraphicsEngine.Datatypes; using GraphicsEngine.Meshes; using Jitter.Dynamics; using Jitter.LinearMath; namespace GraphicsEngine.Tests { public class PyramidPhysics3D : GraphicsApp { public PyramidPhysics3D() : base("PyramidPhysics3D Tests") {} public static void Main() { new PyramidPhysics3D().Run(RenderMode.Render3D); } protected override void Init() { base.Init(); var cubeTexture = new Texture("BoxDiffuse.jpg"); for (int z=0; z<PyramidHeight; z++) for (int x=0; x<PyramidHeight-z; x++) new Cube(cubeTexture, new Vector3D( 1.1f*(x-(PyramidHeight-z)/2.0f), 0, 1.2f*z+0.55f)); } private const int PyramidHeight = 12; protected override void Update() { base.Update(); if (form.MouseClickedHappenend) { form.MouseClickedHappenend = false; var screenPosition = new JVector( -1f + 2* (form.MouseClickPosition.x / form.ClientSize.Width), 1, -1f + 2 * ((form.MouseClickPosition.y / form.ClientSize.Height))); var projectionMatrix = Common.ProjectionMatrix; JMatrix jMatrix = new JMatrix( projectionMatrix.M11, projectionMatrix.M12, projectionMatrix.M13, projectionMatrix.M21, projectionMatrix.M22, projectionMatrix.M23, projectionMatrix.M31, projectionMatrix.M32, projectionMatrix.M33); JMatrix invertedJMatrix; JMatrix.Invert(ref jMatrix, out invertedJMatrix); var rayDirection = JVector.Transform(screenPosition, invertedJMatrix); RigidBody body; JVector normal; float fraction; Entities.world3D.CollisionSystem.Raycast(JitterDatatypes.ToJVector(Common.CameraPosition), rayDirection, null, out body, out normal, out fraction); if (body != null && !body.IsStatic) body.ApplyImpulse(rayDirection * 200); } } } }
{ "content_hash": "25b9866024bc9cb2389aa72ccd7d8a35", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 94, "avg_line_length": 31.660714285714285, "alnum_prop": 0.7106598984771574, "repo_name": "BenjaminNitschke/PhysicsCourse", "id": "81fbe9b7893a7b4b2ec24a5c65458fb7e85f5e74", "size": "1775", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "GraphicsEngine/Tests/PyramidPhysics3D.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "76960" } ], "symlink_target": "" }
/*! * \file Surface.cpp * \brief Surface configuration information. * * A surface consists of a name with associated placement frames and points of interest. * * \author Russell Toris, WPI - rctoris@wpi.edu * \date March 18, 2015 */ #include <interactive_world_tools/Surface.h> #include <stdexcept> using namespace std; using namespace rail::interactive_world; Surface::Surface(const string &name, const string &frame_id, const double width, const double height) : name_(name), frame_id_(frame_id) { width_ = width; height_ = height; } const string &Surface::getName() const { return name_; } void Surface::setName(const string &name) { name_ = name; } const string &Surface::getFrameID() const { return frame_id_; } void Surface::setFrameID(const string &frame_id) { frame_id_ = frame_id; } double Surface::getWidth() const { return width_; } void Surface::setWidth(const double width) { width_ = width; } double Surface::getHeight() const { return height_; } void Surface::setHeight(const double height) { height_ = height; } const vector<PlacementSurface> &Surface::getPlacementSurfaces() const { return placement_surfaces_; } size_t Surface::getNumPlacementSurfaces() const { return placement_surfaces_.size(); } const PlacementSurface &Surface::getPlacementSurface(const size_t index) const { // check the index value first if (index < placement_surfaces_.size()) { return placement_surfaces_[index]; } else { throw std::out_of_range("Surface::getPlacementSurface : Placement surface index does not exist."); } } void Surface::addPlacementSurface(const PlacementSurface &placement_surface) { placement_surfaces_.push_back(placement_surface); } void Surface::removePlacementSurface(const size_t index) { // check the index value first if (index < placement_surfaces_.size()) { placement_surfaces_.erase(placement_surfaces_.begin() + index); } else { throw std::out_of_range("Surface::removePlacementSurface : Placement surface index does not exist."); } } const std::vector<PointOfInterest> &Surface::getPointsOfInterest() const { return pois_; } size_t Surface::getNumPointsOfInterest() const { return pois_.size(); } const PointOfInterest &Surface::getPointOfInterest(const size_t index) const { // check the index value first if (index < pois_.size()) { return pois_[index]; } else { throw std::out_of_range("Surface::getPointOfInterest : Point of interest index does not exist."); } } void Surface::addPointOfInterest(const PointOfInterest &point_of_interest) { pois_.push_back(point_of_interest); } void Surface::removePointOfInterest(const size_t index) { // check the index value first if (index < pois_.size()) { pois_.erase(pois_.begin() + index); } else { throw std::out_of_range("Surface::removePointOfInterest : Point of interest index does not exist."); } } const std::vector<std::string> &Surface::getAliases() const { return aliases_; } size_t Surface::getNumAliases() const { return aliases_.size(); } const std::string &Surface::getAlias(const size_t index) const { // check the index value first if (index < aliases_.size()) { return aliases_[index]; } else { throw std::out_of_range("Surface::getAlias : Alias index does not exist."); } } void Surface::addAlias(const std::string &alias) { aliases_.push_back(alias); } void Surface::removeAlias(const size_t index) { // check the index value first if (index < aliases_.size()) { aliases_.erase(aliases_.begin() + index); } else { throw std::out_of_range("Surface::removeAlias : Alias index does not exist."); } }
{ "content_hash": "7a1e8deeceac5fbb14c0af2290a338a7", "timestamp": "", "source": "github", "line_count": 180, "max_line_length": 105, "avg_line_length": 20.461111111111112, "alnum_prop": 0.6959000814553353, "repo_name": "WPI-RAIL/interactive_world", "id": "4e24d1f1788e506116e36399d7bd2327edcecb7b", "size": "3683", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "interactive_world_tools/src/Surface.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "111179" }, { "name": "CMake", "bytes": "11138" }, { "name": "Java", "bytes": "90070" }, { "name": "Shell", "bytes": "179" } ], "symlink_target": "" }
package com.coolweather.android; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 一开始先从SharedPreferences文件中读取缓存数据 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); // 如果不为null就说明之前已经请求过天气数据了,那么就没必要让用户再次选择城市,而是直接跳转到WeatherActivity if (prefs.getString("wearher",null) != null) { Intent intent = new Intent(this,WeatherActivity.class); startActivity(intent); finish(); } } }
{ "content_hash": "fc8f4c2be803d0d6ad3c4f719afbe801", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 86, "avg_line_length": 35.25, "alnum_prop": 0.7328605200945626, "repo_name": "616342178/coolweather", "id": "7410d31ec0bcde527a3002d45aa01ad01e0cc98b", "size": "956", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/coolweather/android/MainActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "41048" } ], "symlink_target": "" }
package org.apache.zookeeper.metrics; import java.util.Properties; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import org.apache.zookeeper.metrics.impl.NullMetricsProvider; /** * Simple MetricsProvider for tests. */ public abstract class BaseTestMetricsProvider implements MetricsProvider { @Override public void configure(Properties prprts) throws MetricsProviderLifeCycleException { } @Override public void start() throws MetricsProviderLifeCycleException { } @Override public MetricsContext getRootContext() { return NullMetricsProvider.NullMetricsContext.INSTANCE; } @Override public void stop() { } @Override public void dump(BiConsumer<String, Object> sink) { } @Override public void resetAllValues() { } public static final class MetricsProviderCapturingLifecycle extends BaseTestMetricsProvider { public static final AtomicBoolean configureCalled = new AtomicBoolean(); public static final AtomicBoolean startCalled = new AtomicBoolean(); public static final AtomicBoolean stopCalled = new AtomicBoolean(); public static final AtomicBoolean getRootContextCalled = new AtomicBoolean(); public static void reset() { configureCalled.set(false); startCalled.set(false); stopCalled.set(false); getRootContextCalled.set(false); } @Override public void configure(Properties prprts) throws MetricsProviderLifeCycleException { if (!configureCalled.compareAndSet(false, true)) { // called twice throw new IllegalStateException(); } } @Override public void start() throws MetricsProviderLifeCycleException { if (!startCalled.compareAndSet(false, true)) { // called twice throw new IllegalStateException(); } } @Override public MetricsContext getRootContext() { getRootContextCalled.set(true); return NullMetricsProvider.NullMetricsContext.INSTANCE; } @Override public void stop() { if (!stopCalled.compareAndSet(false, true)) { // called twice throw new IllegalStateException(); } } } public static final class MetricsProviderWithErrorInStart extends BaseTestMetricsProvider { @Override public void start() throws MetricsProviderLifeCycleException { throw new MetricsProviderLifeCycleException(); } } public static final class MetricsProviderWithErrorInConfigure extends BaseTestMetricsProvider { @Override public void configure(Properties prprts) throws MetricsProviderLifeCycleException { throw new MetricsProviderLifeCycleException(); } } public static final class MetricsProviderWithConfiguration extends BaseTestMetricsProvider { public static final AtomicInteger httpPort = new AtomicInteger(); @Override public void configure(Properties prprts) throws MetricsProviderLifeCycleException { httpPort.set(Integer.parseInt(prprts.getProperty("httpPort"))); } } public static final class MetricsProviderWithErrorInStop extends BaseTestMetricsProvider { public static final AtomicBoolean stopCalled = new AtomicBoolean(); @Override public void stop() { stopCalled.set(true); throw new RuntimeException(); } } }
{ "content_hash": "b1dd99711de04bc0eee71b7feb96fa37", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 99, "avg_line_length": 28.790697674418606, "alnum_prop": 0.6674744211093161, "repo_name": "maoling/zookeeper", "id": "7ce361cfe2a254abc834ee49bf9a89b48083de4a", "size": "4519", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "zookeeper-server/src/test/java/org/apache/zookeeper/metrics/BaseTestMetricsProvider.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "10133" }, { "name": "C", "bytes": "627863" }, { "name": "C++", "bytes": "708872" }, { "name": "CMake", "bytes": "10533" }, { "name": "CSS", "bytes": "22915" }, { "name": "Dockerfile", "bytes": "1030" }, { "name": "HTML", "bytes": "43586" }, { "name": "Java", "bytes": "6881032" }, { "name": "JavaScript", "bytes": "246638" }, { "name": "M4", "bytes": "52000" }, { "name": "Makefile", "bytes": "11657" }, { "name": "Mako", "bytes": "13704" }, { "name": "Perl", "bytes": "87261" }, { "name": "Python", "bytes": "163305" }, { "name": "Raku", "bytes": "67310" }, { "name": "Shell", "bytes": "116200" }, { "name": "XS", "bytes": "68654" }, { "name": "XSLT", "bytes": "6024" } ], "symlink_target": "" }
/** * Copyright (c) 2014, ControlsFX * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the name of ControlsFX, any associated website, 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 CONTROLSFX 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. */ package com.github.haixing_hu.javafx.control.textfield; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.scene.Node; import javafx.scene.control.PasswordField; import javafx.scene.control.Skin; import javax.annotation.Nullable; /** * A base class for people wanting to customize a {@link PasswordField} to * contain nodes inside the input field area itself, without being on top of the * users typed-in text. * * <p> * Whilst not exactly the same, refer to the {@link CustomTextField} javadoc for * a screenshot and more detail. The obvious difference is that of course the * CustomPasswordField masks the input from users, but in all other ways is * equivalent to {@link CustomTextField}. * * @see CustomPasswordField * @see TextFields * @author ControlsFX * @author Haixing Hu */ public class CustomPasswordField extends PasswordField { public static final String STYLE_CLASS = "custom-password-field"; private final ObjectProperty<Node> left; private final ObjectProperty<Node> right; /** * Instantiates a default CustomPasswordField. */ public CustomPasswordField() { super(); left = new SimpleObjectProperty<>(this, "left"); right = new SimpleObjectProperty<>(this, "right"); getStyleClass().addAll(CustomTextField.STYLE_CLASS, STYLE_CLASS); } /** * Gets the {@link ObjectProperty} wrapping the {@link Node} that is placed on * the left of the text field. * * @return An {@link ObjectProperty} wrapping the {@link Node} that is placed * on the left of the text field. */ public final ObjectProperty<Node> leftProperty() { return left; } /** * Gets the {@link Node} that is placed on the left of the text field. * * @return the {@link Node} that is placed on the left of the text field, or * {@code null} if has none. */ public final Node getLeft() { return left.get(); } /** * Sets the {@link Node} that is placed on the left of the text field. * * @param value * the new {@link Node} that is placed on the left of the text field, * or {@code null} if has none. */ public final void setLeft(@Nullable Node value) { left.set(value); } /** * Gets the {@link ObjectProperty} wrapping the {@link Node} that is placed on * the right of the text field. * * @return An {@link ObjectProperty} wrapping the {@link Node} that is placed * on the right of the text field. */ public final ObjectProperty<Node> rightProperty() { return right; } /** * Gets the {@link Node} that is placed on the right of the text field. * * @return the {@link Node} that is placed on the right of the text field, or * {@code null} if has none. */ public final Node getRight() { return right.get(); } /** * Sets the {@link Node} that is placed on the right of the text field. * * @param value * the new {@link Node} that is placed on the right of the text * field, or {@code null} if has none. */ public final void setRight(Node value) { right.set(value); } @Override protected Skin<?> createDefaultSkin() { return new CustomTextFieldSkin(this) { @Override public ObjectProperty<Node> leftProperty() { return CustomPasswordField.this.leftProperty(); } @Override public ObjectProperty<Node> rightProperty() { return CustomPasswordField.this.rightProperty(); } }; } }
{ "content_hash": "adfc4a4aa2e6a8a5cd1b3cf68dddd225", "timestamp": "", "source": "github", "line_count": 150, "max_line_length": 82, "avg_line_length": 35.1, "alnum_prop": 0.67673314339981, "repo_name": "Haixing-Hu/javafx-widgets", "id": "400ffbef60fef636f2a12819ab4603dd5ab14697", "size": "5842", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/github/haixing_hu/javafx/control/textfield/CustomPasswordField.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "9912" }, { "name": "Java", "bytes": "345287" } ], "symlink_target": "" }
package com.hazelcast.map.impl.proxy; import com.hazelcast.aggregation.Aggregator; import com.hazelcast.config.MapConfig; import com.hazelcast.core.EntryListener; import com.hazelcast.core.EntryView; import com.hazelcast.core.ExecutionCallback; import com.hazelcast.core.HazelcastException; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.ICompletableFuture; import com.hazelcast.core.IMap; import com.hazelcast.core.ManagedContext; import com.hazelcast.internal.journal.EventJournalInitialSubscriberState; import com.hazelcast.internal.journal.EventJournalReader; import com.hazelcast.map.EntryProcessor; import com.hazelcast.map.MapInterceptor; import com.hazelcast.map.QueryCache; import com.hazelcast.map.impl.MapService; import com.hazelcast.map.impl.SimpleEntryView; import com.hazelcast.map.impl.iterator.MapPartitionIterator; import com.hazelcast.map.impl.iterator.MapQueryPartitionIterator; import com.hazelcast.map.impl.journal.MapEventJournalReadOperation; import com.hazelcast.map.impl.journal.MapEventJournalSubscribeOperation; import com.hazelcast.map.impl.query.AggregationResult; import com.hazelcast.map.impl.query.QueryResult; import com.hazelcast.map.impl.query.Target; import com.hazelcast.map.impl.querycache.QueryCacheContext; import com.hazelcast.map.impl.querycache.subscriber.NodeQueryCacheEndToEndConstructor; import com.hazelcast.map.impl.querycache.subscriber.QueryCacheEndToEndProvider; import com.hazelcast.map.impl.querycache.subscriber.QueryCacheRequest; import com.hazelcast.map.impl.querycache.subscriber.SubscriberContext; import com.hazelcast.map.journal.EventJournalMapEvent; import com.hazelcast.map.listener.MapListener; import com.hazelcast.map.listener.MapPartitionLostListener; import com.hazelcast.mapreduce.Collator; import com.hazelcast.mapreduce.CombinerFactory; import com.hazelcast.mapreduce.Job; import com.hazelcast.mapreduce.JobTracker; import com.hazelcast.mapreduce.KeyValueSource; import com.hazelcast.mapreduce.Mapper; import com.hazelcast.mapreduce.MappingJob; import com.hazelcast.mapreduce.ReducerFactory; import com.hazelcast.mapreduce.ReducingSubmittableJob; import com.hazelcast.mapreduce.aggregation.Aggregation; import com.hazelcast.mapreduce.aggregation.Supplier; import com.hazelcast.nio.serialization.Data; import com.hazelcast.projection.Projection; import com.hazelcast.query.PagingPredicate; import com.hazelcast.query.Predicate; import com.hazelcast.query.TruePredicate; import com.hazelcast.ringbuffer.ReadResultSet; import com.hazelcast.spi.InternalCompletableFuture; import com.hazelcast.spi.NodeEngine; import com.hazelcast.spi.Operation; import com.hazelcast.util.CollectionUtil; import com.hazelcast.util.IterationType; import com.hazelcast.util.executor.DelegatingFuture; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import static com.hazelcast.config.InMemoryFormat.NATIVE; import static com.hazelcast.internal.cluster.Versions.V3_11; import static com.hazelcast.map.impl.MapService.SERVICE_NAME; import static com.hazelcast.map.impl.query.QueryResultUtils.transformToSet; import static com.hazelcast.map.impl.querycache.subscriber.QueryCacheRequest.newQueryCacheRequest; import static com.hazelcast.map.impl.recordstore.RecordStore.DEFAULT_MAX_IDLE; import static com.hazelcast.util.MapUtil.createHashMap; import static com.hazelcast.util.Preconditions.checkNoNullInside; import static com.hazelcast.util.Preconditions.checkNotInstanceOf; import static com.hazelcast.util.Preconditions.checkNotNull; import static com.hazelcast.util.Preconditions.checkPositive; import static com.hazelcast.util.Preconditions.checkTrue; import static com.hazelcast.util.Preconditions.isNotNull; import static com.hazelcast.util.SetUtil.createHashSet; import static java.util.Collections.emptyMap; /** * Proxy implementation of {@link com.hazelcast.core.IMap} interface. * * @param <K> the key type of map. * @param <V> the value type of map. */ @SuppressWarnings("checkstyle:classfanoutcomplexity") public class MapProxyImpl<K, V> extends MapProxySupport<K, V> implements EventJournalReader<EventJournalMapEvent<K, V>> { public MapProxyImpl(String name, MapService mapService, NodeEngine nodeEngine, MapConfig mapConfig) { super(name, mapService, nodeEngine, mapConfig); } @Override public V get(Object key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); return toObject(getInternal(key)); } @Override public V put(K key, V value) { return put(key, value, -1, TimeUnit.MILLISECONDS); } @Override public V put(K key, V value, long ttl, TimeUnit timeunit) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); Data valueData = toData(value); Data result = putInternal(key, valueData, ttl, timeunit, DEFAULT_MAX_IDLE, TimeUnit.MILLISECONDS); return toObject(result); } @Override public V put(K key, V value, long ttl, TimeUnit ttlUnit, long maxIdle, TimeUnit maxIdleUnit) { if (isClusterVersionLessThan(V3_11)) { throw new UnsupportedOperationException("put with Max-Idle operation is available " + "when cluster version is 3.11 or higher"); } checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); Data valueData = toData(value); Data result = putInternal(key, valueData, ttl, ttlUnit, maxIdle, maxIdleUnit); return toObject(result); } @Override public boolean tryPut(K key, V value, long timeout, TimeUnit timeunit) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); Data valueData = toData(value); return tryPutInternal(key, valueData, timeout, timeunit); } @Override public V putIfAbsent(K key, V value) { return putIfAbsent(key, value, -1, TimeUnit.MILLISECONDS); } @Override public V putIfAbsent(K key, V value, long ttl, TimeUnit timeunit) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); Data valueData = toData(value); Data result = putIfAbsentInternal(key, valueData, ttl, timeunit, DEFAULT_MAX_IDLE, TimeUnit.MILLISECONDS); return toObject(result); } @Override public V putIfAbsent(K key, V value, long ttl, TimeUnit timeunit, long maxIdle, TimeUnit maxIdleUnit) { if (isClusterVersionLessThan(V3_11)) { throw new UnsupportedOperationException("putIfAbsent with Max-Idle operation is available " + "when cluster version is 3.11 or higher"); } checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); Data valueData = toData(value); Data result = putIfAbsentInternal(key, valueData, ttl, timeunit, maxIdle, maxIdleUnit); return toObject(result); } @Override public void putTransient(K key, V value, long ttl, TimeUnit timeunit) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); Data valueData = toData(value); putTransientInternal(key, valueData, ttl, timeunit, DEFAULT_MAX_IDLE, TimeUnit.MILLISECONDS); } @Override public void putTransient(K key, V value, long ttl, TimeUnit ttlUnit, long maxIdle, TimeUnit maxIdleUnit) { if (isClusterVersionLessThan(V3_11)) { throw new UnsupportedOperationException("putTransient with Max-Idle operation is available " + "when cluster version is 3.11 or higher"); } checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); Data valueData = toData(value); putTransientInternal(key, valueData, ttl, ttlUnit, maxIdle, maxIdleUnit); } @Override public boolean replace(K key, V oldValue, V newValue) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(oldValue, NULL_VALUE_IS_NOT_ALLOWED); checkNotNull(newValue, NULL_VALUE_IS_NOT_ALLOWED); Data oldValueData = toData(oldValue); Data newValueData = toData(newValue); return replaceInternal(key, oldValueData, newValueData); } @Override public V replace(K key, V value) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); Data valueData = toData(value); return toObject(replaceInternal(key, valueData)); } @Override public void set(K key, V value) { set(key, value, -1, TimeUnit.MILLISECONDS); } @Override public void set(K key, V value, long ttl, TimeUnit ttlUnit) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); Data valueData = toData(value); setInternal(key, valueData, ttl, ttlUnit, DEFAULT_MAX_IDLE, TimeUnit.MILLISECONDS); } @Override public void set(K key, V value, long ttl, TimeUnit ttlUnit, long maxIdle, TimeUnit maxIdleUnit) { if (isClusterVersionLessThan(V3_11)) { throw new UnsupportedOperationException("set with Max-Idle operation is available " + "when cluster version is 3.11 or higher"); } checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); Data valueData = toData(value); setInternal(key, valueData, ttl, ttlUnit, maxIdle, maxIdleUnit); } @Override public V remove(Object key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); Data result = removeInternal(key); return toObject(result); } @Override public boolean remove(Object key, Object value) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); Data valueData = toData(value); return removeInternal(key, valueData); } @Override public void removeAll(Predicate<K, V> predicate) { checkNotNull(predicate, "predicate cannot be null"); handleHazelcastInstanceAwareParams(predicate); removeAllInternal(predicate); } @Override public void delete(Object key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); deleteInternal(key); } @Override public boolean containsKey(Object key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); return containsKeyInternal(key); } @Override public boolean containsValue(Object value) { checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); Data valueData = toData(value); return containsValueInternal(valueData); } @Override public void lock(K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); Data keyData = toDataWithStrategy(key); lockSupport.lock(getNodeEngine(), keyData); } @Override public void lock(Object key, long leaseTime, TimeUnit timeUnit) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkPositive(leaseTime, "leaseTime should be positive"); Data keyData = toDataWithStrategy(key); lockSupport.lock(getNodeEngine(), keyData, timeUnit.toMillis(leaseTime)); } @Override public void unlock(K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); Data keyData = toDataWithStrategy(key); lockSupport.unlock(getNodeEngine(), keyData); } @Override public boolean tryRemove(K key, long timeout, TimeUnit timeunit) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); return tryRemoveInternal(key, timeout, timeunit); } @Override public ICompletableFuture<V> getAsync(K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); return new DelegatingFuture<V>(getAsyncInternal(key), serializationService); } @Override public boolean isLocked(K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); Data keyData = toDataWithStrategy(key); return lockSupport.isLocked(getNodeEngine(), keyData); } @Override public ICompletableFuture<V> putAsync(K key, V value) { return putAsync(key, value, -1, TimeUnit.MILLISECONDS); } @Override public ICompletableFuture<V> putAsync(K key, V value, long ttl, TimeUnit timeunit) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); Data valueData = toData(value); return new DelegatingFuture<V>( putAsyncInternal(key, valueData, ttl, timeunit, DEFAULT_MAX_IDLE, TimeUnit.MILLISECONDS), serializationService); } @Override public ICompletableFuture<V> putAsync(K key, V value, long ttl, TimeUnit ttlUnit, long maxIdle, TimeUnit maxIdleUnit) { if (isClusterVersionLessThan(V3_11)) { throw new UnsupportedOperationException("putAsync with Max-Idle operation is available " + "when cluster version is 3.11 or higher"); } checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); Data valueData = toData(value); return new DelegatingFuture<V>( putAsyncInternal(key, valueData, ttl, ttlUnit, maxIdle, maxIdleUnit), serializationService); } @Override public ICompletableFuture<Void> setAsync(K key, V value) { return setAsync(key, value, -1, TimeUnit.MILLISECONDS); } @Override public ICompletableFuture<Void> setAsync(K key, V value, long ttl, TimeUnit timeunit) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); Data valueData = toData(value); return new DelegatingFuture<Void>( setAsyncInternal(key, valueData, ttl, timeunit, DEFAULT_MAX_IDLE, TimeUnit.MILLISECONDS), serializationService); } @Override public ICompletableFuture<Void> setAsync(K key, V value, long ttl, TimeUnit ttlUnit, long maxIdle, TimeUnit maxIdleUnit) { if (isClusterVersionLessThan(V3_11)) { throw new UnsupportedOperationException("setAsync with Max-Idle operation is available " + "when cluster version is 3.11 or higher"); } checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); checkNotNull(value, NULL_VALUE_IS_NOT_ALLOWED); Data valueData = toData(value); return new DelegatingFuture<Void>( setAsyncInternal(key, valueData, ttl, ttlUnit, maxIdle, maxIdleUnit), serializationService); } @Override public ICompletableFuture<V> removeAsync(K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); return new DelegatingFuture<V>(removeAsyncInternal(key), serializationService); } @Override public Map<K, V> getAll(Set<K> keys) { if (CollectionUtil.isEmpty(keys)) { return emptyMap(); } int keysSize = keys.size(); List<Data> dataKeys = new LinkedList<Data>(); List<Object> resultingKeyValuePairs = new ArrayList<Object>(keysSize * 2); getAllInternal(keys, dataKeys, resultingKeyValuePairs); Map<K, V> result = createHashMap(keysSize); for (int i = 0; i < resultingKeyValuePairs.size(); ) { K key = toObject(resultingKeyValuePairs.get(i++)); V value = toObject(resultingKeyValuePairs.get(i++)); result.put(key, value); } return result; } @Override public boolean setTtl(K key, long ttl, TimeUnit timeunit) { checkNotNull(key); checkNotNull(timeunit); return setTtlInternal(key, ttl, timeunit); } @Override public void putAll(Map<? extends K, ? extends V> map) { checkNotNull(map, "Null argument map is not allowed"); putAllInternal(map); } @Override public boolean tryLock(K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); Data keyData = toDataWithStrategy(key); return lockSupport.tryLock(getNodeEngine(), keyData); } @Override public boolean tryLock(K key, long time, TimeUnit timeunit) throws InterruptedException { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); Data keyData = toDataWithStrategy(key); return lockSupport.tryLock(getNodeEngine(), keyData, time, timeunit); } @Override public boolean tryLock(K key, long time, TimeUnit timeunit, long leaseTime, TimeUnit leaseTimeUnit) throws InterruptedException { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); Data keyData = toDataWithStrategy(key); return lockSupport.tryLock(getNodeEngine(), keyData, time, timeunit, leaseTime, leaseTimeUnit); } @Override public void forceUnlock(K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); Data keyData = toDataWithStrategy(key); lockSupport.forceUnlock(getNodeEngine(), keyData); } @Override public String addInterceptor(MapInterceptor interceptor) { checkNotNull(interceptor, "Interceptor should not be null!"); handleHazelcastInstanceAwareParams(interceptor); return addMapInterceptorInternal(interceptor); } @Override public void removeInterceptor(String id) { checkNotNull(id, "Interceptor ID should not be null!"); removeMapInterceptorInternal(id); } @Override public String addLocalEntryListener(MapListener listener) { checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED); handleHazelcastInstanceAwareParams(listener); return addLocalEntryListenerInternal(listener); } @Override public String addLocalEntryListener(EntryListener listener) { checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED); handleHazelcastInstanceAwareParams(listener); return addLocalEntryListenerInternal(listener); } @Override public String addLocalEntryListener(MapListener listener, Predicate<K, V> predicate, boolean includeValue) { checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED); checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED); handleHazelcastInstanceAwareParams(listener, predicate); return addLocalEntryListenerInternal(listener, predicate, null, includeValue); } @Override public String addLocalEntryListener(EntryListener listener, Predicate<K, V> predicate, boolean includeValue) { checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED); checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED); handleHazelcastInstanceAwareParams(listener, predicate); return addLocalEntryListenerInternal(listener, predicate, null, includeValue); } @Override public String addLocalEntryListener(MapListener listener, Predicate<K, V> predicate, K key, boolean includeValue) { checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED); checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED); handleHazelcastInstanceAwareParams(listener, predicate); return addLocalEntryListenerInternal(listener, predicate, toDataWithStrategy(key), includeValue); } @Override public String addLocalEntryListener(EntryListener listener, Predicate<K, V> predicate, K key, boolean includeValue) { checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED); checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED); handleHazelcastInstanceAwareParams(listener, predicate); return addLocalEntryListenerInternal(listener, predicate, toDataWithStrategy(key), includeValue); } @Override public String addEntryListener(MapListener listener, boolean includeValue) { checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED); handleHazelcastInstanceAwareParams(listener); return addEntryListenerInternal(listener, null, includeValue); } @Override public String addEntryListener(EntryListener listener, boolean includeValue) { checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED); handleHazelcastInstanceAwareParams(listener); return addEntryListenerInternal(listener, null, includeValue); } @Override public String addEntryListener(MapListener listener, K key, boolean includeValue) { checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED); checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); handleHazelcastInstanceAwareParams(listener); return addEntryListenerInternal(listener, toDataWithStrategy(key), includeValue); } @Override public String addEntryListener(EntryListener listener, K key, boolean includeValue) { checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED); checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); handleHazelcastInstanceAwareParams(listener); return addEntryListenerInternal(listener, toDataWithStrategy(key), includeValue); } @Override public String addEntryListener(MapListener listener, Predicate<K, V> predicate, K key, boolean includeValue) { checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED); checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED); handleHazelcastInstanceAwareParams(listener, predicate); return addEntryListenerInternal(listener, predicate, toDataWithStrategy(key), includeValue); } @Override public String addEntryListener(EntryListener listener, Predicate<K, V> predicate, K key, boolean includeValue) { checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED); checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED); handleHazelcastInstanceAwareParams(listener, predicate); return addEntryListenerInternal(listener, predicate, toDataWithStrategy(key), includeValue); } @Override public String addEntryListener(MapListener listener, Predicate<K, V> predicate, boolean includeValue) { checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED); checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED); handleHazelcastInstanceAwareParams(listener, predicate); return addEntryListenerInternal(listener, predicate, null, includeValue); } @Override public String addEntryListener(EntryListener listener, Predicate<K, V> predicate, boolean includeValue) { checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED); checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED); handleHazelcastInstanceAwareParams(listener, predicate); return addEntryListenerInternal(listener, predicate, null, includeValue); } @Override public boolean removeEntryListener(String id) { checkNotNull(id, "Listener ID should not be null!"); return removeEntryListenerInternal(id); } @Override public String addPartitionLostListener(MapPartitionLostListener listener) { checkNotNull(listener, NULL_LISTENER_IS_NOT_ALLOWED); handleHazelcastInstanceAwareParams(listener); return addPartitionLostListenerInternal(listener); } @Override public boolean removePartitionLostListener(String id) { checkNotNull(id, "Listener ID should not be null!"); return removePartitionLostListenerInternal(id); } @Override @SuppressWarnings("unchecked") public EntryView<K, V> getEntryView(K key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); SimpleEntryView<K, V> entryViewInternal = (SimpleEntryView<K, V>) getEntryViewInternal(toDataWithStrategy(key)); if (entryViewInternal == null) { return null; } Data value = (Data) entryViewInternal.getValue(); entryViewInternal.setKey(key); entryViewInternal.setValue((V) toObject(value)); return entryViewInternal; } @Override public boolean evict(Object key) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); return evictInternal(key); } @Override public void evictAll() { evictAllInternal(); } @Override public void loadAll(boolean replaceExistingValues) { checkTrue(isMapStoreEnabled(), "First you should configure a map store"); loadAllInternal(replaceExistingValues); } @Override public void loadAll(Set<K> keys, boolean replaceExistingValues) { checkTrue(isMapStoreEnabled(), "First you should configure a map store"); checkNotNull(keys, NULL_KEYS_ARE_NOT_ALLOWED); checkNoNullInside(keys, NULL_KEY_IS_NOT_ALLOWED); loadInternal(keys, null, replaceExistingValues); } @Override public void clear() { clearInternal(); } @Override public Set<K> keySet() { return keySet(TruePredicate.INSTANCE); } @Override @SuppressWarnings("unchecked") public Set<K> keySet(Predicate predicate) { return executePredicate(predicate, IterationType.KEY, true); } @Override public Set<Map.Entry<K, V>> entrySet() { return entrySet(TruePredicate.INSTANCE); } @Override public Set<Map.Entry<K, V>> entrySet(Predicate predicate) { return executePredicate(predicate, IterationType.ENTRY, true); } @Override public Collection<V> values() { return values(TruePredicate.INSTANCE); } @Override @SuppressWarnings("unchecked") public Collection<V> values(Predicate predicate) { return executePredicate(predicate, IterationType.VALUE, false); } private Set executePredicate(Predicate predicate, IterationType iterationType, boolean uniqueResult) { checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED); QueryResult result = executeQueryInternal(predicate, iterationType, Target.ALL_NODES); return transformToSet(serializationService, result, predicate, iterationType, uniqueResult, false); } @Override public Set<K> localKeySet() { return localKeySet(TruePredicate.INSTANCE); } @Override @SuppressWarnings("unchecked") public Set<K> localKeySet(Predicate predicate) { checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED); QueryResult result = executeQueryInternal(predicate, IterationType.KEY, Target.LOCAL_NODE); return transformToSet(serializationService, result, predicate, IterationType.KEY, false, false); } @Override public Object executeOnKey(K key, EntryProcessor entryProcessor) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); handleHazelcastInstanceAwareParams(entryProcessor); Data result = executeOnKeyInternal(key, entryProcessor); return toObject(result); } @Override public Map<K, Object> executeOnKeys(Set<K> keys, EntryProcessor entryProcessor) { checkNotNull(keys, NULL_KEYS_ARE_NOT_ALLOWED); handleHazelcastInstanceAwareParams(entryProcessor); if (keys.isEmpty()) { return emptyMap(); } Set<Data> dataKeys = createHashSet(keys.size()); return executeOnKeysInternal(keys, dataKeys, entryProcessor); } @Override public void submitToKey(K key, EntryProcessor entryProcessor, ExecutionCallback callback) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); handleHazelcastInstanceAwareParams(entryProcessor, callback); executeOnKeyInternal(key, entryProcessor, callback); } @Override public ICompletableFuture submitToKey(K key, EntryProcessor entryProcessor) { checkNotNull(key, NULL_KEY_IS_NOT_ALLOWED); handleHazelcastInstanceAwareParams(entryProcessor); InternalCompletableFuture future = executeOnKeyInternal(key, entryProcessor, null); return new DelegatingFuture(future, serializationService); } @Override public Map<K, Object> executeOnEntries(EntryProcessor entryProcessor) { return executeOnEntries(entryProcessor, TruePredicate.INSTANCE); } @Override public Map<K, Object> executeOnEntries(EntryProcessor entryProcessor, Predicate predicate) { handleHazelcastInstanceAwareParams(entryProcessor, predicate); List<Data> result = new ArrayList<Data>(); executeOnEntriesInternal(entryProcessor, predicate, result); if (result.isEmpty()) { return emptyMap(); } Map<K, Object> resultingMap = createHashMap(result.size() / 2); for (int i = 0; i < result.size(); ) { Data key = result.get(i++); Data value = result.get(i++); resultingMap.put((K) toObject(key), toObject(value)); } return resultingMap; } @Override public <R> R aggregate(Aggregator<Map.Entry<K, V>, R> aggregator) { return aggregate(aggregator, TruePredicate.<K, V>truePredicate()); } @Override public <R> R aggregate(Aggregator<Map.Entry<K, V>, R> aggregator, Predicate<K, V> predicate) { checkNotNull(aggregator, NULL_AGGREGATOR_IS_NOT_ALLOWED); checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED); checkNotPagingPredicate(predicate, "aggregate"); // HazelcastInstanceAware handled by cloning aggregator = serializationService.toObject(serializationService.toData(aggregator)); AggregationResult result = executeQueryInternal(predicate, aggregator, null, IterationType.ENTRY, Target.ALL_NODES); return result.<R>getAggregator().aggregate(); } @Override public <R> Collection<R> project(Projection<Map.Entry<K, V>, R> projection) { return project(projection, TruePredicate.INSTANCE); } @Override public <R> Collection<R> project(Projection<Map.Entry<K, V>, R> projection, Predicate<K, V> predicate) { checkNotNull(projection, NULL_PROJECTION_IS_NOT_ALLOWED); checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED); checkNotPagingPredicate(predicate, "project"); // HazelcastInstanceAware handled by cloning projection = serializationService.toObject(serializationService.toData(projection)); QueryResult result = executeQueryInternal(predicate, null, projection, IterationType.VALUE, Target.ALL_NODES); return transformToSet(serializationService, result, predicate, IterationType.VALUE, false, false); } @Override public <SuppliedValue, Result> Result aggregate(Supplier<K, V, SuppliedValue> supplier, Aggregation<K, SuppliedValue, Result> aggregation) { checkTrue(NATIVE != mapConfig.getInMemoryFormat(), "NATIVE storage format is not supported for MapReduce"); HazelcastInstance hazelcastInstance = getNodeEngine().getHazelcastInstance(); JobTracker jobTracker = hazelcastInstance.getJobTracker("hz::aggregation-map-" + getName()); return aggregate(supplier, aggregation, jobTracker); } @Override public <SuppliedValue, Result> Result aggregate(Supplier<K, V, SuppliedValue> supplier, Aggregation<K, SuppliedValue, Result> aggregation, JobTracker jobTracker) { checkTrue(NATIVE != mapConfig.getInMemoryFormat(), "NATIVE storage format is not supported for MapReduce"); try { isNotNull(jobTracker, "jobTracker"); KeyValueSource<K, V> keyValueSource = KeyValueSource.fromMap(this); Job<K, V> job = jobTracker.newJob(keyValueSource); Mapper mapper = aggregation.getMapper(supplier); CombinerFactory combinerFactory = aggregation.getCombinerFactory(); ReducerFactory reducerFactory = aggregation.getReducerFactory(); Collator collator = aggregation.getCollator(); MappingJob mappingJob = job.mapper(mapper); ReducingSubmittableJob reducingJob; if (combinerFactory == null) { reducingJob = mappingJob.reducer(reducerFactory); } else { reducingJob = mappingJob.combiner(combinerFactory).reducer(reducerFactory); } ICompletableFuture<Result> future = reducingJob.submit(collator); return future.get(); } catch (Exception e) { // TODO: not what we want, because it can lead to wrapping of HazelcastException throw new HazelcastException(e); } } protected Object invoke(Operation operation, int partitionId) throws Throwable { Future future = operationService.invokeOnPartition(SERVICE_NAME, operation, partitionId); Object response = future.get(); Object result = toObject(response); if (result instanceof Throwable) { throw (Throwable) result; } return result; } /** * Returns an iterator for iterating entries in the {@code partitionId}. If {@code prefetchValues} is * {@code true}, values will be sent along with the keys and no additional data will be fetched when * iterating. If {@code false}, only keys will be sent and values will be fetched when calling {@code * Map.Entry.getValue()} lazily. * <p> * The entries are not fetched one-by-one but in batches. * You may control the size of the batch by changing the {@code fetchSize} parameter. * A too small {@code fetchSize} can affect performance since more data will have to be sent to and from the partition owner. * A too high {@code fetchSize} means that more data will be sent which can block other operations from being sent, * including internal operations. * The underlying implementation may send more values in one batch than {@code fetchSize} if it needs to get to * a "safepoint" to resume iteration later. * <p> * <b>NOTE</b> * Iterating the map should be done only when the {@link IMap} is not being * mutated and the cluster is stable (there are no migrations or membership changes). * In other cases, the iterator may not return some entries or may return an entry twice. * * @param fetchSize the size of the batches which will be sent when iterating the data * @param partitionId the partition ID which is being iterated * @param prefetchValues whether to send values along with keys (if {@code true}) or * to fetch them lazily when iterating (if {@code false}) * @return the iterator for the projected entries */ public Iterator<Entry<K, V>> iterator(int fetchSize, int partitionId, boolean prefetchValues) { return new MapPartitionIterator<K, V>(this, fetchSize, partitionId, prefetchValues); } /** * Returns an iterator for iterating the result of the projection on entries in the {@code partitionId} which * satisfy the {@code predicate}. * <p> * The values are not fetched one-by-one but rather in batches. * You may control the size of the batch by changing the {@code fetchSize} parameter. * A too small {@code fetchSize} can affect performance since more data will have to be sent to and from the partition owner. * A too high {@code fetchSize} means that more data will be sent which can block other operations from being sent, * including internal operations. * The underlying implementation may send more values in one batch than {@code fetchSize} if it needs to get to * a "safepoint" to later resume iteration. * Predicates of type {@link PagingPredicate} are not supported. * <p> * <b>NOTE</b> * Iterating the map should be done only when the {@link IMap} is not being * mutated and the cluster is stable (there are no migrations or membership changes). * In other cases, the iterator may not return some entries or may return an entry twice. * * @param fetchSize the size of the batches which will be sent when iterating the data * @param partitionId the partition ID which is being iterated * @param projection the projection to apply before returning the value. {@code null} value is not allowed * @param predicate the predicate which the entries must match. {@code null} value is not allowed * @param <R> the return type * @return the iterator for the projected entries * @throws IllegalArgumentException if the predicate is of type {@link PagingPredicate} * @since 3.9 */ public <R> Iterator<R> iterator(int fetchSize, int partitionId, Projection<Map.Entry<K, V>, R> projection, Predicate<K, V> predicate) { if (predicate instanceof PagingPredicate) { throw new IllegalArgumentException("Paging predicate is not allowed when iterating map by query"); } checkNotNull(projection, NULL_PROJECTION_IS_NOT_ALLOWED); checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED); // HazelcastInstanceAware handled by cloning projection = serializationService.toObject(serializationService.toData(projection)); handleHazelcastInstanceAwareParams(predicate); return new MapQueryPartitionIterator<K, V, R>(this, fetchSize, partitionId, predicate, projection); } @Override public ICompletableFuture<EventJournalInitialSubscriberState> subscribeToEventJournal(int partitionId) { final MapEventJournalSubscribeOperation op = new MapEventJournalSubscribeOperation(name); op.setPartitionId(partitionId); return operationService.invokeOnPartition(op); } /** * {@inheritDoc} * <p> * This implementation will skip cloning of the predicate and projection * for performance reasons. Because of this, the results of the projection * and predicate should not depend on any state that will be lost while * cloning. If you wish to get rid of user state, you may clone the predicate * and projection and keep them cached for all calls to this method to avoid * the overhead of cloning. */ @Override public <T> ICompletableFuture<ReadResultSet<T>> readFromEventJournal( long startSequence, int minSize, int maxSize, int partitionId, com.hazelcast.util.function.Predicate<? super EventJournalMapEvent<K, V>> predicate, Projection<? super EventJournalMapEvent<K, V>, ? extends T> projection) { if (maxSize < minSize) { throw new IllegalArgumentException("maxSize " + maxSize + " must be greater or equal to minSize " + minSize); } final ManagedContext context = serializationService.getManagedContext(); context.initialize(predicate); context.initialize(projection); final MapEventJournalReadOperation<K, V, T> op = new MapEventJournalReadOperation<K, V, T>( name, startSequence, minSize, maxSize, predicate, projection); op.setPartitionId(partitionId); return operationService.invokeOnPartition(op); } @Override public String toString() { return "IMap{name='" + name + '\'' + '}'; } @Override public QueryCache<K, V> getQueryCache(String name) { checkNotNull(name, "name cannot be null"); return getQueryCacheInternal(name, null, null, null, this); } @Override public QueryCache<K, V> getQueryCache(String name, Predicate<K, V> predicate, boolean includeValue) { checkNotNull(name, "name cannot be null"); checkNotNull(predicate, "predicate cannot be null"); checkNotInstanceOf(PagingPredicate.class, predicate, "predicate"); handleHazelcastInstanceAwareParams(predicate); return getQueryCacheInternal(name, null, predicate, includeValue, this); } @Override public QueryCache<K, V> getQueryCache(String name, MapListener listener, Predicate<K, V> predicate, boolean includeValue) { checkNotNull(name, "name cannot be null"); checkNotNull(predicate, "predicate cannot be null"); checkNotInstanceOf(PagingPredicate.class, predicate, "predicate"); handleHazelcastInstanceAwareParams(listener, predicate); return getQueryCacheInternal(name, listener, predicate, includeValue, this); } private QueryCache<K, V> getQueryCacheInternal(String name, MapListener listener, Predicate<K, V> predicate, Boolean includeValue, IMap<K, V> map) { QueryCacheContext queryCacheContext = mapServiceContext.getQueryCacheContext(); QueryCacheRequest request = newQueryCacheRequest() .forMap(map) .withCacheName(name) .withListener(listener) .withPredicate(predicate) .withIncludeValue(includeValue) .withContext(queryCacheContext); return createQueryCache(request); } private QueryCache<K, V> createQueryCache(QueryCacheRequest request) { QueryCacheContext queryCacheContext = request.getContext(); SubscriberContext subscriberContext = queryCacheContext.getSubscriberContext(); QueryCacheEndToEndProvider queryCacheEndToEndProvider = subscriberContext.getEndToEndQueryCacheProvider(); return queryCacheEndToEndProvider.getOrCreateQueryCache(request.getMapName(), request.getCacheName(), new NodeQueryCacheEndToEndConstructor(request)); } private static void checkNotPagingPredicate(Predicate predicate, String method) { if (predicate instanceof PagingPredicate) { throw new IllegalArgumentException("PagingPredicate not supported in " + method + " method"); } } }
{ "content_hash": "3c93f5a380acb54c50aee46116018bc2", "timestamp": "", "source": "github", "line_count": 1054, "max_line_length": 129, "avg_line_length": 39.91935483870968, "alnum_prop": 0.6950920974450386, "repo_name": "tkountis/hazelcast", "id": "1d84b27bf907447f55985d4e325355a1ab602bf0", "size": "42700", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hazelcast/src/main/java/com/hazelcast/map/impl/proxy/MapProxyImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1438" }, { "name": "C", "bytes": "344" }, { "name": "Java", "bytes": "39789402" }, { "name": "Shell", "bytes": "15150" } ], "symlink_target": "" }
package name.chengchao.leetcode; import org.junit.Test; import junit.framework.Assert; public class ReverseInteger_007 { @Test public void judge() { Assert.assertEquals(789, reverse(987)); Assert.assertEquals(321, reverse(123)); Assert.assertEquals(0, reverse(0)); Assert.assertEquals(-123, reverse(-321)); Assert.assertEquals(-123, reverse(1534236469)); } public static int reverse(int x) { try { if (x < 0) { return Integer.valueOf("-" + new StringBuilder(String.valueOf(-x)).reverse().toString()); } return Integer.valueOf(new StringBuilder(String.valueOf(x)).reverse().toString()); } catch (Exception e) { return 0; } } }
{ "content_hash": "b15b0fdad6e3d01e9473f258ac8f798d", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 105, "avg_line_length": 26.896551724137932, "alnum_prop": 0.5923076923076923, "repo_name": "ichengchao/java-practice", "id": "455dfcca268adb4d6be4fee5011ed5c909038b5e", "size": "780", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "leetcode/src/main/java/name/chengchao/leetcode/ReverseInteger_007.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2139" }, { "name": "Dockerfile", "bytes": "3413" }, { "name": "HTML", "bytes": "4658" }, { "name": "Java", "bytes": "183308" }, { "name": "JavaScript", "bytes": "6841" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-us"> <head> <link href="http://gmpg.org/xfn/11" rel="profile"> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta property="og:title" content="room"> <meta property="og:type" content="website"> <meta property="og:description" content=""> <meta property="og:url" content="https://satoshun.github.io/tags/room/"> <meta property="og:site_name" content="stsnブログ"> <meta property="twitter:title" content="room"> <meta property="twitter:description" content="Android, Python, Reactive, DB(RDS), etc"> <meta property="twitter:image" content="https://bit.ly/2S8StSM"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1"> <title> room - stsnブログ </title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"> <link rel="stylesheet" href="https://satoshun.github.io/css/main.css"> <link rel="stylesheet" href="https://satoshun.github.io/css/poole.css"> <link rel="stylesheet" href="https://satoshun.github.io/css/syntax.css"> <link rel="stylesheet" href="https://satoshun.github.io/css/hyde.css"> <link rel="stylesheet" href="//fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface"> <link rel="shortcut icon" href="/favicon.png"> <link href="https://satoshun.github.io/tags/room/index.xml" rel="alternate" type="application/rss+xml" title="stsnブログ" /> <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet"> <link href='//fonts.googleapis.com/css?family=Raleway:400,300' rel='stylesheet' type='text/css'> <script src="//ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js"></script> <script> WebFont.load({ google: { families: ['Raleway'] } }); </script> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/styles/agate.min.css"> <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/highlight.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/languages/kotlin.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/languages/groovy.min.js"></script> <script>hljs.initHighlightingOnLoad();</script> </head> <body class="theme-dark"> <section class="site-nav"> <header class="container"> <nav id="navigation"> <a href="/" class="home">Home</a> <a href="/blog">Blog</a> <a href="/presentation">Presentation</a> <a href="/book">Book</a> </nav> </header> </section> <div class="blog-cover"> <section> <div class="container"> <h1 class="title-container"><a href="https://satoshun.github.io">stsnブログ</a></h1> <h3>Android, Kotlin, Python, Go, Developer</h3> <a class="social-icon" href="https://twitter.com/stsn_jp" title="Follow on Twitter" target="_blank"><i class="icon icon-twitter"></i></a> <a class="social-icon" href="https://github.com/satoshun" title="Follow on Github" target="_blank"><i class="icon icon-github"></i></a> <a class="social-icon" href="/index.xml" title="RSS Feed"> <i class="icon icon-rss"></i> </a> <div class="mb15"></div> </div> </section> </div> <div class="content container"> <h1 class="title">room</h1> <ul class="posts tag-list"> <li class="tag-list-item"> <a href="https://satoshun.github.io/2019/01/room-with-flux/">FluxのDispatcherをRoomのin memoryで実装するのは、冗長なコードが多くなるので良くない</a> <time class="tag-list-item-time">Thu, Jan 24, 2019</time> </li> <li class="tag-list-item"> <a href="https://satoshun.github.io/2017/11/jetpack-room-invalidationtracker/">Android: Roomにおけるデータ変更通知の仕組みについて(InvalidationTracker)</a> <time class="tag-list-item-time">Sun, Nov 26, 2017</time> </li> </ul> </div> </body> </html>
{ "content_hash": "4c977ffff7b5481ec6953f53c6cccf94", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 144, "avg_line_length": 34.24576271186441, "alnum_prop": 0.6483543677307597, "repo_name": "satoshun/satoshun.github.io", "id": "ace5c3c0b3d62acf884aada52b205a0222a71e73", "size": "4159", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "tags/room/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "174264" }, { "name": "HTML", "bytes": "4179614" } ], "symlink_target": "" }
French Language ================
{ "content_hash": "0ee9b21d5c9d726025fcfcfa1c8850ae", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 16, "avg_line_length": 11.333333333333334, "alnum_prop": 0.4117647058823529, "repo_name": "h4labs/lang", "id": "bdecc422faaf0d32a36d40ecb5c14c048668d2a3", "size": "34", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "french/README.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package com.opengamma.analytics.financial.model.finitedifference; import static org.testng.AssertJUnit.assertEquals; import org.apache.commons.lang.Validate; import org.testng.annotations.Test; import com.opengamma.analytics.financial.model.option.pricing.fourier.FFTPricer; import com.opengamma.analytics.financial.model.option.pricing.fourier.HestonCharacteristicExponent; import com.opengamma.analytics.financial.model.option.pricing.fourier.MartingaleCharacteristicExponent; import com.opengamma.analytics.math.cube.Cube; import com.opengamma.analytics.math.cube.FunctionalDoublesCube; import com.opengamma.analytics.math.function.Function; import com.opengamma.analytics.math.interpolation.Interpolator1D; import com.opengamma.analytics.math.interpolation.data.Interpolator1DDataBundle; import com.opengamma.analytics.math.interpolation.factory.NamedInterpolator1dFactory; import com.opengamma.analytics.math.surface.FunctionalDoublesSurface; import com.opengamma.util.test.TestGroup; /** * @deprecated This class tests deprecated functionality */ @Deprecated @Test(groups = TestGroup.UNIT) public class HestonPDETestCase { private static BoundaryCondition2D F_LOWER; private static BoundaryCondition2D F_UPPER; private static BoundaryCondition2D V_LOWER; private static BoundaryCondition2D V_UPPER; private static final double F0 = 0.05; private static final double V0 = 0.01; private static final double KAPPA = 0.2;// changed from 0.2 private static final double THETA = 0.07; private static final double OMEGA = 0.2; private static final double RHO = -0.50;// changed from -0.5 private static final double STRIKE = 0.06; private static final double T = 1.0; private static final double RATE = 0.0; // private static final ZonedDateTime DATE = DateUtil.getUTCDate(2010, 7, 1); // private static final OptionDefinition OPTION; private static final ConvectionDiffusion2DPDEDataBundle DATA; private static Cube<Double, Double, Double, Double> A; private static Cube<Double, Double, Double, Double> B; private static Cube<Double, Double, Double, Double> C; private static Cube<Double, Double, Double, Double> D; private static Cube<Double, Double, Double, Double> E; private static Cube<Double, Double, Double, Double> F; static { // final Function<Double, Double> volZeroBoundary = new Function<Double, Double>() { // @Override // public Double evaluate(final Double... tx) { // Validate.isTrue(tx.length == 2); // double x = tx[1]; // return Math.max(x - STRIKE, 0); // } // }; // // final Function<Double, Double> volInfiniteBoundary = new Function<Double, Double>() { // @Override // public Double evaluate(final Double... tx) { // Validate.isTrue(tx.length == 2); // double x = tx[1]; // return x; // } // }; F_LOWER = new DirichletBoundaryCondition2D(0.0, 0.0); // option worth zero if spot is zero F_UPPER = new SecondDerivativeBoundaryCondition2D(0.0, 5 * F0); // option price linear in spot for spot -> infinity V_LOWER = new SecondDerivativeBoundaryCondition2D(0.0, 0.0); V_UPPER = new SecondDerivativeBoundaryCondition2D(0.0, 5 * V0); // F_UPPER = new DirichletBoundaryCondition2D(0.0, 5 * F0); // a knock-out barrier // V_LOWER = new DirichletBoundaryCondition2D(0.0, 0.0); // V_UPPER = new DirichletBoundaryCondition2D(0.0, 5 * V0); // TODO these more sophisticated boundary conditions don't work // V_LOWER = new DirichletBoundaryCondition2D(FunctionalDoublesSurface.from(volZeroBoundary), 0); // TODO should be solving the // convection PDE on this boundary // V_UPPER = new DirichletBoundaryCondition2D(FunctionalDoublesSurface.from(volInfiniteBoundary), 5 * V0); // option the same as // underlying for vol -> infinity final Function<Double, Double> a = txy -> { Validate.isTrue(txy.length == 3); final double x = txy[1]; final double y = txy[2]; return -0.5 * x * x * y; }; A = FunctionalDoublesCube.from(a); final Function<Double, Double> b = txy -> { Validate.isTrue(txy.length == 3); final double x = txy[1]; return -x * RATE; }; B = FunctionalDoublesCube.from(b); final Function<Double, Double> c = txy -> { Validate.isTrue(txy.length == 3); return RATE; }; C = FunctionalDoublesCube.from(c); final Function<Double, Double> d = txy -> { Validate.isTrue(txy.length == 3); final double y = txy[2]; return -0.5 * OMEGA * OMEGA * y; }; D = FunctionalDoublesCube.from(d); final Function<Double, Double> e = txy -> { Validate.isTrue(txy.length == 3); final double x = txy[1]; final double y = txy[2]; return -x * y * OMEGA * RHO; }; E = FunctionalDoublesCube.from(e); final Function<Double, Double> f = txy -> { Validate.isTrue(txy.length == 3); final double y = txy[2]; return -KAPPA * (THETA - y); }; F = FunctionalDoublesCube.from(f); final Function<Double, Double> payoff = xy -> { Validate.isTrue(xy.length == 2); final double x = xy[0]; return Math.max(x - STRIKE, 0); }; DATA = new ConvectionDiffusion2DPDEDataBundle(A, B, C, D, E, F, FunctionalDoublesSurface.from(payoff)); } static void testCallPrice(final ConvectionDiffusionPDESolver2D solver, final int timeSteps, final int spotSteps, final int volSqrSteps, final boolean print) { final double deltaX = (F_UPPER.getLevel() - F_LOWER.getLevel()) / spotSteps; final double deltaY = (V_UPPER.getLevel() - V_LOWER.getLevel()) / volSqrSteps; final double[][] res = solver.solve(DATA, timeSteps, spotSteps, volSqrSteps, T, F_LOWER, F_UPPER, V_LOWER, V_UPPER); if (print) { final int xSteps = res.length - 1; final int ySteps = res[0].length - 1; for (int j = 0; j <= ySteps; j++) { System.out.print("\t" + (V_LOWER.getLevel() + j * deltaY)); } System.out.print("\n"); for (int i = 0; i <= xSteps; i++) { System.out.print(F_LOWER.getLevel() + i * deltaX); for (int j = 0; j <= ySteps; j++) { System.out.print("\t" + res[i][j]); } System.out.print("\n"); } } // TODO There is no guarantee that F0 and V0 are grid points (it depends on the chosen step sizes), so we should do a surface // interpolation (what fun!) final double pdfPrice = res[(int) (F0 / deltaX)][(int) (V0 / deltaY)]; // System.out.print("\n"); final FFTPricer pricer = new FFTPricer(); final MartingaleCharacteristicExponent heston = new HestonCharacteristicExponent(KAPPA, THETA, V0, OMEGA, RHO); final int n = 51; final double alpha = -0.5; final double tol = 1e-12; final double[][] strikeNprice = pricer.price(F0, 1.0, T, true, heston, STRIKE / 2, STRIKE * 2, n, 0.2, alpha, tol); final int nStrikes = strikeNprice.length; final double[] k = new double[nStrikes]; final double[] price = new double[nStrikes]; for (int i = 0; i < nStrikes; i++) { k[i] = strikeNprice[i][0]; price[i] = strikeNprice[i][1]; } final Interpolator1D interpolator = NamedInterpolator1dFactory.of("DoubleQuadratic"); final Interpolator1DDataBundle dataBundle = interpolator.getDataBundleFromSortedArrays(k, price); final double fftPrice = interpolator.interpolate(dataBundle, STRIKE); // System.out.println(fftPrice + "\t" + pdfPrice); assertEquals(fftPrice, pdfPrice, 2e-6); // for (int i = 0; i < strikeNprice.length; i++) { // System.out.println(strikeNprice[i][0] + "\t" + strikeNprice[i][1]); // } } }
{ "content_hash": "f83dd60ec3ce734e9fc6e82b962dd0f8", "timestamp": "", "source": "github", "line_count": 203, "max_line_length": 137, "avg_line_length": 37.80788177339902, "alnum_prop": 0.673485342019544, "repo_name": "McLeodMoores/starling", "id": "b0dece8ba9f26d4878f572fcf5c0b29314cee2e9", "size": "7812", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "projects/analytics/src/test/java/com/opengamma/analytics/financial/model/finitedifference/HestonPDETestCase.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2505" }, { "name": "CSS", "bytes": "213501" }, { "name": "FreeMarker", "bytes": "310184" }, { "name": "GAP", "bytes": "1490" }, { "name": "Groovy", "bytes": "11518" }, { "name": "HTML", "bytes": "318295" }, { "name": "Java", "bytes": "79541905" }, { "name": "JavaScript", "bytes": "1511230" }, { "name": "PLSQL", "bytes": "398" }, { "name": "PLpgSQL", "bytes": "26901" }, { "name": "Shell", "bytes": "11481" }, { "name": "TSQL", "bytes": "604117" } ], "symlink_target": "" }
This directory contains implementation of layout objects. It covers the following document lifecycle states: * LayoutSubtreeChange (`InLayoutSubtreeChange` and `LayoutSubtreeChangeClean`) * PreLayout (`InPreLayout`) * PerformLayout (`InPerformLayout`) * AfterPerformLayout (`AfterPerformLayout` and `LayoutClean`) Note that a new Blink layout system is under development. See the [LayoutNG design document](https://docs.google.com/document/d/1uxbDh4uONFQOiGuiumlJBLGgO4KDWB8ZEkp7Rd47fw4/preview). ## Overflow and scrolling When a LayoutBox has scrollable overflow, it is associated with a PaintLayerScrollableArea. PaintLayerScrollableArea uses a "scroll origin" to represent the location of the top/left corner of the content rect (the visible part of the content) in the coordinate system defined by the top/left corner of the overflow rect, when the box is scrolled all the way to the beginning of its content. For content which flows left-to-right and top-to-bottom, the scroll origin will be (0, 0), i.e., the top/left of the content rect is coincident with the top/left of the overflow rect when the box is scrolled all the way to the beginning of content. For content which flows right-to-left (including direction:ltr, writing-mode:vertical-rl, and flex-direction:row-reverse), the x-coordinate of the scroll origin will be positive; and for content which flows bottom-to-top (e.g., flex-direction:column-reverse and vertical writing-mode with direction:ltr), the y-coordinate of the scroll origin will be positive. In all cases, the term 'scrollOffset' (or just 'offset') is used to represent the distance of the scrolling viewport from its location when scrolled to the beginning of content, and it uses type ScrollOffset. The term 'scrollPosition' (or just 'position') represents a point in the coordinate space defined by the overflow rect, and it uses type FloatPoint. For illustrations of these concepts, see these files: doc/ltr-tb-scroll.png doc/rtl-bt-scroll.png doc/rtl-tb-scroll.png When computing the scroll origin, if the box is laid out right-to-left and it has a scrollbar for the orthogonal direction (e.g., a vertical scrollbar in a direction:rtl block), the size of the scrollbar must be added to the scroll origin calculation. Here are two examples -- note that it doesn't matter whether the vertical scrollbar is placed on the right or left of the box (the vertical scrollbar is the `|/|` part): content rect |<-------->| scroll origin |----------->| _______________________ | |/| | | |/| | | |/| | direction:rtl | |/| box | | |/| | | |/| | |__________|/|__________| overflow rect |<--------------------->| content rect |<-------->| scroll origin |----------->| _________________________ | | |/| | | |/| | | |/| writing-mode: | | box |/| vertical-rl | | |/| | | |/| |____________|__________|/| overflow rect |<--------------------->| ## Coordinate Spaces Layout and Paint work with and frequently refer to three main coordinate spaces (really two, with one variant): * Physical coordinates: Corresponds to physical direction of the output per the physical display (screen, printed page). Generally used for painting, thus layout logic that feeds into paint may produce values in this space. CSS properties such as `top`, `right`, `bottom`, and `left` are in this space. See also the 'flipped block-flow direction' variant space below. * Logical coordinates: Used in layout to allow for generalized positioning that fits with whatever the `writing-mode` and `direction` CSS property values may be. Properties named with `before`, `after`, `start` or `end` are in this space. These are also known respectively as 'logical top', 'logical bottom', 'logical left', and 'logical right'. * Physical coordinates with flipped block-flow direction: The same as 'physical coordinates', but for `writing-mode: vertical-rl` where blocks are laid out right-to-left, block position is "flipped" from the left to the right side of their containing block. This is essentially a mirror reflection horizontally across the center of a block's containing block. For `writing-mode` values other than `vertical-rl` there is no change from physical coordinates. Layout and paint logic reference this space to connote whether "flipping" has been applied to the values. Final painted output for "flipped block-flow" writing mode must, by definition, incorporate flipping. It can be expensive to look up the writing mode of an object. Performing computation on values known to be in this space can save on the overhead required to unflip/reflip. Example with `writing-mode: vertical-rl; direction: ltr`: 'top' / 'start' side block-flow direction <------------------------------------ | ------------------------------------- | | c | s | | 'left' | o | o | | inline 'right' / | n | m | | direction / 'after' | t | e | | 'before' side | e | | | side | n | | | | t | | | ------------------------------------- v 'bottom' / 'end' side Another example -- consider a relative-positioned element: <style> html { writing-mode: vertical-rl; } </style> <div id="container" style="background-color: lightBlue; width: 300px; height: 200px;"> <div id="relpos" style="position: relative; top: 50px; left: -60px; width: 70px; height: 80px; background-color: red;"></div> </div> The final location of these within an 800x600 frame is as: container: (492, 8 300x200) relpos: (662, 58 70x80) See the [diagram](resources/flipped-blocks-relpos.svg) for full detail on dimensions of the involved elements. Determining the paint invalidation rect for `relpos` via `mapToVisualRectInAncestorSpace()` involves walking up the layout tree from `relpos` flipping the rect within its container at each box. Below we sketch each step as we recurse toward the top of the document, with 'this' on the left, the current rect being mapped on the right, and explanation beneath each: LayoutBlockFlow (relative positioned) DIV id='relpos' 0,0 70x80 Apply the relative position of 'relpos' while flipping within 'container' to respect writing mode. 170 = 300 (container width) - 70 (relpos width) - 60 (relpos left) 50 = relpos top LayoutBlockFlow DIV id='container' 170,50 70x80 Since body has the same width as container, flipping has no effect on the rect in this step. LayoutBlockFlow BODY 170,50 70x80 Flip within the html block, which is symmetrically 8px larger than body due to default margin. LayoutBlockFlow HTML 178,58 70x80 Flip the rectangle within the view. 662 = 800 (view width) - 316 (html width) + 178 (current rect left) LayoutView #document 662,58 70x80 Since relative-positioned elements are positioned via physical coordinates, and flipping at each step mirrors the position based on the width of the containing box at that step, we can only compute the final physical pixels in screen space for a relative-positioned element if we walk up the full layout tree from the starting object to the topmost view as described above. For more examples of writing mode and direction combinations, see this [demo page](http://pauljadam.com/demos/csstext.html) though note `horizontal-bt` is obsolete. ### Flipped Block-Flow Coordinates The nature of "flipping" a value as a mirror reflection within its containing block is such that flipping twice with the same container will produce the original result. Thus when working on involved logic it can be easy to accidentally flip unnecessarily, since flipping (say) one too many times can be "corrected" by flipping again. This can obviously lead to confusing and less performant code, so care should be taken to understand and document any changes to flipping logic. Blink test coverage for features used in vertical writing modes, and `vertical-rl` in particular, may not be as comprehensive as for horizontal writing mode. Keep this in mind when writing new functionality or tests by making sure to incorporate coverage for all writing modes when appropriate. Values are generally transformed into flipped block-flow coordinates via a set of methods on the involved layout objects. See in particular `flipForWritingMode()`, `flipForWritingModeForChild()`, and `topLeftLocation()`. `InlineBox::flipForWritingMode()` variants flip the input value within the inline box's containing block. `LayoutBox::flipForWritingMode()` variants flip the input value within the referenced box. `LayoutBox::flipForWritingModeForChild()` variants flip the input value within the referenced box, offsetting for the specified child box's current x-position and width. This is useful for a common pattern wherein we build up a point location starting with the current location of the (child) box. `LayoutBox::topLeftLocation()` performs flipping as needed. If the containing block is not passed to the method, looking it up requires walking up the layout tree, which can be expensive. Note there are two primary similar, but slightly different, methods regarding finding the containing block for an element: * `LayoutObject::container()` returns the containing block for an element as defined by CSS. * `LayoutObject::containingBlock()` which returns the enclosing non-anonymous block for an element. If the containing block is a relatively positioned inline, it returns that inline's enclosing non-anonymous block. This is the one used by `topLeftLocation()`. There are other containing block methods in `LayoutObject` for special purposes such as fixed position, absolute position, and paint invalidation. Code will sometimes just refer to the 'containing' element, which is an unfortunately ambiguous term. Paying close attention to which method was used to obtain the containing element is important. More complex web platform features such as tables, flexbox, and multicol are typically implemented atop these primitives, along with checks such as `isFlippedBlocksWritingMode()`, `isLeftToRightDirection()`, and `isHorizontalWritingMode()`. See for example `LayoutTableSection::logicalRectForWritingModeAndDirection()`, `LayoutFlexibleBox::updateAutoMarginsInCrossAxis()` or `LayoutMultiColumnFlowThread::flowThreadTranslationAtPoint()`. ## Geometry mapping TODO(wkorman): Elaborate on: * `mapToVisualRectInAncestorSpace()` * `mapAncestorToLocal()` * `Widget` and `FrameView` trees. Note the former will be done away with at some point per http://crbug.com/637460. * `GeometryMapper` (or just point to its section in paint README). For now, see the [Web page geometries](https://docs.google.com/document/d/1WZKlOSUK4XI0Le0fgCsyUTVw0dTwutZXGWwzlHXewiU/preview) design document. ## Scrolling TODO(wkorman): Provide an overview of scrolling. For now, the BlinkOn talk on [Scrolling in Blink](https://docs.google.com/presentation/d/1pwx0qBW4wSmYAOJxq2gb3SMvSTCHz2L2TFx_bjsvm8E/preview) is a good overview. ## Glossaries Here we provide a brief overview of key terms relevant to box flow, inline flow, and text orientation. For more detail see [CSS Writing Modes Level 3](https://www.w3.org/TR/css-writing-modes-3/). The [CSS Logical Properties Level 1](https://drafts.csswg.org/css-logical-props/) specification represents the latest CSSWG thinking on logical coordinate space naming. CSSWG has standardized on `block-start`, `block-end`, `inline-start`, and `inline-end`, or just `start` and `end` when the axis is either implied or irrelevant. Note that much of the Blink code base predates the logical properties specification and so does not yet reference logical direction consistently in the stated manner, though we would like to head in that direction over time. See also the *physical*, *flow-relative*, and *line-relative* [abstract box terminology](https://www.w3.org/TR/css-writing-modes-3/#abstract-box) specification. * `writing-mode`: either horizontal or vertical, with vertical having either left-to-right or right-to-left block flow. Geometry is transposed for vertical writing mode. See calls to `transposed{Rect,Point,Size}()`. * `direction`/`dir`: "inline base direction" of a box. One of `ltr` or `rtl`. See calls to `isLeftToRightDirection()`. * `text-orientation`: orientation of text in a line. Only relevant for vertical modes. * orthogonal flow: when a box has a writing mode perpendicular to its containing block. This can lead to complex cases. See [specification](https://www.w3.org/TR/css-writing-modes-3/#orthogonal-flows) for more.
{ "content_hash": "b4b1ff884144e954de64af497d495042", "timestamp": "", "source": "github", "line_count": 303, "max_line_length": 131, "avg_line_length": 46.399339933993396, "alnum_prop": 0.6650544135429263, "repo_name": "Samsung/ChromiumGStreamerBackend", "id": "4cdf2f0b60212fb25e0e5e295d2d77a349df3093", "size": "14083", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "third_party/WebKit/Source/core/layout/README.md", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
@interface RSMainViewController : UIViewController @end
{ "content_hash": "73e70ff8c9b94405ed9683f98adcf4b2", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 50, "avg_line_length": 19, "alnum_prop": 0.8421052631578947, "repo_name": "vrao423/CustomDynamicTypeFont", "id": "c8c6cb60b634ae9e222690822f81d237e6347b8d", "size": "236", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TestProject/RSMainViewController.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "8684" } ], "symlink_target": "" }
package consent import ( "net/http" "github.com/ory/fosite" ) var _ Strategy = new(DefaultStrategy) type Strategy interface { HandleOAuth2AuthorizationRequest(w http.ResponseWriter, r *http.Request, req fosite.AuthorizeRequester) (*HandledConsentRequest, error) HandleOpenIDConnectLogout(w http.ResponseWriter, r *http.Request) (*LogoutResult, error) }
{ "content_hash": "057f80abe5bea489a5e97a5687b5516f", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 136, "avg_line_length": 22.6875, "alnum_prop": 0.7823691460055097, "repo_name": "ory-am/hydra", "id": "fa2f9eebfed53a984fff135cb4182846ea2b3516", "size": "1128", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "consent/strategy.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "322097" } ], "symlink_target": "" }
package coloring.commands; import org.terasology.codecity.world.map.MapObject; public class BuildInformation { private int x; private int y; private int z; private int height; private int width; private int[] lineLength; private MapObject info; public BuildInformation(int x,int y, int z, int height, int width, MapObject object){ this.x = x; this.y = y; this.z = z; this.height = height; this.info = object; this.width = width; this.lineLength = object.getObject().getLineLength(); } public int[] getLineLength() { return lineLength; } public int getX(){ return x; } public int getY(){ return y; } public int getZ(){ return z; } public String getName(){ return info.getObject().getBase().getName(); } public String getPath(){ return info.getObject().getBase().getPath(); } public int getHeight(){ return height; } public int getWidth(){ return width; } }
{ "content_hash": "31dbb5e780116319f58d253b497657db", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 86, "avg_line_length": 17.75, "alnum_prop": 0.6803900325027086, "repo_name": "CC4401-TeraCity/TeraCity", "id": "ee3bd1c472fc39f9d293cb03f7ac218c340646c5", "size": "923", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/Coloring/src/main/java/coloring/commands/BuildInformation.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3245" }, { "name": "GLSL", "bytes": "109450" }, { "name": "Groovy", "bytes": "1996" }, { "name": "Java", "bytes": "6228708" }, { "name": "Protocol Buffer", "bytes": "9493" }, { "name": "Shell", "bytes": "9748" } ], "symlink_target": "" }
from paasta_tools.autoscaling import cluster_boost from paasta_tools.cli.utils import execute_paasta_cluster_boost_on_remote_master from paasta_tools.cli.utils import lazy_choices_completer from paasta_tools.utils import DEFAULT_SOA_DIR from paasta_tools.utils import list_clusters from paasta_tools.utils import load_system_paasta_config from paasta_tools.utils import paasta_print def add_subparser(subparsers): boost_parser = subparsers.add_parser( 'boost', help="Set, print the status, or clear a capacity boost for a given region in a PaaSTA cluster", description=( "'paasta boost' is used to temporary provision more capacity in a given cluster " "It operates by ssh'ing to a Mesos master of a remote cluster, and " "interracting with the boost in the local zookeeper cluster. If you set or clear " "a boost, you may want to run the cluster autoscaler manually afterwards." ), epilog=( "The boost command may time out during heavy load. When that happens " "users may execute the ssh command directly, in order to bypass the timeout." ), ) boost_parser.add_argument( '-v', '--verbose', action='count', dest="verbose", default=0, help="""Print out more output regarding the state of the cluster. Multiple v options increase verbosity. Maximum is 3.""", ) boost_parser.add_argument( '-c', '--cluster', type=str, required=True, help="""Paasta cluster(s) to boost. This option can take comma separated values. If auto-completion doesn't work, you can get a list of cluster with `paasta list-clusters'""", ).completer = lazy_choices_completer(list_clusters) boost_parser.add_argument( '--soa-dir', dest="soa_dir", metavar="SOA_DIR", default=DEFAULT_SOA_DIR, help="define a different soa config directory", ) boost_parser.add_argument( '-p', '--pool', type=str, default='default', help="Name of the pool you want to increase the capacity. Default is 'default' pool.", ) boost_parser.add_argument( '-b', '--boost', type=float, default=cluster_boost.DEFAULT_BOOST_FACTOR, help="Boost factor to apply. Default is 1.5. A big failover should be 2, 3 is the max.", ) boost_parser.add_argument( '-d', '--duration', type=int, default=cluster_boost.DEFAULT_BOOST_DURATION, help="Duration of the capacity boost in minutes. Default is 40", ) boost_parser.add_argument( '-f', '--force', action='store_true', dest='override', help="Replace an existing boost. Default is false", ) boost_parser.add_argument( 'action', choices=[ 'set', 'status', 'clear', ], help="You can view the status, set or clear a boost.", ) boost_parser.set_defaults(command=paasta_boost) def paasta_boost(args): soa_dir = args.soa_dir system_paasta_config = load_system_paasta_config() all_clusters = list_clusters(soa_dir=soa_dir) clusters = args.cluster.split(',') for cluster in clusters: if cluster not in all_clusters: paasta_print( "Error: {} doesn't look like a valid cluster. ".format(cluster) + "Here is a list of valid paasta clusters:\n" + "\n".join(all_clusters), ) return 1 return_code, output = execute_paasta_cluster_boost_on_remote_master( clusters=clusters, system_paasta_config=system_paasta_config, action=args.action, pool=args.pool, duration=args.duration if args.action == 'set' else None, override=args.override if args.action == 'set' else None, boost=args.boost if args.action == 'set' else None, verbose=args.verbose, ) paasta_print(output) return return_code
{ "content_hash": "de6f0b25a7d3656b688b9054e91eb8e8", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 103, "avg_line_length": 37.822429906542055, "alnum_prop": 0.6209537929330368, "repo_name": "somic/paasta", "id": "3d51c2fbbd2dbb713de05e33044727eabf9105e4", "size": "4647", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "paasta_tools/cli/cmds/boost.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Gherkin", "bytes": "71885" }, { "name": "Makefile", "bytes": "6598" }, { "name": "Python", "bytes": "3231060" }, { "name": "Shell", "bytes": "16324" } ], "symlink_target": "" }
<!DOCTYPE html> <!-- | Generated by Apache Maven Doxia Site Renderer 1.8.1 at 2018-11-14 | Rendered using Apache Maven Fluido Skin 1.6 --> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="Date-Revision-yyyymmdd" content="20181114" /> <meta http-equiv="Content-Language" content="en" /> <title>Play! 2.x &#x2013; Migration from previous plugin version</title> <link rel="stylesheet" href="./css/apache-maven-fluido-1.6.min.css" /> <link rel="stylesheet" href="./css/site.css" /> <link rel="stylesheet" href="./css/print.css" media="print" /> <script type="text/javascript" src="./js/apache-maven-fluido-1.6.min.js"></script> <link rel="stylesheet" href="./css/site.css" type="text/css" /> <!-- Google Analytics --> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-17472708-2']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </head> <body class="topBarDisabled"> <div class="container-fluid"> <div id="banner"> <div class="pull-left"><div id="bannerLeft"><h2>Play! 2.x</h2> </div> </div> <div class="pull-right"><div id="bannerRight"><img src="images/my-avatar-80.png" alt="avatar"/></div> </div> <div class="clear"><hr/></div> </div> <div id="breadcrumbs"> <ul class="breadcrumb"> <li id="publishDate">Last Published: 2018-11-14<span class="divider">|</span> </li> <li id="projectVersion">Version: 1.0.0-rc4</li> </ul> </div> <div class="row-fluid"> <div id="leftColumn" class="span3"> <div class="well sidebar-nav"> <ul class="nav nav-list"> <li class="nav-header">Overview</li> <li><a href="index.html" title="Introduction"><span class="none"></span>Introduction</a> </li> <li><a href="play2-maven-plugin/plugin-info.html" title="Plugin goals"><span class="none"></span>Plugin goals</a> </li> <li class="nav-header">Usage</li> <li><a href="usage.html" title="General instructions"><span class="none"></span>General instructions</a> </li> <li><a href="usage-play26.html" title="Play 2.6.x"><span class="none"></span>Play 2.6.x</a> </li> <li><a href="usage-play25.html" title="Play 2.5.x"><span class="none"></span>Play 2.5.x</a> </li> <li><a href="usage-play24.html" title="Play 2.4.x"><span class="none"></span>Play 2.4.x</a> </li> <li><a href="usage-play23.html" title="Play 2.3.x"><span class="none"></span>Play 2.3.x</a> </li> <li><a href="usage-play22.html" title="Play 2.2.x"><span class="none"></span>Play 2.2.x</a> </li> <li><a href="usage-play21.html" title="Play 2.1.x"><span class="none"></span>Play 2.1.x</a> </li> <li class="nav-header">Migration</li> <li class="active"><a href="#"><span class="none"></span>From previous plugin version</a> </li> <li><a href="migration-play26.html" title="From Play 2.5.x to 2.6.x"><span class="none"></span>From Play 2.5.x to 2.6.x</a> </li> <li><a href="migration-play25.html" title="From Play 2.4.x to 2.5.x"><span class="none"></span>From Play 2.4.x to 2.5.x</a> </li> <li><a href="migration-play24.html" title="From Play 2.3.x to 2.4.x"><span class="none"></span>From Play 2.3.x to 2.4.x</a> </li> <li><a href="migration-play23.html" title="From Play 2.2.x to 2.3.x"><span class="none"></span>From Play 2.2.x to 2.3.x</a> </li> <li><a href="migration-play22.html" title="From Play 2.1.x to 2.2.x"><span class="none"></span>From Play 2.1.x to 2.2.x</a> </li> <li class="nav-header">IDE integration</li> <li><a href="ide-integration-eclipse.html" title="Eclipse/ScalaIDE"><span class="none"></span>Eclipse/ScalaIDE</a> </li> <li><a href="ide-integration-idea.html" title="IntelliJ IDEA"><span class="none"></span>IntelliJ IDEA</a> </li> <li class="nav-header">Deploying</li> <li><a href="default-distribution.html" title="Default distribution"><span class="none"></span>Default distribution</a> </li> <li><a href="custom-distribution.html" title="Custom distribution"><span class="none"></span>Custom distribution</a> </li> <li><a href="war-packaging.html" title="WAR distribution"><span class="none"></span>WAR distribution</a> </li> <li class="nav-header">Other topics</li> <li><a href="assets.html" title="Assets processing"><span class="none"></span>Assets processing</a> </li> <li><a href="running.html" title="Running in development mode"><span class="none"></span>Running in development mode</a> </li> <li><a href="multi-module-builds.html" title="Multi-module builds"><span class="none"></span>Multi-module builds</a> </li> <li class="nav-header">Modules</li> <li><a href="play2-maven-plugin/index.html" title="Play! 2.x Maven Plugin"><span class="none"></span>Play! 2.x Maven Plugin</a> </li> <li><a href="play2-provider-api/index.html" title="Play! 2.x Provider API"><span class="none"></span>Play! 2.x Provider API</a> </li> <li><a href="play2-providers/index.html" title="Play! 2.x Providers"><span class="none"></span>Play! 2.x Providers</a> </li> <li><a href="play2-source-position-mappers/index.html" title="Play! 2.x Source Position Mappers"><span class="none"></span>Play! 2.x Source Position Mappers</a> </li> <li><a href="play2-source-watcher-api/index.html" title="Play! 2.x Source Watcher API"><span class="none"></span>Play! 2.x Source Watcher API</a> </li> <li><a href="play2-source-watchers/index.html" title="Play! 2.x Source Watchers"><span class="none"></span>Play! 2.x Source Watchers</a> </li> <li class="nav-header">Project Documentation</li> <li><a href="project-info.html" title="Project Information"><span class="icon-chevron-right"></span>Project Information</a> </li> </ul> <hr /> <div id="poweredBy"> <div class="clear"></div> <div class="clear"></div> <div class="clear"></div> <div class="clear"></div> <a href="http://maven.apache.org/" title="Built by Maven" class="poweredBy"><img class="builtBy" alt="Built by Maven" src="./images/logos/maven-feather.png" /></a> </div> </div> </div> <div id="bodyColumn" class="span9" > <div class="section"> <h2><a name="Migration_from_previous_plugin_version"></a>Migration from previous plugin version</h2> <p>Change plugin versions from</p> <div> <div> <pre class="source"> &lt;properties&gt; ... &lt;play2.plugin.version&gt;1.0.0-beta7&lt;/play2.plugin.version&gt; &lt;sbt-compiler.plugin.version&gt;1.0.0-rc1&lt;/sbt-compiler.plugin.version&gt; &lt;/properties&gt; </pre></div></div> <p>to</p> <div> <div> <pre class="source"> &lt;properties&gt; ... &lt;play2.plugin.version&gt;1.0.0-rc4&lt;/play2.plugin.version&gt; &lt;sbt-compiler.plugin.version&gt;1.0.0&lt;/sbt-compiler.plugin.version&gt; &lt;/properties&gt; </pre></div></div></div> </div> </div> </div> <hr/> <footer> <div class="container-fluid"> <div class="row-fluid"> <p>Copyright &copy;2013&#x2013;2018. All rights reserved.</p> </div> </div> </footer> </body> </html>
{ "content_hash": "cd62ca232bdf728ff74e83c82320c5a6", "timestamp": "", "source": "github", "line_count": 139, "max_line_length": 171, "avg_line_length": 55.906474820143885, "alnum_prop": 0.6140779822416678, "repo_name": "play2-maven-plugin/play2-maven-plugin.github.io", "id": "e4ad98c46c4edffdd6ceb1f78d96ad997f4b7d3d", "size": "7771", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "play2-maven-plugin/1.0.0-rc4/migration-plugin.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2793124" }, { "name": "HTML", "bytes": "178221432" }, { "name": "JavaScript", "bytes": "120742" } ], "symlink_target": "" }
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { emberModalDialog: { modalRootElementId: 'materialize-modal-root-element' } // Here you can pass flags/options to your application instance // when it is created }, sassOptions: { includePaths: ['bower_components/materialize/sass'] } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.baseURL = '/ember-cli-materialize'; ENV.locationType = 'hash'; } ENV.contentSecurityPolicy = { 'default-src': "'unsafe-inline'", 'script-src': "'self' 'unsafe-eval' 'unsafe-inline'", 'style-src': "'self' 'unsafe-inline'", 'connect-src': "'self' ", 'img-src': "'self'", 'media-src': "'self'" }; return ENV; };
{ "content_hash": "deb87760e7a416e985577e0d06a66bd1", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 77, "avg_line_length": 25.11111111111111, "alnum_prop": 0.5935524652338812, "repo_name": "basz/ember-cli-materialize", "id": "f6a270f6243e4f720cf3e7f81c9ea7d12c729859", "size": "1582", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "tests/dummy/config/environment.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3316" }, { "name": "HTML", "bytes": "1732" }, { "name": "Handlebars", "bytes": "52123" }, { "name": "JavaScript", "bytes": "135677" }, { "name": "Shell", "bytes": "302" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.tsa.vector_ar.var_model.VARResults.cov_ybar &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/stylesheets/deprecation.css"> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="../_static/material.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/doctools.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.tsa.vector_ar.var_model.VARResults.fevd" href="statsmodels.tsa.vector_ar.var_model.VARResults.fevd.html" /> <link rel="prev" title="statsmodels.tsa.vector_ar.var_model.VARResults.cov_params" href="statsmodels.tsa.vector_ar.var_model.VARResults.cov_params.html" /> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.tsa.vector_ar.var_model.VARResults.cov_ybar" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels v0.12.2</span> <span class="md-header-nav__topic"> statsmodels.tsa.vector_ar.var_model.VARResults.cov_ybar </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="GET" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../_static/versions.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../vector_ar.html" class="md-tabs__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a></li> <li class="md-tabs__item"><a href="statsmodels.tsa.vector_ar.var_model.VARResults.html" class="md-tabs__link">statsmodels.tsa.vector_ar.var_model.VARResults</a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels v0.12.2</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../tsa.html" class="md-nav__link">Time Series analysis <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa</span></code></a> </li> <li class="md-nav__item"> <a href="../statespace.html" class="md-nav__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a> </li> <li class="md-nav__item"> <a href="../vector_ar.html" class="md-nav__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.tsa.vector_ar.var_model.VARResults.cov_ybar.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <h1 id="generated-statsmodels-tsa-vector-ar-var-model-varresults-cov-ybar--page-root">statsmodels.tsa.vector_ar.var_model.VARResults.cov_ybar<a class="headerlink" href="#generated-statsmodels-tsa-vector-ar-var-model-varresults-cov-ybar--page-root" title="Permalink to this headline">¶</a></h1> <dl class="py method"> <dt id="statsmodels.tsa.vector_ar.var_model.VARResults.cov_ybar"> <code class="sig-prename descclassname">VARResults.</code><code class="sig-name descname">cov_ybar</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults.cov_ybar"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#statsmodels.tsa.vector_ar.var_model.VARResults.cov_ybar" title="Permalink to this definition">¶</a></dt> <dd><p>Asymptotically consistent estimate of covariance of the sample mean</p> <div class="math notranslate nohighlight"> \[ \begin{align}\begin{aligned}\begin{split}\sqrt(T) (\bar{y} - \mu) \rightarrow {\cal N}(0, \Sigma_{\bar{y}})\\\end{split}\\\Sigma_{\bar{y}} = B \Sigma_u B^\prime, \text{where } B = (I_K - A_1 - \cdots - A_p)^{-1}\end{aligned}\end{align} \]</div> <p class="rubric">Notes</p> <p>Lütkepohl Proposition 3.3</p> </dd></dl> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.tsa.vector_ar.var_model.VARResults.cov_params.html" title="statsmodels.tsa.vector_ar.var_model.VARResults.cov_params" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.tsa.vector_ar.var_model.VARResults.cov_params </span> </div> </a> <a href="statsmodels.tsa.vector_ar.var_model.VARResults.fevd.html" title="statsmodels.tsa.vector_ar.var_model.VARResults.fevd" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.tsa.vector_ar.var_model.VARResults.fevd </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Feb 02, 2021. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 3.4.3. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
{ "content_hash": "820d5bcad540285b01092e3cca97cf2c", "timestamp": "", "source": "github", "line_count": 453, "max_line_length": 999, "avg_line_length": 40.437086092715234, "alnum_prop": 0.6018670160497871, "repo_name": "statsmodels/statsmodels.github.io", "id": "8099991e2570d6b5e059e041f9687fd352ae8203", "size": "18323", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "v0.12.2/generated/statsmodels.tsa.vector_ar.var_model.VARResults.cov_ybar.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package com.amazonaws.services.ec2.model; import java.io.Serializable; /** * <p> * Describes the status of a volume. * </p> */ public class VolumeStatusInfo implements Serializable, Cloneable { /** * <p> * The status of the volume. * </p> */ private String status; /** * <p> * The details of the volume status. * </p> */ private com.amazonaws.internal.SdkInternalList<VolumeStatusDetails> details; /** * <p> * The status of the volume. * </p> * * @param status * The status of the volume. * @see VolumeStatusInfoStatus */ public void setStatus(String status) { this.status = status; } /** * <p> * The status of the volume. * </p> * * @return The status of the volume. * @see VolumeStatusInfoStatus */ public String getStatus() { return this.status; } /** * <p> * The status of the volume. * </p> * * @param status * The status of the volume. * @return Returns a reference to this object so that method calls can be * chained together. * @see VolumeStatusInfoStatus */ public VolumeStatusInfo withStatus(String status) { setStatus(status); return this; } /** * <p> * The status of the volume. * </p> * * @param status * The status of the volume. * @return Returns a reference to this object so that method calls can be * chained together. * @see VolumeStatusInfoStatus */ public void setStatus(VolumeStatusInfoStatus status) { this.status = status.toString(); } /** * <p> * The status of the volume. * </p> * * @param status * The status of the volume. * @return Returns a reference to this object so that method calls can be * chained together. * @see VolumeStatusInfoStatus */ public VolumeStatusInfo withStatus(VolumeStatusInfoStatus status) { setStatus(status); return this; } /** * <p> * The details of the volume status. * </p> * * @return The details of the volume status. */ public java.util.List<VolumeStatusDetails> getDetails() { if (details == null) { details = new com.amazonaws.internal.SdkInternalList<VolumeStatusDetails>(); } return details; } /** * <p> * The details of the volume status. * </p> * * @param details * The details of the volume status. */ public void setDetails(java.util.Collection<VolumeStatusDetails> details) { if (details == null) { this.details = null; return; } this.details = new com.amazonaws.internal.SdkInternalList<VolumeStatusDetails>( details); } /** * <p> * The details of the volume status. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if * any). Use {@link #setDetails(java.util.Collection)} or * {@link #withDetails(java.util.Collection)} if you want to override the * existing values. * </p> * * @param details * The details of the volume status. * @return Returns a reference to this object so that method calls can be * chained together. */ public VolumeStatusInfo withDetails(VolumeStatusDetails... details) { if (this.details == null) { setDetails(new com.amazonaws.internal.SdkInternalList<VolumeStatusDetails>( details.length)); } for (VolumeStatusDetails ele : details) { this.details.add(ele); } return this; } /** * <p> * The details of the volume status. * </p> * * @param details * The details of the volume status. * @return Returns a reference to this object so that method calls can be * chained together. */ public VolumeStatusInfo withDetails( java.util.Collection<VolumeStatusDetails> details) { setDetails(details); return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getStatus() != null) sb.append("Status: " + getStatus() + ","); if (getDetails() != null) sb.append("Details: " + getDetails()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof VolumeStatusInfo == false) return false; VolumeStatusInfo other = (VolumeStatusInfo) obj; if (other.getStatus() == null ^ this.getStatus() == null) return false; if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false) return false; if (other.getDetails() == null ^ this.getDetails() == null) return false; if (other.getDetails() != null && other.getDetails().equals(this.getDetails()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode()); hashCode = prime * hashCode + ((getDetails() == null) ? 0 : getDetails().hashCode()); return hashCode; } @Override public VolumeStatusInfo clone() { try { return (VolumeStatusInfo) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
{ "content_hash": "158280bc353450fef7aac201efbf822f", "timestamp": "", "source": "github", "line_count": 248, "max_line_length": 88, "avg_line_length": 25.72983870967742, "alnum_prop": 0.5453690644099671, "repo_name": "dump247/aws-sdk-java", "id": "140d48e1457397a6511ad4a40776ad0f1e2c0f8d", "size": "6968", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/VolumeStatusInfo.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "117958" }, { "name": "Java", "bytes": "104374753" }, { "name": "Scilab", "bytes": "3375" } ], "symlink_target": "" }
namespace yocto { #define YOCTO_JSON_SAX 1 using njson = nlohmann::ordered_json; // load/save json bool load_json(const string& filename, njson& json, string& error) { // error helpers auto parse_error = [filename, &error]() { error = filename + ": parse error in json"; return false; }; auto text = ""s; if (!load_text(filename, text, error)) return false; try { json = njson::parse(text); return true; } catch (std::exception&) { return parse_error(); } } bool save_json(const string& filename, const njson& json, string& error) { return save_text(filename, json.dump(2), error); } // convert json void to_json(json_value& json, const njson& njs) { switch (njs.type()) { case njson::value_t::null: json = json_value{}; break; case njson::value_t::number_integer: json = (int64_t)njs; break; case njson::value_t::number_unsigned: json = (uint64_t)njs; break; case njson::value_t::number_float: json = (double)njs; break; case njson::value_t::boolean: json = (bool)njs; break; case njson::value_t::string: json = (string)njs; break; case njson::value_t::array: json = json_array(); for (auto& ejs : njs) to_json(json.emplace_back(), ejs); break; case njson::value_t::object: json = json_object(); for (auto& [key, ejs] : njs.items()) to_json(json[key], ejs); break; case njson::value_t::binary: json = json_binary(); json.get_ref<json_binary>() = njs.get_binary(); break; case njson::value_t::discarded: json = json_value{}; break; } } // convert json void from_json(const json_value& json, njson& njs) { switch (json.type()) { case json_type::null: njs = {}; break; case json_type::ninteger: njs = json.get_ref<int64_t>(); break; case json_type::nunsigned: njs = json.get_ref<uint64_t>(); break; case json_type::nfloat: njs = json.get_ref<double>(); break; case json_type::boolean: njs = json.get_ref<bool>(); break; case json_type::string: njs = json.get_ref<string>(); break; case json_type::array: njs = njson::array(); for (auto& ejs : json) from_json(ejs, njs.emplace_back()); break; case json_type::object: njs = njson::object(); for (auto& [key, ejs] : json.items()) from_json(ejs, njs[key]); break; case json_type::binary: njs = njson::binary({}); njs.get_binary() = json.get_ref<json_binary>(); break; } } #if YOCTO_JSON_SAX == 1 // load json bool load_json(const string& filename, json_value& json, string& error) { // error helpers auto parse_error = [filename, &error]() { error = filename + ": parse error in json"; return false; }; // sax handler struct sax_handler { // stack yocto::json_value* root = nullptr; std::vector<yocto::json_value*> stack = {}; std::string current_key; explicit sax_handler(yocto::json_value* root_) { *root_ = yocto::json_value{}; root = root_; stack.push_back(root); } // get current value yocto::json_value& next_value() { if (stack.size() == 1) return *root; if (stack.back()->is_array()) return (*stack.back()).emplace_back(); if (stack.back()->is_object()) return (*stack.back())[current_key]; throw yocto::json_error{"bad json type"}; } // values bool null() { next_value() = yocto::json_value{}; return true; } bool boolean(bool value) { next_value() = value; return true; } bool number_integer(int64_t value) { next_value() = value; return true; } bool number_unsigned(uint64_t value) { next_value() = value; return true; } bool number_float(double value, const std::string&) { next_value() = value; return true; } bool string(std::string& value) { next_value() = value; return true; } bool binary(std::vector<uint8_t>& value) { next_value() = value; return true; } // objects bool start_object(size_t elements) { next_value() = yocto::json_object{}; stack.push_back(&next_value()); return true; } bool end_object() { stack.pop_back(); return true; } bool key(std::string& value) { current_key = value; return true; } // arrays bool start_array(size_t elements) { next_value() = yocto::json_array{}; stack.push_back(&next_value()); return true; } bool end_array() { stack.pop_back(); return true; } bool parse_error(size_t position, const std::string& last_token, const nlohmann::detail::exception&) { return false; } }; // set up parsing json = json_value{}; auto handler = sax_handler{&json}; // load text auto text = ""s; if (!load_text(filename, text, error)) return false; // parse json if (!njson::sax_parse(text, &handler)) return parse_error(); return true; } #else // load json bool load_json(const string& filename, json_value& json, string& error) { // parse json auto njs = njson{}; if (!load_json(filename, njs, error)) return false; // convert to_json(json, njs); return true; } #endif // save json bool save_json(const string& filename, const json_value& json, string& error) { // convert auto njs = njson{}; from_json(json, njs); // save return save_json(filename, njs, error); } // Formats a Json to string bool format_json(string& text, const json_value& json, string& error) { // convert auto njs = njson{}; from_json(json, njs); // save text = njs.dump(2); return true; } string format_json(const json_value& json) { auto text = string{}; auto error = string{}; if (!format_json(text, json, error)) return ""; return text; } } // namespace yocto // ----------------------------------------------------------------------------- // IMPLEMENTATION OF JSON VALIDATION // ----------------------------------------------------------------------------- namespace yocto { // Validate a value against a schema static bool validate_json(const json_value& value, const string& path, const json_value& schema, vector<string>& errors, size_t max_error) { // error handling auto emit_error = [&errors, max_error, &path](const string& message) { errors.push_back(message + (path.empty() ? ""s : ("at " + path))); return errors.size() >= max_error; }; // early exit if (schema.is_boolean() && schema.get<bool>()) return true; if (schema.is_object() && schema.empty()) return true; // validate type if (schema.contains("type") && schema.at("type").is_string()) { auto& type = schema.at("type").get_ref<string>(); auto type_ok = (type == "null" && value.is_null()) || (type == "integer" && value.is_integer()) || (type == "number" && value.is_number()) || (type == "boolean" && value.is_boolean()) || (type == "string" && value.is_string()) || (type == "array" && value.is_array()) || (type == "object" && value.is_object()); if (!type_ok) { if (!emit_error(type + " expected")) return false; } } if (schema.contains("type") && schema.at("type").is_array()) { auto type_ok = false; for (auto& tschema : schema) { if (type_ok) break; auto& type = tschema.get_ref<string>(); type_ok = (type == "null" && value.is_null()) || (type == "integer" && value.is_integer()) || (type == "number" && value.is_number()) || (type == "boolean" && value.is_boolean()) || (type == "string" && value.is_string()) || (type == "array" && value.is_array()) || (type == "object" && value.is_object()); } if (!type_ok) { auto types = ""s; for (auto& tschema : schema) types += (types.empty() ? "" : " or") + tschema.get_ref<string>(); if (!emit_error(types + " expected")) return false; } } // check range // TODO(fabio): fix number precision if (schema.contains("minimum") && value.is_number()) { if (schema.at("minimum").get<double>() > value.get<double>()) { if (!emit_error("value out of range")) return false; } } if (schema.contains("maximum") && value.is_number()) { if (schema.at("maximum").get<double>() > value.get<double>()) { if (!emit_error("value out of range")) return false; } } if (schema.contains("exclusiveMinimum") && value.is_number()) { if (schema.at("exclusiveMinimum").get<double>() >= value.get<double>()) { if (!emit_error("value out of range")) return false; } } if (schema.contains("exclusiveMaximum") && value.is_number()) { if (schema.at("exclusiveMaximum").get<double>() <= value.get<double>()) { if (!emit_error("value out of range")) return false; } } // enum checks if (schema.contains("enum") && schema.at("enum").is_array()) { auto found = false; for (auto& item : schema.at("enum")) { if (found) break; if (item.is_string() && value.is_string() && item.get_ref<string>() == value.get_ref<string>()) found = true; if (item.is_integer() && value.is_integer() && item.get<int64_t>() == value.get<int64_t>()) found = true; if (item.is_number() && value.is_number() && item.get<double>() == value.get<double>()) found = true; } if (!found) { if (!emit_error("invalid enum")) return false; } } // size checks if (schema.contains("minLength") && value.is_string()) { if (schema.at("minLength").get<size_t>() > value.get_ref<string>().size()) { if (!emit_error("size out of range")) return false; } } if (schema.contains("maxLength") && value.is_string()) { if (schema.at("maxLength").get<size_t>() < value.get_ref<string>().size()) { if (!emit_error("size out of range")) return false; } } if (schema.contains("minItems") && value.is_array()) { if (schema.at("minItems").get<size_t>() > value.get_ref<json_array>().size()) { if (!emit_error("size out of range")) return false; } } if (schema.contains("maxItems") && value.is_array()) { if (schema.at("maxItems").get<size_t>() < value.get_ref<json_array>().size()) { if (!emit_error("size out of range")) return false; } } if (schema.contains("minProperties") && value.is_object()) { if (schema.at("minProperties").get<size_t>() > value.get_ref<json_object>().size()) { if (!emit_error("size out of range")) return false; } } if (schema.contains("maxProperties") && value.is_object()) { if (schema.at("maxProperties").get<size_t>() < value.get_ref<json_object>().size()) { if (!emit_error("size out of range")) return false; } } // check array items if (schema.contains("items") && value.is_object() && schema.at("items").is_object()) { auto& items = schema.at("items"); for (auto idx = (size_t)0; idx < value.size(); idx++) { if (!validate_json(value.at(idx), path + "/" + std::to_string(idx), items, errors, max_error)) { if (errors.size() > max_error) break; } } } if (schema.contains("items") && value.is_array() && schema.at("items").is_array()) { auto& items = schema.at("items").get_ref<json_array>(); for (auto idx = (size_t)0; idx < std::min(items.size(), value.size()); idx++) { if (!validate_json(value.at(idx), path + "/" + std::to_string(idx), items.at(idx), errors, max_error)) { if (errors.size() > max_error) break; } } } // check object properties if (schema.contains("properties") && value.is_object() && schema.at("properties").is_object()) { auto& properties = schema.at("properties").get_ref<json_object>(); for (auto& [name, property] : properties) { if (!value.contains(name)) continue; if (!validate_json( value.at(name), path + "/" + name, property, errors, max_error)) { if (errors.size() > max_error) break; } } } if (schema.contains("additionalProperties") && value.is_object() && schema.contains("properties") && schema.at("additionalProperties").is_boolean() && schema.at("additionalProperties").get<bool>() == false) { auto& properties = schema.at("properties"); for (auto& [name, item] : value.get_ref<json_object>()) { if (properties.contains(name)) { if (!emit_error("unknown property " + name)) return false; } } } if (schema.contains("additionalProperties") && value.is_object() && schema.contains("properties") && schema.at("additionalProperties").is_object()) { auto& properties = schema.at("properties"); for (auto& [name, item] : value.get_ref<json_object>()) { if (properties.contains(name)) continue; if (!validate_json( item, path + "/" + name, properties, errors, max_error)) { if (errors.size() > max_error) break; } } } if (schema.contains("required") && value.is_object() && schema.at("required").is_array()) { auto& required = schema.at("required").get_ref<json_array>(); for (auto& name_ : required) { auto& name = name_.get_ref<string>(); if (!value.contains(name)) { if (emit_error("missing value for " + name)) return false; } } } // done return false; } bool validate_json( const json_value& value, const json_value& schema, string& error) { auto errors = vector<string>{}; if (validate_json(value, "", schema, errors, 1)) return true; error = errors.at(0); return false; } bool validate_json(const json_value& value, const json_value& schema, vector<string>& errors, size_t max_errors) { return validate_json(value, "", schema, errors, max_errors); } } // namespace yocto // ----------------------------------------------------------------------------- // IMPLEMENTATION OF COMMAND-LINE PARSING // ----------------------------------------------------------------------------- namespace yocto { static json_value fix_cli_schema(const json_value& schema) { return schema; } static string get_cliusage( const json_value& schema, const string& app_name, const string& command) { // helper auto is_positional = [](const json_value& schema, const string& name) -> bool { if (!schema.contains("cli_positional")) return false; if (!schema.at("cli_positional").is_array()) return false; for (auto& pname : schema.at("cli_positional")) { if (pname.is_string() && pname.get_ref<string>() == name) return true; } return false; }; auto is_required = [](const json_value& schema, const string& name) -> bool { if (!schema.contains("required")) return false; if (!schema.at("required").is_array()) return false; for (auto& pname : schema.at("required")) { if (pname.is_string() && pname.get_ref<string>() == name) return true; } return false; }; auto has_commands = [](const json_value& schema) -> bool { for (auto& [name, property] : schema.at("properties").items()) { if (property.value("type", "") == "object") return true; } return false; }; auto get_alternate = [](const json_value& schema, const string& alt) -> string { if (!schema.contains("cli_alternate")) return ""; if (!schema.at("cli_alternate").is_object()) return ""; if (!schema.at("cli_alternate").contains(alt)) return ""; if (!schema.at("cli_alternate").at(alt).is_string()) return ""; return schema.at("cli_alternate").at(alt).get<string>(); }; auto message = string{}; auto usage_optional = string{}, usage_positional = string{}, usage_command = string{}; for (auto& [name, property] : schema.at("properties").items()) { if (property.value("type", "") == "object") continue; auto decorated_name = name; auto positional = is_positional(schema, name); if (!positional) { decorated_name = "--" + name; if (auto alt = get_alternate(schema, name); !alt.empty()) decorated_name += ", -" + alt; } auto line = " " + decorated_name; if (property.value("type", "") != "boolean") { line += " <" + property.value("type", "") + ">"; } while (line.size() < 32) line += " "; line += property.value("description", ""); if (is_required(schema, name)) { line += " [req]\n"; } else if (property.contains("default")) { auto& default_ = property.at("default"); if (default_.is_array()) { line += " ["; for (auto& item : default_) { if (&item != &default_.at(0)) line += ", "; line += format_json(item); } line += "]\n"; } else if (default_.is_object()) { line += " [object]\n"; } else { line += " [" + format_json(property.at("default")) + "]\n"; } } else { line += "\n"; } if (property.contains("enum")) { line += " with choices: "; auto len = 16; for (auto& choice_ : property.at("enum")) { auto choice = format_json(choice_); if (len + choice.size() + 2 > 78) { line += "\n "; len = 16; } line += choice + ", "; len += choice.size() + 2; } line = line.substr(0, line.size() - 2); line += "\n"; } if (positional) { usage_positional += line; } else { usage_optional += line; } } if (has_commands(schema)) { for (auto& [name, property] : schema.at("properties").items()) { if (property.value("type", "") != "object") continue; auto line = " " + name; while (line.size() < 32) line += " "; line += property.value("description", "") + "\n"; usage_command += line; } } { auto line = string{}; line += " --help"; while (line.size() < 32) line += " "; line += "Prints an help message\n"; usage_optional += line; } message += "usage: " + path_basename(app_name); if (!command.empty()) message += " " + command; if (!usage_command.empty()) message += " command"; if (!usage_optional.empty()) message += " [options]"; if (!usage_positional.empty()) message += " <arguments>"; message += "\n"; message += schema.value("description", "") + "\n\n"; if (!usage_command.empty()) { message += "commands:\n" + usage_command + "\n"; } if (!usage_optional.empty()) { message += "options:\n" + usage_optional + "\n"; } if (!usage_positional.empty()) { message += "arguments:\n" + usage_positional + "\n"; } return message; } string get_command(const cli_state& cli) { return cli.command; } bool get_help(const cli_state& cli) { return cli.help; } string get_usage(const cli_state& cli) { return cli.usage; } static bool parse_clivalue( json_value& value, const string& arg, const json_value& schema) { // if (!choices.empty()) { // if (std::find(choices.begin(), choices.end(), arg) == choices.end()) // return false; // } auto type = schema.value("type", "string"); if (type == "string") { value = arg; return true; } else if (type == "integer") { auto end = (char*)nullptr; if (arg.find('-') == 0) { value = (int64_t)strtol(arg.c_str(), &end, 10); } else { value = (uint64_t)strtoul(arg.c_str(), &end, 10); } return end != nullptr; } else if (type == "number") { auto end = (char*)nullptr; value = strtod(arg.c_str(), &end); return end != nullptr; return true; } else if (type == "boolean") { if (arg == "true" || arg == "1") { value = true; return true; } else if (arg == "false" || arg == "0") { value = false; return true; } else { return false; } } return false; } static bool parse_clivalue( json_value& value, const vector<string>& args, const json_value& schema) { auto type = schema.value("type", "string"); if (type == "array") { value = json_array{}; for (auto& arg : args) { if (!parse_clivalue(value.emplace_back(), arg, schema.at("items"))) return false; } return true; } return false; } static const char* cli_help_message = "Help invoked"; bool parse_cli(json_value& value, const json_value& schema_, const vector<string>& args, string& error, string& usage, string& command) { auto cli_error = [&error](const string& message) { error = message; return false; }; // helpers auto advance_positional = [](const json_value& schema, size_t& last_positional) -> string { if (!schema.contains("cli_positional")) return ""; auto& positionals = schema.at("cli_positional"); if (!positionals.is_array()) return ""; if (positionals.size() == last_positional) return ""; if (!positionals.at(last_positional).is_string()) return ""; return positionals.at(last_positional++).get<string>(); }; auto is_positional = [](const json_value& schema, const string& name) -> bool { if (!schema.contains("cli_positional")) return false; if (!schema.at("cli_positional").is_array()) return false; for (auto& pname : schema.at("cli_positional")) { if (pname.is_string() && pname.get_ref<string>() == name) return true; } return false; }; auto is_required = [](const json_value& schema, const string& name) -> bool { if (!schema.contains("required")) return false; if (!schema.at("required").is_array()) return false; for (auto& pname : schema.at("required")) { if (pname.is_string() && pname.get_ref<string>() == name) return true; } return false; }; auto get_alternate = [](const json_value& schema, const string& alt) -> string { if (!schema.contains("cli_alternate")) return ""; if (!schema.at("cli_alternate").is_object()) return ""; if (!schema.at("cli_alternate").contains(alt)) return ""; if (!schema.at("cli_alternate").at(alt).is_string()) return ""; return schema.at("cli_alternate").at(alt).get<string>(); }; auto get_command = [](const json_value& schema) -> string { if (!schema.contains("cli_command")) return "$command"; if (!schema.at("cli_command").is_string()) return "$command"; return schema.at("cli_command").get<string>(); }; auto has_commands = [](const json_value& schema) -> bool { for (auto& [name, property] : schema.at("properties").items()) { if (property.value("type", "") == "object") return true; } return false; }; // parsing stack struct stack_elem { string name = ""; json_value& schema; json_value& value; size_t positional = 0; }; // initialize parsing auto schema = fix_cli_schema(schema_); value = json_object{}; auto stack = vector<stack_elem>{{"", schema, value, 0}}; command = ""; usage = get_cliusage(schema, args[0], command); // parse the command line for (auto idx = (size_t)1; idx < args.size(); idx++) { auto& [_, schema, value, cpositional] = stack.back(); auto arg = args.at(idx); auto positional = arg.find('-') != 0; if (positional && has_commands(schema)) { auto name = string{}; for (auto& [pname, property] : schema.at("properties").items()) { if (property.value("type", "string") != "object") continue; if (pname != arg) continue; name = arg; } if (name.empty()) return cli_error("missing value for command"); value[get_command(schema)] = name; value[name] = json_object{}; stack.push_back( {name, schema.at("properties").at(name), value.at(name), 0}); command += (command.empty() ? "" : " ") + name; usage = get_cliusage(stack.back().schema, args[0], command); continue; } else if (positional) { auto name = string{}; auto next_positional = advance_positional(schema, cpositional); for (auto& [pname, property] : schema.at("properties").items()) { if (property.value("type", "string") == "object") continue; if (pname != next_positional) continue; name = pname; } if (name.empty()) return cli_error("too many positional arguments"); auto& property = schema.at("properties").at(name); if (property.value("type", "string") == "array") { auto array_args = vector<string>(args.begin() + idx, args.end()); if (!parse_clivalue(value[name], array_args, property)) return cli_error("bad value for " + name); idx = args.size(); } else if (property.value("type", "string") != "object") { if (!parse_clivalue(value[name], args[idx], property)) return cli_error("bad value for " + name); } } else { if (arg == "--help" || arg == "-?") { return cli_error(cli_help_message); } arg = arg.substr(1); if (arg.find('-') == 0) arg = arg.substr(1); auto name = string{}; for (auto& [pname, property] : schema.at("properties").items()) { if (property.value("type", "string") == "object") continue; if (is_positional(schema, pname)) continue; if (pname != arg && get_alternate(schema, pname) != arg) continue; name = pname; break; } if (name.empty()) return cli_error("unknown option " + args[idx]); if (value.contains(name)) return cli_error("option already set " + name); auto& property = schema.at("properties").at(name); if (property.value("type", "string") == "boolean") { if (!parse_clivalue(value[name], "true", property)) return cli_error("bad value for " + name); } else if (property.value("type", "string") == "array") { auto min_items = (int)property.value("minItems", 0); auto max_items = (int)property.value("maxItems", 0); if (min_items != max_items || max_items == 0) return cli_error("bad array for " + name); if (idx + max_items >= args.size()) return cli_error("missing value for " + name); auto array_args = vector<string>( args.begin() + idx + 1, args.begin() + idx + 1 + max_items); if (!parse_clivalue(value[name], array_args, property)) return cli_error("bad value for " + name); idx += 1 + max_items; } else { if (idx + 1 >= args.size()) return cli_error("missing value for " + name); if (!parse_clivalue(value[name], args[idx + 1], property)) return cli_error("bad value for " + name); idx += 1; } } } // check for required and apply defaults for (auto& [_, schema, value, __] : stack) { if (has_commands(schema) && !value.contains(get_command(schema))) return cli_error("missing value for " + get_command(schema)); for (auto& [name, property] : schema.at("properties").items()) { if (property.value("type", "string") == "object") continue; if (is_required(schema, name) && !value.contains(name)) return cli_error("missing value for " + name); if (property.contains("default") && !value.contains(name)) value[name] = property.at("default"); } } // done return true; } bool parse_cli(json_value& value, const json_value& schema, const vector<string>& args, string& error, string& usage) { auto command = string{}; return parse_cli(value, schema, args, error, usage, command); } bool parse_cli(json_value& value, const json_value& schema, int argc, const char** argv, string& error, string& usage) { return parse_cli(value, schema, {argv, argv + argc}, error, usage); } void parse_cli( json_value& value, const json_value& schema, const vector<string>& args) { auto error = string{}; auto usage = string{}; if (!parse_cli(value, schema, args, error, usage)) { if (error != cli_help_message) { print_info("error: " + error); print_info(""); } print_info(usage); exit(error != cli_help_message ? 1 : 0); } } void parse_cli( json_value& value, const json_value& schema, int argc, const char** argv) { return parse_cli(value, schema, {argv, argv + argc}); } } // namespace yocto // ----------------------------------------------------------------------------- // IMPLEMENTATION OF JSON TREE DATA STRUCTURE // ----------------------------------------------------------------------------- namespace yocto { // convert json void to_json(njson& njs, json_ctview json) { switch (get_type(json)) { case json_type::null: njs = nullptr; break; case json_type::ninteger: njs = get_number_integer(json); break; case json_type::nunsigned: njs = get_number_unsigned(json); break; case json_type::nfloat: njs = get_number_real(json); break; case json_type::boolean: njs = get_boolean(json); break; case json_type::string: njs = get_string(json); break; case json_type::array: njs = njson::array(); for (auto ejs : iterate_array(json)) to_json(njs.emplace_back(), ejs); break; case json_type::object: njs = njson::object(); for (auto [key, ejs] : iterate_object(json)) to_json(njs[string{key}], ejs); break; case json_type::binary: njs = njson::binary({}); get_binary(json, njs.get_binary()); break; } } // convert json void from_json(const njson& njs, json_tview json) { switch (njs.type()) { case njson::value_t::null: set_null(json); break; case njson::value_t::number_integer: set_integer(json, (int64_t)njs); break; case njson::value_t::number_unsigned: set_unsigned(json, njs); break; case njson::value_t::number_float: set_real(json, njs); break; case njson::value_t::boolean: set_boolean(json, (bool)njs); break; case njson::value_t::string: set_string(json, (string)njs); break; case njson::value_t::array: set_array(json); for (auto& ejs : njs) from_json(ejs, append_element(json)); break; case njson::value_t::object: set_object(json); for (auto& [key, ejs] : njs.items()) from_json(ejs, insert_element(json, key)); break; case njson::value_t::binary: set_binary(json, njs.get_binary()); break; case njson::value_t::discarded: set_null(json); break; } } #if YOCTO_JSON_SAX == 1 // load json bool load_json(const string& filename, json_tree& json, string& error) { // error helpers auto parse_error = [filename, &error]() { error = filename + ": parse error in json"; return false; }; // sax handler struct sax_handler { // stack json_tview root; std::vector<json_tview> stack = {}; std::string current_key; explicit sax_handler(json_tview root_) : root{root_}, stack{root_} {} // get current value json_tview next_value() { if (stack.size() == 1) return root; auto& jst = _get_type(stack.back()); if (jst == json_type::array) return append_element(stack.back()); if (jst == json_type::object) return insert_element(stack.back(), current_key); throw yocto::json_error{"bad json type"}; } // values bool null() { set_null(next_value()); return true; } bool boolean(bool value) { set_boolean(next_value(), value); return true; } bool number_integer(int64_t value) { set_integer(next_value(), value); return true; } bool number_unsigned(uint64_t value) { set_unsigned(next_value(), value); return true; } bool number_float(double value, const std::string&) { set_real(next_value(), value); return true; } bool string(std::string& value) { set_string(next_value(), value); return true; } bool binary(std::vector<uint8_t>& value) { set_binary(next_value(), value); return true; } // objects bool start_object(size_t elements) { set_object(next_value()); stack.push_back(next_value()); return true; } bool end_object() { stack.pop_back(); return true; } bool key(std::string& value) { current_key = value; return true; } // arrays bool start_array(size_t elements) { set_array(next_value()); stack.push_back(next_value()); return true; } bool end_array() { stack.pop_back(); return true; } bool parse_error(size_t position, const std::string& last_token, const nlohmann::detail::exception&) { return false; } }; // set up parsing json = json_tree{}; auto handler = sax_handler{get_root(json)}; // load text auto text = ""s; if (!load_text(filename, text, error)) return false; // parse json if (!njson::sax_parse(text, &handler)) return parse_error(); return true; } #else // load json bool load_json(const string& filename, json_tree& json, string& error) { // parse json auto njs = njson{}; if (!load_json(filename, njs, error)) return false; // convert from_json(njs, get_root(json)); return true; } #endif // save json bool save_json(const string& filename, const json_tree& json, string& error) { // convert auto njs = njson{}; to_json(njs, get_root((json_tree&)json)); // save return save_json(filename, njs, error); } } // namespace yocto
{ "content_hash": "52e58452f243092f393b6e37c175cd3d", "timestamp": "", "source": "github", "line_count": 1018, "max_line_length": 80, "avg_line_length": 33.09430255402751, "alnum_prop": 0.5651825467497774, "repo_name": "jing-interactive/Cinder-portfolio", "id": "95a41b5bbac9ce16cfb3886bfe0f48c5a493a54a", "size": "35221", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "blocks/yocto-gl/libs/yocto/yocto_json.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1506" }, { "name": "C", "bytes": "466592" }, { "name": "C++", "bytes": "1900983" }, { "name": "Cuda", "bytes": "112150" }, { "name": "GLSL", "bytes": "48532" }, { "name": "JavaScript", "bytes": "16386" }, { "name": "Objective-C", "bytes": "106163" }, { "name": "Processing", "bytes": "1689" } ], "symlink_target": "" }
<!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>Ji Young Hong, BFA Illustration Senior Thesis 2016 - 2017</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="apple-touch-icon" href="apple-touch-icon.png"> <!-- Place favicon.ico in the root directory --> <link rel="stylesheet" href="../css/normalize.css"> <link rel="stylesheet" href="../css/main.css"> <script src="../js/vendor/modernizr-2.8.3.min.js"></script> <link href="https://fonts.googleapis.com/css?family=Space+Mono:400,400i" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="../css/webfont.css"> </head> <body id='individual' class='wrapper bg-yellow'> <!--[if lt IE 8]> <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <![endif]--> <div id='header' class='wrapper monospace large italic padding bg-yellow-fade'> <ul class='col_66 inline-block top'> <a href='../index.html'><li>Parsons School of Design / The New School</br>BFA Illustration<scpan class='m-left inline-block'>Senior Thesis</scpan></li></a> </ul> <ul id='menu' class='col_33 inline-block top wrapper bg-white'> <li class='selected wrapper'> 2016 &mdash; 2017<scpan class='arrow'>&darr;</scpan> <ul> <div class='unselected grey hidden col_100 padding'> <a href='#'><li class='wrapper'>No Other Years</li></a> </div> </ul> </li> <li class='selected wrapper'> All Disciplines<scpan class='arrow'>&darr;</scpan> <ul> <div class='unselected grey hidden padding'> <a href='../work/animation.html'><li class='wrapper'>Animation</li></a> <a href='../work/book_illustration.html'><li class='wrapper'>Book Illustration</li></a> <a href='../work/comics_graphic_novel.html'><li class='wrapper'>Comics and Graphic Novel</li></a> <a href='../work/childrens_book.html'><li class='wrapper'>Children&#8217;s Book</li></a> <a href='../work/editorial.html'><li class='wrapper'>Editorial</li></a> <a href='../work/game_design.html'><li class='wrapper'>Game Design</li></a> <a href='../work/multimedia.html'><li class='wrapper'>Multimedia</li></a> <a href='../work/painting.html'><li class='wrapper'>Painting</li></a> <a href='../work/printmaking.html'><li class='wrapper'>Printmaking</li></a> <a href='../work/visual_essay.html'><li class='wrapper'>Visual Essay</li></a> <a href='../work/puppets_toy_theatre.html'><li class='wrapper'>Puppets and Toy Theatre</li></a> <a href='../work/surface_design.html'><li class='wrapper'>Surface Design</li></a> <a href='../work/toy_design.html'><li class='wrapper'>Toy Design</li></a> <a href='../work/world_building.html'><li class='wrapper'>World Building</li></a> </div> </ul> </li> </ul> <ul class='toggle wrapper col_100 top padding'> <li> <scpan class='arrow'><a href='Gutierrez_Bradley.html'>&larr;</a></scpan> <scpan class='arrow'><a href='Jame_Abby.html'>&rarr;</a></scpan> </li> </ul> </div> <div id='main_content' class='documentation padding bg-white'> <ul class='col_33 inline-block top'> <li class='sans-serif large'>Ji Young Hong</li> <li class='monospace medium italic'>Flip</li> <li class='sans-serif medium'>Flipping memory from the past.</li> <li class='sans-serif small'>My thesis is about a childhood memory. I want to depict how I perceive my memory through a portrait of myself and people around me. Since memories from the past are not accurate, they might have some unrealistic points at somewhere.</li> <li class='sans-serif small'>Therefore, each portrait will have own memories or episode that explains what happened at that time. It would be hard to imagine what stories it has, but I hope viewers still can see what I felt in the past.</li> <!-- <li class='sans-serif small'>Personal Website</br> <a href='#'>Website</a> </li> --> <li class='sans-serif small'>Disciplines</br> <a class='monospace italic' href='../work/editorial.html'>Editorial</a></br> <a class='monospace italic' href='../work/animation.html'>Animation</a></br> <a class='monospace italic' href='../work/visual_essay.html'>Visual Essay</a> </li> </ul> <ul class='col_66 inline-block center'> <li class='wrapper'><img class='fade-in' src='../img/Hong_Ji_Young/01_image_Hong_Ji_Young_sp17.jpg'/></li> <li class='wrapper'><img class='fade-in' src='../img/Hong_Ji_Young/02_image_Hong_Ji_Young_sp17.jpg'/></li> <li class='wrapper'><img class='fade-in' src='../img/Hong_Ji_Young/03_image_Hong_Ji_Young_sp17.jpg'/></li> <li class='wrapper'><img class='fade-in' src='../img/Hong_Ji_Young/04_image_Hong_Ji_Young_sp17.jpg'/></li> <li class='wrapper'><img class='fade-in' src='../img/Hong_Ji_Young/05_image_Hong_Ji_Young_sp17.jpg'/></li> </ul> </div> <div id='footer' class='monospace large italic padding bg-white'> <ul class='col_33 inline-block top'> <a href='http://www.newschool.edu/parsons/bfa-illustration/'><li>Parsons Illustration</br>2 West 13th St, #806</br>New York, NY 10011</li></a> </ul> <ul class='unselected col_33 inline-block top'> <a href='#'><li class='wrapper'>Twitter<scpan class='arrow'>&rarr;</scpan></li></a> <a href='#'><li class='wrapper'>Instagram<scpan class='arrow'>&rarr;</scpan></li></a> <a href='#'><li class='wrapper'>Facebook<scpan class='arrow'>&rarr;</scpan></li></a> </ul> <ul class='col_33 inline-block top right'> <a id='scroll_to_top'><li>Top</li></a> </ul> </div> <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script> <script>window.jQuery || document.write('<script src="../js/vendor/jquery-1.12.0.min.js"><\/script>')</script> <script src="../js/plugins.js"></script> <script src="../js/main.js"></script> </body> </html>
{ "content_hash": "56a110dff838a7effaeb73255bc5e26c", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 282, "avg_line_length": 68.30841121495327, "alnum_prop": 0.5413873306881927, "repo_name": "clarissaong/clarissaong.github.io", "id": "6adf1b9c75212ff2a3ab2cc9fbad0a2476701073", "size": "7309", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web_v4/student/Hong_Ji_Young.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "158772" }, { "name": "CSS", "bytes": "72211" }, { "name": "HTML", "bytes": "1072361" }, { "name": "JavaScript", "bytes": "62918" } ], "symlink_target": "" }
'use strict'; /** * Module dependencies */ var path = require('path'), mongoose = require('mongoose'), Medium = mongoose.model('Medium'), errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')); /** * Create an medium */ exports.create = function (req, res) { var medium = new Medium(req.body); medium.user = req.user; medium.save(function (err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(medium); } }); }; /** * Show the current medium */ exports.read = function (req, res) { // convert mongoose document to JSON var medium = req.medium ? req.medium.toJSON() : {}; // Add a custom field to the Medium, for determining if the current User is the "owner". // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Medium model. medium.isCurrentUserOwner = !!(req.user && medium.user && medium.user._id.toString() === req.user._id.toString()); res.json(medium); }; /** * Update an medium */ exports.update = function (req, res) { var medium = req.medium; medium.title = req.body.title; medium.content = req.body.content; medium.save(function (err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(medium); } }); }; /** * Delete an medium */ exports.delete = function (req, res) { var medium = req.medium; medium.remove(function (err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(medium); } }); }; /** * List of Mediums */ exports.list = function (req, res) { Medium.find().sort('-created').populate('user', 'displayName').exec(function (err, mediums) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(mediums); } }); }; /** * Medium middleware */ exports.mediumByID = function (req, res, next, id) { if (!mongoose.Types.ObjectId.isValid(id)) { return res.status(400).send({ message: 'Medium is invalid' }); } Medium.findById(id).populate('user', 'displayName').exec(function (err, medium) { if (err) { return next(err); } else if (!medium) { return res.status(404).send({ message: 'No medium with that identifier has been found' }); } req.medium = medium; next(); }); };
{ "content_hash": "ecb6eb97d01eece3b5bd5bc6255ad245", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 194, "avg_line_length": 27.471153846153847, "alnum_prop": 0.5463773188659433, "repo_name": "p3t3revans/MaristOnline", "id": "1204fdbda671cba52d00d220c333f9e8ad086eed", "size": "2857", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/mediums/server/controllers/mediums.server.controller.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7049" }, { "name": "HTML", "bytes": "80991" }, { "name": "JavaScript", "bytes": "324055" }, { "name": "Shell", "bytes": "686" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TeleTurk.Core.Auth; using TeleTurk.Core.MTProto; using TeleTurk.Core.MTProto.Crypto; using TeleTurk.Core.Network; namespace TeleTurk.Core.Handlers { class ContactsHandlers { } }
{ "content_hash": "174a91ccc511e6917aa17073f2c8a09d", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 35, "avg_line_length": 19.625, "alnum_prop": 0.7770700636942676, "repo_name": "ShanalTeam/TeleTurk", "id": "5d891f65e4cb2ffa2207b05a4b072e9fad695a63", "size": "316", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TeleTurk.Core/Handlers/ContactsHandlers.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1945902" } ], "symlink_target": "" }
<?php /** * Template for single operation in group. * * @author: Andrii Birev */ defined('BEXEC')or die('No direct access!'); use \Brilliant\CMS\BLang; $fields=array(); if(empty($this->operation)){ $fields['amount']=0; $fields['peritem']=''; } else{ $fields['amount']=$this->operation->amountformat(); $fields['peritem']=$this->operation->peritem; } $idpref='operation-'.$this->index.'-'; ?> <div id="opgroupexample" class="panel panel-default opgoperation"<?php echo(empty($this->operation)?' style="display: none;"':''); ?>> <div class="panel-heading"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h3 class="panel-title">Operation</h3> </div> <div class="panel-body row"> <div class="col-lg-3 col-md-12 col-sm-12 opgname form-group"> <label class="sr-only" for="<?php echo $idpref.'payee'; ?>">Payee</label> <input type="hidden" id="<?php echo $idpref.'payee'; ?>" class="form-control input-sm select2 payees" name="opgroup_name" placeholder="Payee" value="<?php echo $this->operation->payee; ?>"/> </div> <div class="col-lg-3 col-md-4 col-sm-4 opgname form-group"> <label class="sr-only" for="opgroup_name">Account</label> <select type="text" id="opgroup_name" class="form-control input-sm" name="opgroup_account" placeholder="Account"> <option value=""><?php echo BLang::_('COMPFINANCES_ACCOUNT_PLEASESELECT'); ?></option> <?php foreach($this->accounts as $acc): ?> <option value="<?php echo $acc->id; ?>"<?php echo($this->operation->account==$acc->id?' selected':''); ?>><?php echo htmlspecialchars($acc->name); ?></option> <?php endforeach; ?> </select> </div> <div class="col-lg-3 col-md-4 col-sm-4 opgname form-group"> <label class="sr-only" for="opgroup_name">Category</label> <select type="text" id="opgroup_name" class="form-control input-sm" name="opgroup_category" placeholder="Category"> <option value=""><?php echo BLang::_('COMPFINANCES_CATEGORY_PLEASESELECT'); ?></option> <?php foreach($this->categories as $cat): ?> <option value="<?php echo $cat->id; ?>"<?php echo($this->operation->category==$cat->id?' selected':''); ?>><?php echo htmlspecialchars($cat->getnamelevel()); ?></option> <?php endforeach; ?> </select> </div> <div class="col-lg-3 col-md-4 col-sm-4 opgname form-group"> <label class="sr-only" for="opgroup_name">Project</label> <select type="text" id="opgroup_name" class="form-control input-sm" name="opgroup_project" placeholder="Project"> <option value=""><?php echo BLang::_('PROJECTS_PROJECT_PLEASESELECT'); ?></option> <?php foreach($this->projects as $project): ?> <option value="<?php echo $project->id; ?>"><?php echo htmlspecialchars($project->getnamelevel()); ?></option> <?php endforeach; ?> </select> </div> <div class="col-lg-4 col-md-4 col-sm-4 opgname form-group"> <label class="sr-only" for="opgroup_name">Per item</label> <div class="input-group"> <div class="input-group-btn"> <button type="button" class="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><span class="glyphicon glyphicon-minus"></span>&nbsp;<span class="caret"></span></button> <ul class="dropdown-menu"> <li><a href="#">+</a></li> <li><a href="#">-</a></li> </ul> </div><!-- /btn-group --> <input type="text" id="opgroup_name" class="form-control input-sm" name="opgroup_name" placeholder="Per item" value="<?php echo $fields['peritem']; ?>"/> <span class="input-group-addon">грн.</span> </div> </div> <div class="col-lg-4 col-md-4 col-sm-4 opgname form-group"> <div class="input-group"> <label class="sr-only" for="opgroup_name">Items</label> <input type="text" id="opgroup_name" class="form-control input-sm" name="opgroup_name" placeholder="Items" value="<?php echo(empty($this->operation)?1:$this->operation->items); ?>"/> <div class="input-group-btn"> <button type="button" class="btn btn-default btn-sm input-sm dropdown-toggle" data-toggle="dropdown" aria-expanded="false">шт.<span class="caret"></span></button> <ul class="dropdown-menu dropdown-menu-right" role="menu"> <li><a href="#">шт.</a></li> <li><a href="#">кг.</a></li> <li class="divider"></li> <li><a href="#">м</a></li> <li><a href="#">м<sup>2</sup></a></li> <li><a href="#">м<sup>3</sup></a></li> </ul> </div><!-- /btn-group --> </div><!-- /input-group --> </div> <div class="col-lg-4 col-md-4 col-sm-4 opgname form-group"> <label class="sr-only" for="opgroup_name">Amount</label> <input type="text" id="opgroup_name" class="form-control input-sm" name="opgroup_name" placeholder="Amount"/> </div> </div><!-- /panel-body --> </div><!-- /opgoperation -->
{ "content_hash": "ec5d04f9da06ff5a71d94461f78f34c5", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 229, "avg_line_length": 51.57446808510638, "alnum_prop": 0.6344884488448845, "repo_name": "konservs/financello", "id": "187cdf82200bc9ef340f2e0eff4631ce4ea79810", "size": "4860", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "templates/members/finances.opgroup.operation.d.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6103" }, { "name": "JavaScript", "bytes": "4537" }, { "name": "PHP", "bytes": "293759" } ], "symlink_target": "" }
package com.tw.qa.plugin.sample; import com.google.gson.GsonBuilder; import com.thoughtworks.go.plugin.api.GoApplicationAccessor; import com.thoughtworks.go.plugin.api.GoPlugin; import com.thoughtworks.go.plugin.api.GoPluginIdentifier; import com.thoughtworks.go.plugin.api.annotation.Extension; import com.thoughtworks.go.plugin.api.annotation.Load; import com.thoughtworks.go.plugin.api.annotation.UnLoad; import com.thoughtworks.go.plugin.api.exceptions.UnhandledRequestTypeException; import com.thoughtworks.go.plugin.api.info.PluginContext; import com.thoughtworks.go.plugin.api.logging.Logger; import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import com.tw.go.dependency.Console; import java.util.HashMap; import static java.util.Arrays.asList; @Extension public class TestWithSomePluginXmlValues implements GoPlugin { Console console = new Console(); Logger logger = Logger.getLoggerFor(TestWithSomePluginXmlValues.class); static { Logger.getLoggerFor(TestWithSomePluginXmlValues.class).info("Boo"); } @Load public void onLoad(PluginContext context) { logger.info("Boo"); System.out.println("Plugin with some plugin.xml values loaded"); } @UnLoad public void onUnload(PluginContext context) { System.out.println("Plugin unloaded"); } @Override public void initializeGoApplicationAccessor(GoApplicationAccessor goApplicationAccessor) { } @Override public GoPluginApiResponse handle(GoPluginApiRequest goPluginApiRequest) throws UnhandledRequestTypeException { if ("configuration".equals(goPluginApiRequest.requestName())) { return new GetTaskPluginConfig().execute(); } else if ("view".equals(goPluginApiRequest.requestName())) { return getViewRequest(); } throw new UnhandledRequestTypeException(goPluginApiRequest.requestName()); } private GoPluginApiResponse getViewRequest(){ HashMap<String, String> view = new HashMap<>(); view.put("displayValue", "TestTask"); view.put("template", "<html><body>with some plugin xml values</body></html>"); return DefaultGoPluginApiResponse.success(new GsonBuilder().create().toJson(view)); } @Override public GoPluginIdentifier pluginIdentifier() { return new GoPluginIdentifier("task", asList("1.0")); } }
{ "content_hash": "7124d65f3fe5b9b8d24a4b0c98b81780", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 115, "avg_line_length": 35.27777777777778, "alnum_prop": 0.7452755905511811, "repo_name": "gocd/go-plugins", "id": "1a8e463d537554fdda3d71ada4220991d15495f9", "size": "3286", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plugins-for-tests/test-with-some-plugin-xml-values/src/main/java/com/tw/qa/plugin/sample/TestWithSomePluginXmlValues.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "6553" }, { "name": "Java", "bytes": "175480" } ], "symlink_target": "" }
.. .. .. 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. .. Developer's Guide ***************** Use this guide to start developing applications that consume the Traffic Control APIs, to create extensions to Traffic Ops, or work on Traffic Control itself. .. toctree:: :maxdepth: 2 building traffic_ops traffic_portal traffic_router traffic_monitor traffic_monitor_golang traffic_stats traffic_server
{ "content_hash": "35c26c0460309e390719b101d3af62ef", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 158, "avg_line_length": 30.032258064516128, "alnum_prop": 0.7314715359828142, "repo_name": "serDrem/incubator-trafficcontrol", "id": "ecabe1de58ef053fdf29c9af547cedff6ae5b435", "size": "931", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "docs/source/development/index.rst", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "21929" }, { "name": "CSS", "bytes": "188879" }, { "name": "Go", "bytes": "1377260" }, { "name": "HTML", "bytes": "723492" }, { "name": "Java", "bytes": "1232975" }, { "name": "JavaScript", "bytes": "1598022" }, { "name": "Makefile", "bytes": "1047" }, { "name": "PLSQL", "bytes": "4308" }, { "name": "PLpgSQL", "bytes": "70798" }, { "name": "Perl", "bytes": "3472258" }, { "name": "Perl 6", "bytes": "25530" }, { "name": "Python", "bytes": "92267" }, { "name": "Roff", "bytes": "4011" }, { "name": "Ruby", "bytes": "4090" }, { "name": "SQLPL", "bytes": "67758" }, { "name": "Shell", "bytes": "166073" } ], "symlink_target": "" }
package org.mones.chartjsgenj; import static org.junit.Assert.fail; import junit.framework.Assert; import org.junit.Test; public class ThemeTest { @Test public void testTheme() { try { new Theme(null); } catch (NullPointerException npe) { // ok! } catch (Exception e) { e.printStackTrace(); fail(); } try { Theme t0 = new Theme(""); Assert.assertNotNull(t0); Assert.assertNotNull(t0.getColours()); Assert.assertEquals(1, t0.getColours().size()); // black Assert.assertEquals(0, t0.getColours().get(0).getR()); Assert.assertEquals(0, t0.getColours().get(0).getG()); Assert.assertEquals(0, t0.getColours().get(0).getB()); Assert.assertEquals(1.0f, t0.getColours().get(0).getA()); Theme t1 = new Theme(Theme.HM_LIME); Assert.assertNotNull(t1); Assert.assertNotNull(t1.getColours()); Assert.assertEquals(6, t1.getColours().size()); } catch (Exception e) { e.printStackTrace(); fail(); } } @Test public void testAddColors() { Theme t1 = new Theme(Theme.HM_LIME); Assert.assertNotNull(t1); Assert.assertNotNull(t1.getColours()); Assert.assertEquals(6, t1.getColours().size()); Theme t2 = new Theme(Theme.SOLARIZED_BASE); Assert.assertNotNull(t2); Assert.assertNotNull(t2.getColours()); Assert.assertEquals(8, t2.getColours().size()); t1.addColours(t2.getColours()); Assert.assertEquals(8, t2.getColours().size()); Assert.assertEquals(14, t1.getColours().size()); } @Test public void testApplyChart() { Theme t1 = new Theme("#112233,#223311"); Assert.assertNotNull(t1); Assert.assertNotNull(t1.getColours()); Assert.assertEquals(2, t1.getColours().size()); Chart c = new Chart(ChartType.LINE); c.addDataset(new Dataset("1", 1)); c.addDataset(new Dataset("2", 2)); t1.apply(c); Assert.assertEquals("#112233", c.getDatasets().get(0).getColor().toHTML()); Assert.assertEquals("#112233", c.getDatasets().get(0).getPointColor().toHTML()); Assert.assertEquals("#112233", c.getDatasets().get(0).getStrokeColor().toHTML()); Assert.assertEquals("#223311", c.getDatasets().get(1).getColor().toHTML()); Assert.assertEquals("#223311", c.getDatasets().get(1).getPointColor().toHTML()); Assert.assertEquals("#223311", c.getDatasets().get(1).getStrokeColor().toHTML()); } @Test public void testApplyChartInt() { Theme t1 = new Theme("#112233,#223311"); Assert.assertNotNull(t1); Assert.assertNotNull(t1.getColours()); Assert.assertEquals(2, t1.getColours().size()); Chart c = new Chart(ChartType.LINE); c.addDataset(new Dataset("1", 1)); c.addDataset(new Dataset("2", 2)); t1.apply(c, 1); Assert.assertEquals("#223311", c.getDatasets().get(0).getColor().toHTML()); Assert.assertEquals("#223311", c.getDatasets().get(0).getPointColor().toHTML()); Assert.assertEquals("#223311", c.getDatasets().get(0).getStrokeColor().toHTML()); Assert.assertEquals("#112233", c.getDatasets().get(1).getColor().toHTML()); Assert.assertEquals("#112233", c.getDatasets().get(1).getPointColor().toHTML()); Assert.assertEquals("#112233", c.getDatasets().get(1).getStrokeColor().toHTML()); } }
{ "content_hash": "087eb7054fa06572141b9dc1df5c4ba5", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 83, "avg_line_length": 34.24175824175824, "alnum_prop": 0.6854942233632862, "repo_name": "mones/chartjsgenj", "id": "59d77abd4952b18bdf6cd3c3b6b48aaf806ed73b", "size": "3326", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/org/mones/chartjsgenj/ThemeTest.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Java", "bytes": "80950" } ], "symlink_target": "" }
$H ${artifactId} ${artifactId} description $H$H Configuration Before building ${artifactId} you need to define the following environment variables to point to the local DataFlow update site [dataflow-p2-site](https://github.com/ActianCorp/dataflow-p2-site) root directory and the DataFlow version. export DATAFLOW_REPO_HOME=/Users/myuser/dataflow-p2-site export DATAFLOW_VER=6.5.2.112 $H$H Building The update site is built using [Apache Maven 3.0.5 or later](http://maven.apache.org/). To build, run: mvn clean install You can update the version number by running mvn org.eclipse.tycho:tycho-versions-plugin:set-version -DnewVersion=version where version is of the form x.y.z or x.y.z-SNAPSHOT. $H$H Using ${artifactId} with the DataFlow Engine The build generates a JAR file in the target directory under ${artifactId}-dataflow-extensions with a name similar to ${artifactId}-dataflow-extensions-1.y.z.jar which can be included on the classpath when using the DataFlow engine. $H$H Installing the ${artifactId} plug-in in KNIME The build also produces a ZIP file which can be used as an archive file with the KNIME 'Help/Install New Software...' dialog. The ZIP file can be found in the target directory under ${artifactId}-knime-extensions-update-site and with a name like com.actian.services.knime.${artifactId}.update-1.y.z.zip
{ "content_hash": "fd7324c0dde42e55ed0a7f4ceb133b1c", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 235, "avg_line_length": 30.91111111111111, "alnum_prop": 0.7548526240115025, "repo_name": "ActianCorp/df-newextension-archetype", "id": "4feaf8ef463f3c450bf63b28802be2247ad22420", "size": "1408", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/resources/archetype-resources/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "17049" } ], "symlink_target": "" }
<?php /** * @var string $token * @var string $user_name * @var string $new_password * @var string $url */ $url = \yii\helpers\Url::to(['/user/account/activate', 'token' => $token], true); ?> <p><?= Yii::t('mail', 'Hello, ') . $user_name . '!' ?></p> <p><?= Yii::t('mail', 'You are receiving this email because you (or someone pretending to be you) asked to send a new password to your account on web site. If you did not ask to send the password, you should not pay attention to this letter, and if such mail continue to arrive, contact our administration.') ?></p> <p><?= Yii::t('mail', 'Before using the new password you have to activate it. Follow the link below: ') ?></p> <p><?= \yii\helpers\Html::a($url, $url);?></p> <p><?= Yii::t('mail', 'After successful activation you can log in using the following password: ') ?></p> <p><?= Yii::t('mail', 'Password: ') . $new_password ?></p> <p><?= Yii::t('mail', 'Thanks, site administration.') ?></p>
{ "content_hash": "b724beef7ed84853082ed3c4e2e60746", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 159, "avg_line_length": 50.31578947368421, "alnum_prop": 0.6317991631799164, "repo_name": "vetoni/toko", "id": "116f2f1034e0606eaaa11e11170d666021e5b445", "size": "956", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mail/user/forgot_password.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "258" }, { "name": "Batchfile", "bytes": "515" }, { "name": "CSS", "bytes": "30150" }, { "name": "JavaScript", "bytes": "6393" }, { "name": "PHP", "bytes": "373159" } ], "symlink_target": "" }
from django.contrib.auth.models import AnonymousUser from django.db import models from django.db.models.aggregates import Count from polymorphic.manager import PolymorphicManager from shop.order_signals import processing from shop.util.compat.db import atomic #============================================================================== # Product #============================================================================== class ProductStatisticsManager(PolymorphicManager): """ A Manager for all the non-object manipulation needs, mostly statistics and other "data-mining" toys. """ def top_selling_products(self, quantity): """ This method "mines" the previously passed orders, and gets a list of products (of a size equal to the quantity parameter), ordered by how many times they have been purchased. """ # Importing here is fugly, but it saves us from circular imports... from shop.models.ordermodel import OrderItem # Get an aggregate of product references and their respective counts top_products_data = OrderItem.objects.values( 'product').annotate( product_count=Count('product') ).order_by('product_count' )[:quantity] # The top_products_data result should be in the form: # [{'product_reference': '<product_id>', 'product_count': <count>}, ..] top_products_list = [] # The actual list of products for values in top_products_data: prod = values.get('product') # We could eventually return the count easily here, if needed. top_products_list.append(prod) return top_products_list class ProductManager(PolymorphicManager): """ A more classic manager for Product filtering and manipulation. """ def active(self): return self.filter(active=True) #============================================================================== # Order #============================================================================== class OrderManager(models.Manager): def get_latest_for_user(self, user): """ Returns the last Order (from a time perspective) a given user has placed. """ if user and not isinstance(user, AnonymousUser): return self.filter(user=user).order_by('-modified')[0] else: return None def get_unconfirmed_for_cart(self, cart): return self.filter(cart_pk=cart.pk, status__lt=self.model.CONFIRMED) def remove_old_orders(self, cart): """ Removes all old unconfirmed order objects. """ old_orders = self.get_unconfirmed_for_cart(cart) old_orders.delete() def create_order_object(self, cart, request): """ Create an empty order object and fill it with the given cart data. """ order = self.model() order.cart_pk = cart.pk order.user = cart.user order.status = self.model.PROCESSING # Processing order.order_subtotal = cart.subtotal_price order.order_total = cart.total_price return order @atomic def create_from_cart(self, cart, request): """ This creates a new Order object (and all the rest) from a passed Cart object. Specifically, it creates an Order with corresponding OrderItems and eventually corresponding ExtraPriceFields This will only actually commit the transaction once the function exits to minimize useless database access. The `state` parameter is further passed to process_cart_item, process_cart, and post_process_cart, so it can be used as a way to store per-request arbitrary information. Emits the ``processing`` signal. """ # must be imported here! from shop.models.ordermodel import ( ExtraOrderItemPriceField, ExtraOrderPriceField, OrderItem, ) from shop.models.cartmodel import CartItem # First, let's remove old orders self.remove_old_orders(cart) # Create an empty order object order = self.create_order_object(cart, request) order.save() # Let's serialize all the extra price arguments in DB for field in cart.extra_price_fields: eoi = ExtraOrderPriceField() eoi.order = order eoi.label = unicode(field[0]) eoi.value = field[1] if len(field) == 3: eoi.data = field[2] eoi.save() # There, now move on to the order items. cart_items = CartItem.objects.filter(cart=cart) for item in cart_items: item.update(request) order_item = OrderItem() order_item.order = order order_item.product_reference = item.product.get_product_reference() order_item.product_name = item.product.get_name() order_item.product = item.product order_item.unit_price = item.product.get_price() order_item.quantity = item.quantity order_item.line_total = item.line_total order_item.line_subtotal = item.line_subtotal order_item.save() # For each order item, we save the extra_price_fields to DB for field in item.extra_price_fields: eoi = ExtraOrderItemPriceField() eoi.order_item = order_item # Force unicode, in case it has àö... eoi.label = unicode(field[0]) eoi.value = field[1] if len(field) == 3: eoi.data = field[2] eoi.save() processing.send(self.model, order=order, cart=cart) return order
{ "content_hash": "409fcf52d7744c0909425d5391a25753", "timestamp": "", "source": "github", "line_count": 162, "max_line_length": 79, "avg_line_length": 36.141975308641975, "alnum_prop": 0.5772843723313408, "repo_name": "febsn/django-shop", "id": "134033087bdaba26d39dd2d265e396aaa47d798e", "size": "5881", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "shop/models_bases/managers.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "9179" }, { "name": "Python", "bytes": "410245" }, { "name": "Shell", "bytes": "916" } ], "symlink_target": "" }
package org.ohdsi.webapi.tag.domain; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity(name = "ReusableTag") @Table(name = "reusable_tag") public class ReusableTag { @EmbeddedId private AssetTagPK assetId; @OneToOne(optional = false, targetEntity = Tag.class, fetch = FetchType.LAZY) @JoinColumn(name = "tag_id", insertable = false, updatable = false) private Tag tag; public AssetTagPK getAssetId() { return assetId; } public void setAssetId(AssetTagPK assetId) { this.assetId = assetId; } public Tag getTag() { return tag; } public void setTag(Tag tag) { this.tag = tag; } }
{ "content_hash": "c7602747780bc825dc342bf831d625d5", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 81, "avg_line_length": 23.25, "alnum_prop": 0.6893667861409797, "repo_name": "OHDSI/WebAPI", "id": "cf26ead9b6f9ed573eacbd8f11e90a89abf58bd8", "size": "837", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/ohdsi/webapi/tag/domain/ReusableTag.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "2198" }, { "name": "HTML", "bytes": "127" }, { "name": "Java", "bytes": "3237113" }, { "name": "Makefile", "bytes": "4511" }, { "name": "PLSQL", "bytes": "161939" }, { "name": "PLpgSQL", "bytes": "4032" }, { "name": "R", "bytes": "6576" }, { "name": "TSQL", "bytes": "1637669" } ], "symlink_target": "" }
<?php namespace test\i\d; class a { }
{ "content_hash": "7ec1492924409448a29a332294a64d39", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 19, "avg_line_length": 12.333333333333334, "alnum_prop": 0.6486486486486487, "repo_name": "theosyspe/levent_01", "id": "94197b710bc912328ef44ae3afb0041f31fe3a15", "size": "37", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/ZF2/bin/test/i/d/a.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "1045" }, { "name": "PHP", "bytes": "11366" } ], "symlink_target": "" }
'use strict'; const Generator = require('yeoman-generator'); const chalk = require('chalk'); const yosay = require('yosay'); module.exports = class extends Generator { prompting() { // Have Yeoman greet the user. this.log(yosay( 'Welcome to the primo ' + chalk.red('generator-swagger-es-6') + ' generator!' )); const prompts = [{ type: 'input', name: 'name', message: 'Your project name.', default: this.appname }, { type: 'input', name: 'author', message: 'Your name.', store: true }, { type: 'input', name: 'description', message: 'Write a description.', default: '' }, { type: 'input', name: 'git', message: 'Your git repository.', default: '' }, { type: 'confirm', name: 'auth', message: 'Would you an authentication boilerplate?' }, { type: 'confirm', name: 'eslint', message: 'Would you like to enable eslint with airbnb config?' }, { type: 'checkbox', name: 'CI', message: 'Which CI\'s would you like to use?', choices: [{ name: 'travis', value: 'Travis-CI', checked: false }, { name: 'appveyor', value: 'Appveyor', checked: false }] }, { type: 'confirm', name: 'docker', message: 'Would you like to deploy with docker?' }, { type: 'confirm', name: 'heroku', message: 'Initialize Procfile for heroku?' }]; return this.prompt(prompts).then(props => { // To access props later use this.props.someAnswer; this.props = props; }); } writing() { let excludeFiles = []; if (!this.props.auth) { excludeFiles.push(...[ '**/src/auth/**/*', '**/src/test/controllers/auth.js', '**/src/test/controllers/user.js', '**/src/test/models/user.js', '**/src/models/user.js', '**/src/api/controllers/auth.js', '**/src/api/controllers/user.js' ]); } const copyOptions = excludeFiles.length === 0 ? null : { globOptions: { ignore: excludeFiles } }; this.fs.copy( this.templatePath('gitignore'), this.destinationPath('.gitignore') ); if (this.props.eslint) { this.fs.copy( this.templatePath('editorconfig'), this.destinationPath('.editorconfig') ); this.fs.copy( this.templatePath('eslintrc.js'), this.destinationPath('.eslintrc.js') ); } this.fs.copy( this.templatePath('codeclimate.yml'), this.destinationPath('.codeclimate.yml') ); this.fs.copyTpl( this.templatePath('src/'), this.destinationPath('src/'), { auth: this.props.auth }, null, copyOptions ); this.fs.copyTpl( this.templatePath('_package.json'), this.destinationPath('package.json'), { name: this.props.name, author: this.props.author, description: this.props.description, git: this.props.git, auth: this.props.auth, eslint: this.props.eslint, travis: this.props.CI && this.props.CI.includes('Travis-CI') } ); this.fs.copyTpl( this.templatePath('_gulpfile.babel.js'), this.destinationPath('gulpfile.babel.js'), { eslint: this.props.eslint } ); this.fs.copy( this.templatePath('_mocha.conf.js'), this.destinationPath('mocha.conf.js') ); if (this.props.docker) { this.fs.copyTpl( this.templatePath('_Dockerfile'), this.destinationPath('Dockerfile'), { cwd: `${process.cwd()}` } ); this.fs.copyTpl( this.templatePath('_docker-compose.yml'), this.destinationPath('docker-compose.yml'), { cwd: `${process.cwd()}` } ); this.fs.copy( this.templatePath('_env'), this.destinationPath('.env') ); } if (this.props.heroku) { this.fs.copy( this.templatePath('_Procfile'), this.destinationPath('Procfile') ); } this.fs.copyTpl( this.templatePath('_README.md'), this.destinationPath('README.md'), { git: this.props.git, name: this.props.name, repoName: this.parseGitReopName(this.props.git), docker: this.props.docker, travis: this.props.CI && this.props.CI.includes('Travis-CI'), appveyor: this.props.CI && this.props.CI.includes('Appveyor'), eslint: this.props.eslint } ); if (this.props.CI && this.props.CI.includes('Travis-CI')) { this.fs.copy( this.templatePath('_travis.yml'), this.destinationPath('.travis.yml') ); } if (this.props.CI && this.props.CI.includes('Appveyor')) { this.fs.copy( this.templatePath('_appveyor.yml'), this.destinationPath('appveyor.yml') ); } } parseGitReopName(git) { var regex = new RegExp(/(?:\.[a-z]+[\:|\/])(.+)(?:\.git)/); // eslint-disable-line no-useless-escape var match = String(git).match(regex); if (match) { return match[1]; } return ''; } install() { this.installDependencies({ npm: true, bower: false, yarn: false }); } };
{ "content_hash": "38096cee846ab5748dd0c8bd054c76f7", "timestamp": "", "source": "github", "line_count": 210, "max_line_length": 104, "avg_line_length": 25.561904761904763, "alnum_prop": 0.5406110283159463, "repo_name": "Eskalol/generator-swagger-es-6", "id": "e631f50ef30655f192fb8716b43a85e3076acd0e", "size": "5368", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "generators/app/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "69787" } ], "symlink_target": "" }
package org.ehcache.clustered.common.internal.messages; import org.ehcache.clustered.common.internal.exceptions.ClusterException; import org.ehcache.clustered.common.internal.store.Util; import org.terracotta.runnel.Struct; import org.terracotta.runnel.StructBuilder; import org.terracotta.runnel.decoding.Enm; import org.terracotta.runnel.decoding.StructDecoder; import org.terracotta.runnel.encoding.StructEncoder; import org.terracotta.runnel.encoding.StructEncoderFunction; import java.nio.ByteBuffer; import static java.nio.ByteBuffer.wrap; import static org.ehcache.clustered.common.internal.messages.ChainCodec.CHAIN_STRUCT; import static org.ehcache.clustered.common.internal.messages.EhcacheEntityResponse.AllInvalidationDone; import static org.ehcache.clustered.common.internal.messages.EhcacheEntityResponse.ClientInvalidateAll; import static org.ehcache.clustered.common.internal.messages.EhcacheEntityResponse.ClientInvalidateHash; import static org.ehcache.clustered.common.internal.messages.EhcacheEntityResponse.HashInvalidationDone; import static org.ehcache.clustered.common.internal.messages.EhcacheEntityResponse.ServerInvalidateHash; import static org.ehcache.clustered.common.internal.messages.EhcacheEntityResponse.MapValue; import static org.ehcache.clustered.common.internal.messages.EhcacheResponseType.EHCACHE_RESPONSE_TYPES_ENUM_MAPPING; import static org.ehcache.clustered.common.internal.messages.EhcacheResponseType.RESPONSE_TYPE_FIELD_INDEX; import static org.ehcache.clustered.common.internal.messages.EhcacheResponseType.RESPONSE_TYPE_FIELD_NAME; import static org.ehcache.clustered.common.internal.messages.MessageCodecUtils.KEY_FIELD; import static org.ehcache.clustered.common.internal.messages.MessageCodecUtils.SERVER_STORE_NAME_FIELD; public class ResponseCodec { private static final String EXCEPTION_FIELD = "exception"; private static final String INVALIDATION_ID_FIELD = "invalidationId"; private static final String CHAIN_FIELD = "chain"; private static final String MAP_VALUE_FIELD = "mapValue"; private final ExceptionCodec exceptionCodec = new ExceptionCodec(); private static final Struct SUCCESS_RESPONSE_STRUCT = StructBuilder.newStructBuilder() .enm(RESPONSE_TYPE_FIELD_NAME, RESPONSE_TYPE_FIELD_INDEX, EHCACHE_RESPONSE_TYPES_ENUM_MAPPING) .build(); private static final Struct FAILURE_RESPONSE_STRUCT = StructBuilder.newStructBuilder() .enm(RESPONSE_TYPE_FIELD_NAME, RESPONSE_TYPE_FIELD_INDEX, EHCACHE_RESPONSE_TYPES_ENUM_MAPPING) .struct(EXCEPTION_FIELD, 20, ExceptionCodec.EXCEPTION_STRUCT) .build(); private static final Struct GET_RESPONSE_STRUCT = StructBuilder.newStructBuilder() .enm(RESPONSE_TYPE_FIELD_NAME, RESPONSE_TYPE_FIELD_INDEX, EHCACHE_RESPONSE_TYPES_ENUM_MAPPING) .struct(CHAIN_FIELD, 20, CHAIN_STRUCT) .build(); private static final Struct HASH_INVALIDATION_DONE_RESPONSE_STRUCT = StructBuilder.newStructBuilder() .enm(RESPONSE_TYPE_FIELD_NAME, RESPONSE_TYPE_FIELD_INDEX, EHCACHE_RESPONSE_TYPES_ENUM_MAPPING) .string(SERVER_STORE_NAME_FIELD, 20) .int64(KEY_FIELD, 30) .build(); private static final Struct ALL_INVALIDATION_DONE_RESPONSE_STRUCT = StructBuilder.newStructBuilder() .enm(RESPONSE_TYPE_FIELD_NAME, RESPONSE_TYPE_FIELD_INDEX, EHCACHE_RESPONSE_TYPES_ENUM_MAPPING) .string(SERVER_STORE_NAME_FIELD, 20) .build(); private static final Struct CLIENT_INVALIDATE_HASH_RESPONSE_STRUCT = StructBuilder.newStructBuilder() .enm(RESPONSE_TYPE_FIELD_NAME, RESPONSE_TYPE_FIELD_INDEX, EHCACHE_RESPONSE_TYPES_ENUM_MAPPING) .string(SERVER_STORE_NAME_FIELD, 20) .int64(KEY_FIELD, 30) .int32(INVALIDATION_ID_FIELD, 40) .build(); private static final Struct CLIENT_INVALIDATE_ALL_RESPONSE_STRUCT = StructBuilder.newStructBuilder() .enm(RESPONSE_TYPE_FIELD_NAME, RESPONSE_TYPE_FIELD_INDEX, EHCACHE_RESPONSE_TYPES_ENUM_MAPPING) .string(SERVER_STORE_NAME_FIELD, 20) .int32(INVALIDATION_ID_FIELD, 30) .build(); private static final Struct SERVER_INVALIDATE_HASH_RESPONSE_STRUCT = StructBuilder.newStructBuilder() .enm(RESPONSE_TYPE_FIELD_NAME, RESPONSE_TYPE_FIELD_INDEX, EHCACHE_RESPONSE_TYPES_ENUM_MAPPING) .string(SERVER_STORE_NAME_FIELD, 20) .int64(KEY_FIELD, 30) .build(); private static final Struct MAP_VALUE_RESPONSE_STRUCT = StructBuilder.newStructBuilder() .enm(RESPONSE_TYPE_FIELD_NAME, RESPONSE_TYPE_FIELD_INDEX, EHCACHE_RESPONSE_TYPES_ENUM_MAPPING) .byteBuffer(MAP_VALUE_FIELD, 20) .build(); private final ChainCodec chainCodec; public ResponseCodec() { this.chainCodec = new ChainCodec(); } public byte[] encode(EhcacheEntityResponse response) { switch (response.getResponseType()) { case FAILURE: final EhcacheEntityResponse.Failure failure = (EhcacheEntityResponse.Failure)response; return FAILURE_RESPONSE_STRUCT.encoder() .enm(RESPONSE_TYPE_FIELD_NAME, failure.getResponseType()) .struct(EXCEPTION_FIELD, new StructEncoderFunction<StructEncoder<StructEncoder<Void>>>() { @Override public void encode(StructEncoder<StructEncoder<Void>> encoder) { exceptionCodec.encode(encoder, failure.getCause()); } }) .encode().array(); case SUCCESS: return SUCCESS_RESPONSE_STRUCT.encoder() .enm(RESPONSE_TYPE_FIELD_NAME, response.getResponseType()) .encode().array(); case GET_RESPONSE: final EhcacheEntityResponse.GetResponse getResponse = (EhcacheEntityResponse.GetResponse)response; return GET_RESPONSE_STRUCT.encoder() .enm(RESPONSE_TYPE_FIELD_NAME, getResponse.getResponseType()) .struct(CHAIN_FIELD, new StructEncoderFunction<StructEncoder<StructEncoder<Void>>>() { @Override public void encode(StructEncoder<StructEncoder<Void>> encoder) { chainCodec.encode(encoder, getResponse.getChain()); } }) .encode().array(); case HASH_INVALIDATION_DONE: { HashInvalidationDone hashInvalidationDone = (HashInvalidationDone) response; return HASH_INVALIDATION_DONE_RESPONSE_STRUCT.encoder() .enm(RESPONSE_TYPE_FIELD_NAME, hashInvalidationDone.getResponseType()) .string(SERVER_STORE_NAME_FIELD, hashInvalidationDone.getCacheId()) .int64(KEY_FIELD, hashInvalidationDone.getKey()) .encode().array(); } case ALL_INVALIDATION_DONE: { AllInvalidationDone allInvalidationDone = (AllInvalidationDone) response; return ALL_INVALIDATION_DONE_RESPONSE_STRUCT.encoder() .enm(RESPONSE_TYPE_FIELD_NAME, allInvalidationDone.getResponseType()) .string(SERVER_STORE_NAME_FIELD, allInvalidationDone.getCacheId()) .encode().array(); } case CLIENT_INVALIDATE_HASH: { ClientInvalidateHash clientInvalidateHash = (ClientInvalidateHash) response; return CLIENT_INVALIDATE_HASH_RESPONSE_STRUCT.encoder() .enm(RESPONSE_TYPE_FIELD_NAME, clientInvalidateHash.getResponseType()) .string(SERVER_STORE_NAME_FIELD, clientInvalidateHash.getCacheId()) .int64(KEY_FIELD, clientInvalidateHash.getKey()) .int32(INVALIDATION_ID_FIELD, clientInvalidateHash.getInvalidationId()) .encode().array(); } case CLIENT_INVALIDATE_ALL: { ClientInvalidateAll clientInvalidateAll = (ClientInvalidateAll) response; return CLIENT_INVALIDATE_ALL_RESPONSE_STRUCT.encoder() .enm(RESPONSE_TYPE_FIELD_NAME, clientInvalidateAll.getResponseType()) .string(SERVER_STORE_NAME_FIELD, clientInvalidateAll.getCacheId()) .int32(INVALIDATION_ID_FIELD, clientInvalidateAll.getInvalidationId()) .encode().array(); } case SERVER_INVALIDATE_HASH: { ServerInvalidateHash serverInvalidateHash = (ServerInvalidateHash) response; return SERVER_INVALIDATE_HASH_RESPONSE_STRUCT.encoder() .enm(RESPONSE_TYPE_FIELD_NAME, serverInvalidateHash.getResponseType()) .string(SERVER_STORE_NAME_FIELD, serverInvalidateHash.getCacheId()) .int64(KEY_FIELD, serverInvalidateHash.getKey()) .encode().array(); } case MAP_VALUE: { MapValue mapValue = (MapValue) response; byte[] encodedMapValue = Util.marshall(mapValue.getValue()); return MAP_VALUE_RESPONSE_STRUCT.encoder() .enm(RESPONSE_TYPE_FIELD_NAME, mapValue.getResponseType()) .byteBuffer(MAP_VALUE_FIELD, wrap(encodedMapValue)) .encode().array(); } default: throw new UnsupportedOperationException("The operation is not supported : " + response.getResponseType()); } } public EhcacheEntityResponse decode(byte[] payload) { ByteBuffer buffer = wrap(payload); StructDecoder<Void> decoder = SUCCESS_RESPONSE_STRUCT.decoder(buffer); Enm<EhcacheResponseType> opCodeEnm = decoder.enm(RESPONSE_TYPE_FIELD_NAME); if (!opCodeEnm.isFound()) { throw new AssertionError("Got a response without an opCode"); } if (!opCodeEnm.isValid()) { // Need to ignore the response here as we do not understand its type - coming from the future? return null; } EhcacheResponseType opCode = opCodeEnm.get(); buffer.rewind(); switch (opCode) { case SUCCESS: return EhcacheEntityResponse.Success.INSTANCE; case FAILURE: decoder = FAILURE_RESPONSE_STRUCT.decoder(buffer); ClusterException exception = exceptionCodec.decode(decoder.struct(EXCEPTION_FIELD)); return new EhcacheEntityResponse.Failure(exception.withClientStackTrace()); case GET_RESPONSE: decoder = GET_RESPONSE_STRUCT.decoder(buffer); return new EhcacheEntityResponse.GetResponse(chainCodec.decode(decoder.struct(CHAIN_FIELD))); case HASH_INVALIDATION_DONE: { decoder = HASH_INVALIDATION_DONE_RESPONSE_STRUCT.decoder(buffer); String cacheId = decoder.string(SERVER_STORE_NAME_FIELD); long key = decoder.int64(KEY_FIELD); return EhcacheEntityResponse.hashInvalidationDone(cacheId, key); } case ALL_INVALIDATION_DONE: { decoder = ALL_INVALIDATION_DONE_RESPONSE_STRUCT.decoder(buffer); String cacheId = decoder.string(SERVER_STORE_NAME_FIELD); return EhcacheEntityResponse.allInvalidationDone(cacheId); } case CLIENT_INVALIDATE_HASH: { decoder = CLIENT_INVALIDATE_HASH_RESPONSE_STRUCT.decoder(buffer); String cacheId = decoder.string(SERVER_STORE_NAME_FIELD); long key = decoder.int64(KEY_FIELD); int invalidationId = decoder.int32(INVALIDATION_ID_FIELD); return EhcacheEntityResponse.clientInvalidateHash(cacheId, key, invalidationId); } case CLIENT_INVALIDATE_ALL: { decoder = CLIENT_INVALIDATE_ALL_RESPONSE_STRUCT.decoder(buffer); String cacheId = decoder.string(SERVER_STORE_NAME_FIELD); int invalidationId = decoder.int32(INVALIDATION_ID_FIELD); return EhcacheEntityResponse.clientInvalidateAll(cacheId, invalidationId); } case SERVER_INVALIDATE_HASH: { decoder = SERVER_INVALIDATE_HASH_RESPONSE_STRUCT.decoder(buffer); String cacheId = decoder.string(SERVER_STORE_NAME_FIELD); long key = decoder.int64(KEY_FIELD); return EhcacheEntityResponse.serverInvalidateHash(cacheId, key); } case MAP_VALUE: { decoder = MAP_VALUE_RESPONSE_STRUCT.decoder(buffer); return EhcacheEntityResponse.mapValue(Util.unmarshall(decoder.byteBuffer(MAP_VALUE_FIELD))); } default: throw new UnsupportedOperationException("The operation is not supported with opCode : " + opCode); } } }
{ "content_hash": "7b218529b101c0d59147ff49da4fd054", "timestamp": "", "source": "github", "line_count": 230, "max_line_length": 117, "avg_line_length": 51.243478260869566, "alnum_prop": 0.7280671983709486, "repo_name": "akomakom/ehcache3", "id": "b1919369230966286a0b232d591e015e58aba397", "size": "12380", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/ResponseCodec.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "18215" }, { "name": "Java", "bytes": "6946029" } ], "symlink_target": "" }
namespace Microsoft.Azure.Commands.Management.DeviceProvisioningServices.Models { using Microsoft.Rest.Azure; using Newtonsoft.Json; /// <summary> /// Description of the response of the verification code. /// </summary> public partial class PSVerificationCodeResponse : IResource { /// <summary> /// Gets the property of ResourceGroupName /// </summary> public string ResourceGroupName { get { return IotDpsUtils.GetResourceGroupName(Id); } } /// <summary> /// Gets the property of Iot Dps Name /// </summary> public string Name { get { return IotDpsUtils.GetIotDpsName(Id); } } /// <summary> /// Gets name of certificate. /// </summary> [JsonProperty(PropertyName = "name")] public string CertificateName { get; private set; } /// <summary> /// Gets request etag. /// </summary> [JsonProperty(PropertyName = "etag")] public string Etag { get; private set; } /// <summary> /// Gets the resource identifier. /// </summary> [JsonProperty(PropertyName = "id")] public string Id { get; private set; } /// <summary> /// Gets the resource type. /// </summary> [JsonProperty(PropertyName = "type")] public string Type { get; private set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "properties")] public PSVerificationCodeResponseProperties Properties { get; set; } } }
{ "content_hash": "45eb89a0a6268f753426e91fc1eeb528", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 79, "avg_line_length": 27.580645161290324, "alnum_prop": 0.5350877192982456, "repo_name": "ClogenyTechnologies/azure-powershell", "id": "302dd2a7d1c45f13e3cd6516d50988476ba6e396", "size": "2466", "binary": false, "copies": "16", "ref": "refs/heads/master", "path": "src/ResourceManager/DeviceProvisioningServices/Commands.DeviceProvisioningServices/Models/PSVerificationCodeResponse.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "14332261" }, { "name": "JavaScript", "bytes": "4979" }, { "name": "PHP", "bytes": "41" }, { "name": "PowerShell", "bytes": "590227" }, { "name": "Python", "bytes": "20483" }, { "name": "Shell", "bytes": "16102" } ], "symlink_target": "" }
/** * Automatically generated file. Please do not edit. * @author Highcharts Config Generator by Karasiq * @see [[http://api.highcharts.com/highmaps]] */ package com.highmaps.config import scalajs.js, js.`|` import com.highcharts.CleanJsObject import com.highcharts.HighchartsUtils._ /** * @note JavaScript name: <code>plotOptions-candlestick-states-select</code> */ @js.annotation.ScalaJSDefined class PlotOptionsCandlestickStatesSelect extends com.highcharts.HighchartsGenericObject { /** * <p>A specific color for the selected point.</p> * @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/maps/plotoptions/series-states-hover/">Hover options</a> */ val color: js.UndefOr[String | js.Object] = js.undefined /** * <p>A specific border color for the selected point.</p> */ val borderColor: js.UndefOr[String | js.Object] = js.undefined /** * <p>Animation setting for hovering the graph in line-type series.</p> * @since 5.0.8 */ val animation: js.UndefOr[Boolean | js.Object] = js.undefined /** * <p>Enable separate styles for the hovered series to visualize that * the user hovers either the series itself or the legend. .</p> * @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-states-hover-enabled/">Line</a> <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-states-hover-enabled-column/">Column</a> <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-states-hover-enabled-pie/">Pie</a> * @since 1.2 */ val enabled: js.UndefOr[Boolean] = js.undefined /** * <p>The border width of the point in this state</p> */ val borderWidth: js.UndefOr[Double] = js.undefined } object PlotOptionsCandlestickStatesSelect { /** * @param color <p>A specific color for the selected point.</p> * @param borderColor <p>A specific border color for the selected point.</p> * @param animation <p>Animation setting for hovering the graph in line-type series.</p> * @param enabled <p>Enable separate styles for the hovered series to visualize that. the user hovers either the series itself or the legend. .</p> * @param borderWidth <p>The border width of the point in this state</p> */ def apply(color: js.UndefOr[String | js.Object] = js.undefined, borderColor: js.UndefOr[String | js.Object] = js.undefined, animation: js.UndefOr[Boolean | js.Object] = js.undefined, enabled: js.UndefOr[Boolean] = js.undefined, borderWidth: js.UndefOr[Double] = js.undefined): PlotOptionsCandlestickStatesSelect = { val colorOuter: js.UndefOr[String | js.Object] = color val borderColorOuter: js.UndefOr[String | js.Object] = borderColor val animationOuter: js.UndefOr[Boolean | js.Object] = animation val enabledOuter: js.UndefOr[Boolean] = enabled val borderWidthOuter: js.UndefOr[Double] = borderWidth com.highcharts.HighchartsGenericObject.toCleanObject(new PlotOptionsCandlestickStatesSelect { override val color: js.UndefOr[String | js.Object] = colorOuter override val borderColor: js.UndefOr[String | js.Object] = borderColorOuter override val animation: js.UndefOr[Boolean | js.Object] = animationOuter override val enabled: js.UndefOr[Boolean] = enabledOuter override val borderWidth: js.UndefOr[Double] = borderWidthOuter }) } }
{ "content_hash": "891fceab4669bc450b788836076e5dcb", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 317, "avg_line_length": 48.64383561643836, "alnum_prop": 0.7271191213742608, "repo_name": "Karasiq/scalajs-highcharts", "id": "08dffd062cd99921443b9cb4372d24340041d8a5", "size": "3551", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/com/highmaps/config/PlotOptionsCandlestickStatesSelect.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Scala", "bytes": "131509301" } ], "symlink_target": "" }
package org.robolectric.shadows; import static android.os.Build.VERSION_CODES.KITKAT; import static android.os.Build.VERSION_CODES.LOLLIPOP; import android.graphics.PixelFormat; import android.graphics.Point; import android.graphics.Rect; import android.util.DisplayMetrics; import android.view.Display; import android.view.DisplayAdjustments; import android.view.Surface; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.annotation.RealObject; @SuppressWarnings({"UnusedDeclaration"}) @Implements(value = Display.class) public class ShadowDisplay { @RealObject Display realObject; private int displayId; private String name = "Default Display"; private int flags; private int width = 480; private int height = 800; private int realWidth = 480; private int realHeight = 854; private float density = 1.5f; private int densityDpi = DisplayMetrics.DENSITY_HIGH; private float xdpi = 240.0f; private float ydpi = 240.0f; private float scaledDensity = 1.0f; private float refreshRate = 60.0f; private int rotation = Surface.ROTATION_0; private int pixelFormat = PixelFormat.RGBA_4444; @Implementation public int getHeight() { return height; } @Implementation public void getMetrics(DisplayMetrics outMetrics) { outMetrics.density = density; outMetrics.densityDpi = densityDpi; outMetrics.scaledDensity = scaledDensity; outMetrics.widthPixels = width; outMetrics.heightPixels = height; outMetrics.xdpi = xdpi; outMetrics.ydpi = ydpi; } @Implementation public void getRealMetrics(DisplayMetrics outMetrics) { getMetrics(outMetrics); outMetrics.widthPixels = realWidth; outMetrics.heightPixels = realHeight; } @Implementation public int getWidth() { return width; } @Implementation public int getDisplayId() { return displayId; } @Implementation public String getName() { return name; } @Implementation public int getFlags() { return flags; } @Implementation public float getRefreshRate() { return refreshRate; } @Implementation public int getOrientation() { return getRotation(); } @Implementation public int getRotation() { return rotation; } @Implementation public int getPixelFormat() { return pixelFormat; } @Implementation public void getCurrentSizeRange(Point outSmallestSize, Point outLargestSize) { int minimum = Math.min(width, height); int maximum = Math.max(width, height); outSmallestSize.set(minimum, minimum); outLargestSize.set(maximum, maximum); } @Implementation public void getSize(Point outSize) { outSize.set(width, height); } @Implementation public void getRectSize(Rect outSize) { outSize.set(0, 0, width, height); } @Implementation public void getRealSize(Point outSize) { outSize.set(realWidth, realHeight); } @Implementation(minSdk = LOLLIPOP) public int getState() { return Display.STATE_ON; } public float getDensity() { return density; } public void setDensity(float density) { this.density = density; } public int getDensityDpi() { return densityDpi; } public void setDensityDpi(int densityDpi) { this.densityDpi = densityDpi; } public float getXdpi() { return xdpi; } public void setXdpi(float xdpi) { this.xdpi = xdpi; } public float getYdpi() { return ydpi; } public void setYdpi(float ydpi) { this.ydpi = ydpi; } public float getScaledDensity() { return scaledDensity; } public void setScaledDensity(float scaledDensity) { this.scaledDensity = scaledDensity; } public void setDisplayId(int displayId) { this.displayId = displayId; } public void setName(String name) { this.name = name; } public void setFlags(int flags) { this.flags = flags; } public void setWidth(int width) { this.width = width; } public void setHeight(int height) { this.height = height; } public void setRealWidth(int realWidth) { this.realWidth = realWidth; } public void setRealHeight(int realHeight) { this.realHeight = realHeight; } public void setRefreshRate(float refreshRate) { this.refreshRate = refreshRate; } public void setRotation(int rotation) { this.rotation = rotation; } public void setPixelFormat(int pixelFormat) { this.pixelFormat = pixelFormat; } @Implementation(minSdk = KITKAT) public Object getDisplayAdjustments() { return new DisplayAdjustments(); } }
{ "content_hash": "ddf1b9e0af42ebc61fc7db4fa35c72ec", "timestamp": "", "source": "github", "line_count": 213, "max_line_length": 80, "avg_line_length": 21.55399061032864, "alnum_prop": 0.7105205837508168, "repo_name": "ChengCorp/robolectric", "id": "49214ef769fe699e580ec6568c88c605ddcffef7", "size": "4591", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "shadows/framework/src/main/java/org/robolectric/shadows/ShadowDisplay.java", "mode": "33188", "license": "mit", "language": [ { "name": "Groovy", "bytes": "27193" }, { "name": "Java", "bytes": "3928619" }, { "name": "Ruby", "bytes": "7830" }, { "name": "Shell", "bytes": "13666" } ], "symlink_target": "" }
gradle-examples =============== Gradle Build Examples
{ "content_hash": "34743e59c620af53b3f98cb69ceaee90", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 21, "avg_line_length": 13.75, "alnum_prop": 0.6, "repo_name": "ethankhall/gradle-examples", "id": "d751f2b3ba74abe74e69d96680b0503d881ad696", "size": "55", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Groovy", "bytes": "683" } ], "symlink_target": "" }
<br><br><br> <center> <h3>Average consumption by car brand</h3><br><br> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div"></div> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Brand', 'Average'], <?php foreach ($consumption as $consumption) { echo "[ '$consumption->brand', $consumption->avg],"; } ?> ]); var options = { }; var chart = new google.visualization.PieChart(document.getElementById('piechart1')); chart.draw(data, options); } </script> <div id="piechart1" style="width: 900px; height: 500px;"></div> <h3>Number of workplaces in given cities</h3><br><br> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div"></div> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['City', 'number'], <?php foreach ($workplace as $workplace) { echo "[ '$workplace->city', $workplace->pocet],"; } ?> ]); var options = { }; var chart = new google.visualization.PieChart(document.getElementById('piechart2')); chart.draw(data, options); } </script> <div id="piechart2" style="width: 900px; height: 500px;"></div> <h3>Frequencion of visited worklpaces</h3><br><br> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div"></div> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['workplace', 'pocet'], <?php foreach ($wrkplacefreq as $wrkplacefreq) { echo "[ '$wrkplacefreq->workplace', $wrkplacefreq->pocet],"; } ?> ]); var options = { }; var chart = new google.visualization.PieChart(document.getElementById('piechart3')); chart.draw(data, options); } </script> <div id="piechart3" style="width: 900px; height: 500px;"></div> <h3>Usage of vehicles</h3><br><br> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div"></div> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['workplace', 'pocet'], <?php foreach ($vehicles as $vehicles) { echo "[ '$vehicles->brand $vehicles->model', $vehicles->pocet],"; } ?> ]); var options = { }; var chart = new google.visualization.PieChart(document.getElementById('piechart4')); chart.draw(data, options); } </script> <div id="piechart4" style="width: 900px; height: 500px;"></div>
{ "content_hash": "be66e7ead5b226213521ce48a0d3cc98", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 96, "avg_line_length": 30.830882352941178, "alnum_prop": 0.5475792988313857, "repo_name": "vencelem/company", "id": "9ce57186e04b78e0c50dbdb8376075157225b3d5", "size": "4193", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/views/template/home.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "240" }, { "name": "CSS", "bytes": "85" }, { "name": "HTML", "bytes": "5633" }, { "name": "JavaScript", "bytes": "484" }, { "name": "PHP", "bytes": "1820415" } ], "symlink_target": "" }
<?php /** * Created by ra on 6/13/2015. */ td_demo_media::add_image_to_media_gallery('td_pic_13', "http://demo_content.tagdiv.com/Newspaper_6/tech/13.jpg"); td_demo_media::add_image_to_media_gallery('td_pic_14', "http://demo_content.tagdiv.com/Newspaper_6/tech/14.jpg"); //post images td_demo_media::add_image_to_media_gallery('td_pic_p1', "http://demo_content.tagdiv.com/Newspaper_6/tech/p1.jpg"); td_demo_media::add_image_to_media_gallery('td_pic_p2', "http://demo_content.tagdiv.com/Newspaper_6/tech/p2.jpg");
{ "content_hash": "8309388d8d754054df102b1988e49e90", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 130, "avg_line_length": 48.833333333333336, "alnum_prop": 0.6228668941979523, "repo_name": "tuanlibra/thptxuanang", "id": "8c49fe5b5cbb223a8580a225573b7c87fc091c9a", "size": "586", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "wp-content/themes/Newspaper/includes/demos/tech/td_media_4.php", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.calendarfx.app; import com.calendarfx.model.Calendar; import com.calendarfx.model.CalendarSource; import com.calendarfx.view.MonthSheetView; import de.jensd.fx.glyphs.weathericons.WeatherIcon; import de.jensd.fx.glyphs.weathericons.WeatherIconView; import javafx.application.Application; import javafx.beans.Observable; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.stage.Stage; import java.time.LocalDate; public class WeatherApp extends Application { @Override public void start(Stage primaryStage) throws Exception { Calendar zurich = new Calendar("Zurich"); CalendarSource calendarSource = new CalendarSource("Weather"); calendarSource.getCalendars().addAll(zurich); MonthSheetView sheetView = new MonthSheetView(); sheetView.setPadding(new Insets(20)); sheetView.setCellFactory(param -> new WeatherCell(param.getView(), param.getDate())); sheetView.getCalendarSources().setAll(calendarSource); sheetView.setContextMenu(null); Scene scene = new Scene(sheetView); primaryStage.setTitle("Weather Calendar"); primaryStage.setScene(scene); primaryStage.setWidth(1300); primaryStage.setHeight(1000); primaryStage.centerOnScreen(); primaryStage.show(); } public static void main(String[] args) { launch(args); } private static class WeatherCell extends MonthSheetView.SimpleDateCell { private WeatherIconView icon = new WeatherIconView(WeatherIcon.DAY_SUNNY); public WeatherCell(MonthSheetView view, LocalDate date) { super(view, date); weekNumberLabel.setVisible(false); if (getDate() != null) { switch ((int) (Math.random() * 9)) { case 0: icon = new WeatherIconView(WeatherIcon.DAY_SUNNY); break; case 1: icon = new WeatherIconView(WeatherIcon.DAY_RAIN); break; case 2: icon = new WeatherIconView(WeatherIcon.DAY_CLOUDY); break; case 3: icon = new WeatherIconView(WeatherIcon.DAY_FOG); break; case 4: icon = new WeatherIconView(WeatherIcon.DAY_LIGHTNING); break; case 5: icon = new WeatherIconView(WeatherIcon.DAY_HAIL); break; case 6: icon = new WeatherIconView(WeatherIcon.DAY_CLOUDY_HIGH); break; case 7: icon = new WeatherIconView(WeatherIcon.DAY_HAZE); break; default: icon = new WeatherIconView(WeatherIcon.DAY_SHOWERS); break; } } getChildren().add(icon); icon.setGlyphSize(14); updateFillColor(icon); WeatherIconView fIcon = icon; getView().getDateSelectionModel().getSelectedDates().addListener((Observable it) -> updateFillColor(fIcon)); } private void updateFillColor(WeatherIconView icon) { if (getDate() != null && getDate().equals(getView().getToday()) || getView().getDateSelectionModel().isSelected(getDate())) { icon.setFill(Color.WHITE); } else { icon.setFill(Color.CADETBLUE); } } @Override protected void layoutChildren() { Insets insets = getInsets(); double top = insets.getTop(); double bottom = insets.getBottom(); double left = insets.getLeft(); double right = insets.getRight(); double w = getWidth(); double h = getHeight(); double availableHeight = h - top - bottom; double ps1 = dayOfMonthLabel.prefWidth(-1); double ps2 = dayOfWeekLabel.prefWidth(-1); double ps3 = icon.prefWidth(-1); dayOfMonthLabel.resizeRelocate(left, top, ps1, availableHeight); dayOfWeekLabel.resizeRelocate(left + ps1, top, ps2, availableHeight); icon.resizeRelocate(w - right - ps3, (availableHeight - icon.prefHeight(-1)) / 2, ps3, availableHeight); } } }
{ "content_hash": "0a274a6d1694c0992e7bf68995295ece", "timestamp": "", "source": "github", "line_count": 127, "max_line_length": 137, "avg_line_length": 35.94488188976378, "alnum_prop": 0.5699890470974809, "repo_name": "dlemmermann/CalendarFX", "id": "d54819d62744cdb613b15eab320e7f2644587d0a", "size": "5214", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "CalendarFXWeather/src/main/java/com/calendarfx/app/WeatherApp.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "107051" }, { "name": "HTML", "bytes": "16749" }, { "name": "Java", "bytes": "2316831" } ], "symlink_target": "" }
/////// ////////////////// /////// PROJECT: MTA iLife - German Fun Reallife Gamemode /////// VERSION: 1.7.2 /////// DEVELOPERS: See DEVELOPERS.md in the top folder /////// LICENSE: See LICENSE.md in the top folder /////// ///////////////// ]] --[[ DoneastyShader = { [1] = dxCreateShader("res/shader/texture.fx"), [2] = dxCreateShader("res/shader/texture.fx"), [3] = dxCreateShader("res/shader/texture.fx"), [4] = dxCreateShader("res/shader/texture.fx"), [5] = dxCreateShader("res/shader/texture.fx"), [6] = dxCreateShader("res/shader/texture.fx"), [7] = dxCreateShader("res/shader/texture.fx"), [8] = dxCreateShader("res/shader/texture.fx"), [9] = dxCreateShader("res/shader/texture.fx"), [10] = dxCreateShader("res/shader/texture.fx") } DoneastyTextures = { [2] = "cj_don_post_2", [6] = "cj_don_post_1", [1] = "cj_binc_3", [7] = "base5_2", [4] = "cj_merc_logo", [3] = "cj_pizza_men1" } addEventHandler("onClientResourceStart", getRootElement(), function() triggerServerEvent("onClientRequestDoneastyObects", localPlayer) end) addEvent("onServerSendDoneastyObjects", true) addEventHandler("onServerSendDoneastyObjects", getRootElement(), function(obj) for k,v in ipairs(DoneastyShader) do if (DoneastyTextures[k]) then dxSetShaderValue(v,"Tex",dxCreateTexture("res/images/doneasty/"..k..".png")) for kk,vv in ipairs(obj) do engineRemoveShaderFromWorldTexture(billboardLarge, DoneastyTextures[k], vv) engineApplyShaderToWorldTexture(v, DoneastyTextures[k], vv, true) end end end end ) addEventHandler("onClientResourceStart", getRootElement(), function() DoneastyLaden = dxCreateShader("res/shader/texture.fx") dxSetShaderValue(DoneastyLaden,"Tex",dxCreateTexture("res/images/doneasty/banner.png")) engineApplyShaderToWorldTexture(DoneastyLaden, "bailbonds1_lan", nil, true) end ) function renderDoneasty() local sx, sy = guiGetScreenSize() dxDrawImage((sx-616)/2, (sy-237)/2, 616, 237, "res/images/doneasty/11.png") end Doneasty = nil addEvent("DoneastyBook", true) addEventHandler("DoneastyBook", getRootElement(), function() if not(Doneatsy) then Doneasty = true addEventHandler("onClientRender", getRootElement(), renderDoneasty) hideInventoryGui() setTimer(function() removeEventHandler("onClientRender", getRootElement(),renderDoneasty) Doneasty = nil end, 6000, 1) end end )]]
{ "content_hash": "d941c0df255759c66efcaacf59cb9ba3", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 139, "avg_line_length": 32.13513513513514, "alnum_prop": 0.6984861227922624, "repo_name": "Noneatme/iLife-SA", "id": "86e7d374ae24ec1d7a61bc78d8a96ad2acb403bb", "size": "2383", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/World/doneasty.lua", "mode": "33188", "license": "mit", "language": [ { "name": "HLSL", "bytes": "12310" }, { "name": "Lua", "bytes": "3352030" } ], "symlink_target": "" }
package com.hotf.client.action; import net.customware.gwt.dispatch.shared.Action; import com.hotf.client.action.result.AccountResult; public class SaveAccountAction implements Action<AccountResult> { private AccountResult account; public SaveAccountAction() { super(); } public SaveAccountAction(AccountResult account) { super(); this.account = account; } /** * @return the account */ public AccountResult getAccount() { return account; } }
{ "content_hash": "8d9410c9ded0864ce7b4f4d0a86bb640", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 65, "avg_line_length": 18.37037037037037, "alnum_prop": 0.7016129032258065, "repo_name": "jeffgager/heroesofthefall", "id": "30d62bcef12e016d0ad497369252d194fbcf5415", "size": "496", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hotf/src/com/hotf/client/action/SaveAccountAction.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "81365" }, { "name": "Java", "bytes": "899142" }, { "name": "JavaScript", "bytes": "186378" }, { "name": "Python", "bytes": "91066" } ], "symlink_target": "" }