code
stringlengths 4
1.01M
| language
stringclasses 2
values |
|---|---|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactIconBase = require('react-icon-base');
var _reactIconBase2 = _interopRequireDefault(_reactIconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var FaHouzz = function FaHouzz(props) {
return _react2.default.createElement(
_reactIconBase2.default,
_extends({ viewBox: '0 0 40 40' }, props),
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'm19.9 26.6l11.5-6.6v13.2l-11.5 6.6v-13.2z m-11.4-6.6v13.2l11.4-6.6z m11.4-19.8v13.2l-11.4 6.6v-13.2z m0 13.2l11.5-6.6v13.2z' })
)
);
};
exports.default = FaHouzz;
module.exports = exports['default'];
|
Java
|
//===--- JumpDiagnostics.cpp - Protected scope jump analysis ------*- C++ -*-=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the JumpScopeChecker class, which is used to diagnose
// jumps that enter a protected scope in an invalid way.
//
//===----------------------------------------------------------------------===//
#include "clang/Sema/SemaInternal.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/StmtCXX.h"
#include "clang/AST/StmtObjC.h"
#include "llvm/ADT/BitVector.h"
using namespace clang;
namespace {
/// JumpScopeChecker - This object is used by Sema to diagnose invalid jumps
/// into VLA and other protected scopes. For example, this rejects:
/// goto L;
/// int a[n];
/// L:
///
class JumpScopeChecker {
Sema &S;
/// Permissive - True when recovering from errors, in which case precautions
/// are taken to handle incomplete scope information.
const bool Permissive;
/// GotoScope - This is a record that we use to keep track of all of the
/// scopes that are introduced by VLAs and other things that scope jumps like
/// gotos. This scope tree has nothing to do with the source scope tree,
/// because you can have multiple VLA scopes per compound statement, and most
/// compound statements don't introduce any scopes.
struct GotoScope {
/// ParentScope - The index in ScopeMap of the parent scope. This is 0 for
/// the parent scope is the function body.
unsigned ParentScope;
/// InDiag - The note to emit if there is a jump into this scope.
unsigned InDiag;
/// OutDiag - The note to emit if there is an indirect jump out
/// of this scope. Direct jumps always clean up their current scope
/// in an orderly way.
unsigned OutDiag;
/// Loc - Location to emit the diagnostic.
SourceLocation Loc;
GotoScope(unsigned parentScope, unsigned InDiag, unsigned OutDiag,
SourceLocation L)
: ParentScope(parentScope), InDiag(InDiag), OutDiag(OutDiag), Loc(L) {}
};
SmallVector<GotoScope, 48> Scopes;
llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
SmallVector<Stmt*, 16> Jumps;
SmallVector<IndirectGotoStmt*, 4> IndirectJumps;
SmallVector<LabelDecl*, 4> IndirectJumpTargets;
public:
JumpScopeChecker(Stmt *Body, Sema &S);
private:
void BuildScopeInformation(Decl *D, unsigned &ParentScope);
void BuildScopeInformation(VarDecl *D, const BlockDecl *BDecl,
unsigned &ParentScope);
void BuildScopeInformation(Stmt *S, unsigned &origParentScope);
void VerifyJumps();
void VerifyIndirectJumps();
void NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes);
void DiagnoseIndirectJump(IndirectGotoStmt *IG, unsigned IGScope,
LabelDecl *Target, unsigned TargetScope);
void CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
unsigned JumpDiag, unsigned JumpDiagWarning,
unsigned JumpDiagCXX98Compat);
void CheckGotoStmt(GotoStmt *GS);
unsigned GetDeepestCommonScope(unsigned A, unsigned B);
};
} // end anonymous namespace
#define CHECK_PERMISSIVE(x) (assert(Permissive || !(x)), (Permissive && (x)))
JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s)
: S(s), Permissive(s.hasAnyUnrecoverableErrorsInThisFunction()) {
// Add a scope entry for function scope.
Scopes.push_back(GotoScope(~0U, ~0U, ~0U, SourceLocation()));
// Build information for the top level compound statement, so that we have a
// defined scope record for every "goto" and label.
unsigned BodyParentScope = 0;
BuildScopeInformation(Body, BodyParentScope);
// Check that all jumps we saw are kosher.
VerifyJumps();
VerifyIndirectJumps();
}
/// GetDeepestCommonScope - Finds the innermost scope enclosing the
/// two scopes.
unsigned JumpScopeChecker::GetDeepestCommonScope(unsigned A, unsigned B) {
while (A != B) {
// Inner scopes are created after outer scopes and therefore have
// higher indices.
if (A < B) {
assert(Scopes[B].ParentScope < B);
B = Scopes[B].ParentScope;
} else {
assert(Scopes[A].ParentScope < A);
A = Scopes[A].ParentScope;
}
}
return A;
}
typedef std::pair<unsigned,unsigned> ScopePair;
/// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a
/// diagnostic that should be emitted if control goes over it. If not, return 0.
static ScopePair GetDiagForGotoScopeDecl(Sema &S, const Decl *D) {
if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
unsigned InDiag = 0;
unsigned OutDiag = 0;
if (VD->getType()->isVariablyModifiedType())
InDiag = diag::note_protected_by_vla;
if (VD->hasAttr<BlocksAttr>())
return ScopePair(diag::note_protected_by___block,
diag::note_exits___block);
if (VD->hasAttr<CleanupAttr>())
return ScopePair(diag::note_protected_by_cleanup,
diag::note_exits_cleanup);
if (VD->hasLocalStorage()) {
switch (VD->getType().isDestructedType()) {
case QualType::DK_objc_strong_lifetime:
return ScopePair(diag::note_protected_by_objc_strong_init,
diag::note_exits_objc_strong);
case QualType::DK_objc_weak_lifetime:
return ScopePair(diag::note_protected_by_objc_weak_init,
diag::note_exits_objc_weak);
case QualType::DK_cxx_destructor:
OutDiag = diag::note_exits_dtor;
break;
case QualType::DK_none:
break;
}
}
const Expr *Init = VD->getInit();
if (S.Context.getLangOpts().CPlusPlus && VD->hasLocalStorage() && Init) {
// C++11 [stmt.dcl]p3:
// A program that jumps from a point where a variable with automatic
// storage duration is not in scope to a point where it is in scope
// is ill-formed unless the variable has scalar type, class type with
// a trivial default constructor and a trivial destructor, a
// cv-qualified version of one of these types, or an array of one of
// the preceding types and is declared without an initializer.
// C++03 [stmt.dcl.p3:
// A program that jumps from a point where a local variable
// with automatic storage duration is not in scope to a point
// where it is in scope is ill-formed unless the variable has
// POD type and is declared without an initializer.
InDiag = diag::note_protected_by_variable_init;
// For a variable of (array of) class type declared without an
// initializer, we will have call-style initialization and the initializer
// will be the CXXConstructExpr with no intervening nodes.
if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
const CXXConstructorDecl *Ctor = CCE->getConstructor();
if (Ctor->isTrivial() && Ctor->isDefaultConstructor() &&
VD->getInitStyle() == VarDecl::CallInit) {
if (OutDiag)
InDiag = diag::note_protected_by_variable_nontriv_destructor;
else if (!Ctor->getParent()->isPOD())
InDiag = diag::note_protected_by_variable_non_pod;
else
InDiag = 0;
}
}
}
return ScopePair(InDiag, OutDiag);
}
if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
if (TD->getUnderlyingType()->isVariablyModifiedType())
return ScopePair(isa<TypedefDecl>(TD)
? diag::note_protected_by_vla_typedef
: diag::note_protected_by_vla_type_alias,
0);
}
return ScopePair(0U, 0U);
}
/// \brief Build scope information for a declaration that is part of a DeclStmt.
void JumpScopeChecker::BuildScopeInformation(Decl *D, unsigned &ParentScope) {
// If this decl causes a new scope, push and switch to it.
std::pair<unsigned,unsigned> Diags = GetDiagForGotoScopeDecl(S, D);
if (Diags.first || Diags.second) {
Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second,
D->getLocation()));
ParentScope = Scopes.size()-1;
}
// If the decl has an initializer, walk it with the potentially new
// scope we just installed.
if (VarDecl *VD = dyn_cast<VarDecl>(D))
if (Expr *Init = VD->getInit())
BuildScopeInformation(Init, ParentScope);
}
/// \brief Build scope information for a captured block literal variables.
void JumpScopeChecker::BuildScopeInformation(VarDecl *D,
const BlockDecl *BDecl,
unsigned &ParentScope) {
// exclude captured __block variables; there's no destructor
// associated with the block literal for them.
if (D->hasAttr<BlocksAttr>())
return;
QualType T = D->getType();
QualType::DestructionKind destructKind = T.isDestructedType();
if (destructKind != QualType::DK_none) {
std::pair<unsigned,unsigned> Diags;
switch (destructKind) {
case QualType::DK_cxx_destructor:
Diags = ScopePair(diag::note_enters_block_captures_cxx_obj,
diag::note_exits_block_captures_cxx_obj);
break;
case QualType::DK_objc_strong_lifetime:
Diags = ScopePair(diag::note_enters_block_captures_strong,
diag::note_exits_block_captures_strong);
break;
case QualType::DK_objc_weak_lifetime:
Diags = ScopePair(diag::note_enters_block_captures_weak,
diag::note_exits_block_captures_weak);
break;
case QualType::DK_none:
llvm_unreachable("non-lifetime captured variable");
}
SourceLocation Loc = D->getLocation();
if (Loc.isInvalid())
Loc = BDecl->getLocation();
Scopes.push_back(GotoScope(ParentScope,
Diags.first, Diags.second, Loc));
ParentScope = Scopes.size()-1;
}
}
/// BuildScopeInformation - The statements from CI to CE are known to form a
/// coherent VLA scope with a specified parent node. Walk through the
/// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
/// walking the AST as needed.
void JumpScopeChecker::BuildScopeInformation(Stmt *S,
unsigned &origParentScope) {
// If this is a statement, rather than an expression, scopes within it don't
// propagate out into the enclosing scope. Otherwise we have to worry
// about block literals, which have the lifetime of their enclosing statement.
unsigned independentParentScope = origParentScope;
unsigned &ParentScope = ((isa<Expr>(S) && !isa<StmtExpr>(S))
? origParentScope : independentParentScope);
unsigned StmtsToSkip = 0u;
// If we found a label, remember that it is in ParentScope scope.
switch (S->getStmtClass()) {
case Stmt::AddrLabelExprClass:
IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel());
break;
case Stmt::IndirectGotoStmtClass:
// "goto *&&lbl;" is a special case which we treat as equivalent
// to a normal goto. In addition, we don't calculate scope in the
// operand (to avoid recording the address-of-label use), which
// works only because of the restricted set of expressions which
// we detect as constant targets.
if (cast<IndirectGotoStmt>(S)->getConstantTarget()) {
LabelAndGotoScopes[S] = ParentScope;
Jumps.push_back(S);
return;
}
LabelAndGotoScopes[S] = ParentScope;
IndirectJumps.push_back(cast<IndirectGotoStmt>(S));
break;
case Stmt::SwitchStmtClass:
// Evaluate the C++17 init stmt and condition variable
// before entering the scope of the switch statement.
if (Stmt *Init = cast<SwitchStmt>(S)->getInit()) {
BuildScopeInformation(Init, ParentScope);
++StmtsToSkip;
}
if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) {
BuildScopeInformation(Var, ParentScope);
++StmtsToSkip;
}
// Fall through
case Stmt::GotoStmtClass:
// Remember both what scope a goto is in as well as the fact that we have
// it. This makes the second scan not have to walk the AST again.
LabelAndGotoScopes[S] = ParentScope;
Jumps.push_back(S);
break;
case Stmt::IfStmtClass: {
IfStmt *IS = cast<IfStmt>(S);
if (!(IS->isConstexpr() || IS->isObjCAvailabilityCheck()))
break;
unsigned Diag = IS->isConstexpr() ? diag::note_protected_by_constexpr_if
: diag::note_protected_by_if_available;
if (VarDecl *Var = IS->getConditionVariable())
BuildScopeInformation(Var, ParentScope);
// Cannot jump into the middle of the condition.
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope, Diag, 0, IS->getLocStart()));
BuildScopeInformation(IS->getCond(), NewParentScope);
// Jumps into either arm of an 'if constexpr' are not allowed.
NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope, Diag, 0, IS->getLocStart()));
BuildScopeInformation(IS->getThen(), NewParentScope);
if (Stmt *Else = IS->getElse()) {
NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope, Diag, 0, IS->getLocStart()));
BuildScopeInformation(Else, NewParentScope);
}
return;
}
case Stmt::CXXTryStmtClass: {
CXXTryStmt *TS = cast<CXXTryStmt>(S);
{
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_cxx_try,
diag::note_exits_cxx_try,
TS->getSourceRange().getBegin()));
if (Stmt *TryBlock = TS->getTryBlock())
BuildScopeInformation(TryBlock, NewParentScope);
}
// Jump from the catch into the try is not allowed either.
for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) {
CXXCatchStmt *CS = TS->getHandler(I);
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_cxx_catch,
diag::note_exits_cxx_catch,
CS->getSourceRange().getBegin()));
BuildScopeInformation(CS->getHandlerBlock(), NewParentScope);
}
return;
}
case Stmt::SEHTryStmtClass: {
SEHTryStmt *TS = cast<SEHTryStmt>(S);
{
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_seh_try,
diag::note_exits_seh_try,
TS->getSourceRange().getBegin()));
if (Stmt *TryBlock = TS->getTryBlock())
BuildScopeInformation(TryBlock, NewParentScope);
}
// Jump from __except or __finally into the __try are not allowed either.
if (SEHExceptStmt *Except = TS->getExceptHandler()) {
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_seh_except,
diag::note_exits_seh_except,
Except->getSourceRange().getBegin()));
BuildScopeInformation(Except->getBlock(), NewParentScope);
} else if (SEHFinallyStmt *Finally = TS->getFinallyHandler()) {
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_seh_finally,
diag::note_exits_seh_finally,
Finally->getSourceRange().getBegin()));
BuildScopeInformation(Finally->getBlock(), NewParentScope);
}
return;
}
case Stmt::DeclStmtClass: {
// If this is a declstmt with a VLA definition, it defines a scope from here
// to the end of the containing context.
DeclStmt *DS = cast<DeclStmt>(S);
// The decl statement creates a scope if any of the decls in it are VLAs
// or have the cleanup attribute.
for (auto *I : DS->decls())
BuildScopeInformation(I, origParentScope);
return;
}
case Stmt::ObjCAtTryStmtClass: {
// Disallow jumps into any part of an @try statement by pushing a scope and
// walking all sub-stmts in that scope.
ObjCAtTryStmt *AT = cast<ObjCAtTryStmt>(S);
// Recursively walk the AST for the @try part.
{
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_objc_try,
diag::note_exits_objc_try,
AT->getAtTryLoc()));
if (Stmt *TryPart = AT->getTryBody())
BuildScopeInformation(TryPart, NewParentScope);
}
// Jump from the catch to the finally or try is not valid.
for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) {
ObjCAtCatchStmt *AC = AT->getCatchStmt(I);
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_objc_catch,
diag::note_exits_objc_catch,
AC->getAtCatchLoc()));
// @catches are nested and it isn't
BuildScopeInformation(AC->getCatchBody(), NewParentScope);
}
// Jump from the finally to the try or catch is not valid.
if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_objc_finally,
diag::note_exits_objc_finally,
AF->getAtFinallyLoc()));
BuildScopeInformation(AF, NewParentScope);
}
return;
}
case Stmt::ObjCAtSynchronizedStmtClass: {
// Disallow jumps into the protected statement of an @synchronized, but
// allow jumps into the object expression it protects.
ObjCAtSynchronizedStmt *AS = cast<ObjCAtSynchronizedStmt>(S);
// Recursively walk the AST for the @synchronized object expr, it is
// evaluated in the normal scope.
BuildScopeInformation(AS->getSynchExpr(), ParentScope);
// Recursively walk the AST for the @synchronized part, protected by a new
// scope.
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_objc_synchronized,
diag::note_exits_objc_synchronized,
AS->getAtSynchronizedLoc()));
BuildScopeInformation(AS->getSynchBody(), NewParentScope);
return;
}
case Stmt::ObjCAutoreleasePoolStmtClass: {
// Disallow jumps into the protected statement of an @autoreleasepool.
ObjCAutoreleasePoolStmt *AS = cast<ObjCAutoreleasePoolStmt>(S);
// Recursively walk the AST for the @autoreleasepool part, protected by a
// new scope.
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_objc_autoreleasepool,
diag::note_exits_objc_autoreleasepool,
AS->getAtLoc()));
BuildScopeInformation(AS->getSubStmt(), NewParentScope);
return;
}
case Stmt::ExprWithCleanupsClass: {
// Disallow jumps past full-expressions that use blocks with
// non-trivial cleanups of their captures. This is theoretically
// implementable but a lot of work which we haven't felt up to doing.
ExprWithCleanups *EWC = cast<ExprWithCleanups>(S);
for (unsigned i = 0, e = EWC->getNumObjects(); i != e; ++i) {
const BlockDecl *BDecl = EWC->getObject(i);
for (const auto &CI : BDecl->captures()) {
VarDecl *variable = CI.getVariable();
BuildScopeInformation(variable, BDecl, origParentScope);
}
}
break;
}
case Stmt::MaterializeTemporaryExprClass: {
// Disallow jumps out of scopes containing temporaries lifetime-extended to
// automatic storage duration.
MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
if (MTE->getStorageDuration() == SD_Automatic) {
SmallVector<const Expr *, 4> CommaLHS;
SmallVector<SubobjectAdjustment, 4> Adjustments;
const Expr *ExtendedObject =
MTE->GetTemporaryExpr()->skipRValueSubobjectAdjustments(
CommaLHS, Adjustments);
if (ExtendedObject->getType().isDestructedType()) {
Scopes.push_back(GotoScope(ParentScope, 0,
diag::note_exits_temporary_dtor,
ExtendedObject->getExprLoc()));
origParentScope = Scopes.size()-1;
}
}
break;
}
case Stmt::CaseStmtClass:
case Stmt::DefaultStmtClass:
case Stmt::LabelStmtClass:
LabelAndGotoScopes[S] = ParentScope;
break;
default:
break;
}
for (Stmt *SubStmt : S->children()) {
if (!SubStmt)
continue;
if (StmtsToSkip) {
--StmtsToSkip;
continue;
}
// Cases, labels, and defaults aren't "scope parents". It's also
// important to handle these iteratively instead of recursively in
// order to avoid blowing out the stack.
while (true) {
Stmt *Next;
if (SwitchCase *SC = dyn_cast<SwitchCase>(SubStmt))
Next = SC->getSubStmt();
else if (LabelStmt *LS = dyn_cast<LabelStmt>(SubStmt))
Next = LS->getSubStmt();
else
break;
LabelAndGotoScopes[SubStmt] = ParentScope;
SubStmt = Next;
}
// Recursively walk the AST.
BuildScopeInformation(SubStmt, ParentScope);
}
}
/// VerifyJumps - Verify each element of the Jumps array to see if they are
/// valid, emitting diagnostics if not.
void JumpScopeChecker::VerifyJumps() {
while (!Jumps.empty()) {
Stmt *Jump = Jumps.pop_back_val();
// With a goto,
if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
// The label may not have a statement if it's coming from inline MS ASM.
if (GS->getLabel()->getStmt()) {
CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(),
diag::err_goto_into_protected_scope,
diag::ext_goto_into_protected_scope,
diag::warn_cxx98_compat_goto_into_protected_scope);
}
CheckGotoStmt(GS);
continue;
}
// We only get indirect gotos here when they have a constant target.
if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) {
LabelDecl *Target = IGS->getConstantTarget();
CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(),
diag::err_goto_into_protected_scope,
diag::ext_goto_into_protected_scope,
diag::warn_cxx98_compat_goto_into_protected_scope);
continue;
}
SwitchStmt *SS = cast<SwitchStmt>(Jump);
for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
SC = SC->getNextSwitchCase()) {
if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(SC)))
continue;
SourceLocation Loc;
if (CaseStmt *CS = dyn_cast<CaseStmt>(SC))
Loc = CS->getLocStart();
else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC))
Loc = DS->getLocStart();
else
Loc = SC->getLocStart();
CheckJump(SS, SC, Loc, diag::err_switch_into_protected_scope, 0,
diag::warn_cxx98_compat_switch_into_protected_scope);
}
}
}
/// VerifyIndirectJumps - Verify whether any possible indirect jump
/// might cross a protection boundary. Unlike direct jumps, indirect
/// jumps count cleanups as protection boundaries: since there's no
/// way to know where the jump is going, we can't implicitly run the
/// right cleanups the way we can with direct jumps.
///
/// Thus, an indirect jump is "trivial" if it bypasses no
/// initializations and no teardowns. More formally, an indirect jump
/// from A to B is trivial if the path out from A to DCA(A,B) is
/// trivial and the path in from DCA(A,B) to B is trivial, where
/// DCA(A,B) is the deepest common ancestor of A and B.
/// Jump-triviality is transitive but asymmetric.
///
/// A path in is trivial if none of the entered scopes have an InDiag.
/// A path out is trivial is none of the exited scopes have an OutDiag.
///
/// Under these definitions, this function checks that the indirect
/// jump between A and B is trivial for every indirect goto statement A
/// and every label B whose address was taken in the function.
void JumpScopeChecker::VerifyIndirectJumps() {
if (IndirectJumps.empty()) return;
// If there aren't any address-of-label expressions in this function,
// complain about the first indirect goto.
if (IndirectJumpTargets.empty()) {
S.Diag(IndirectJumps[0]->getGotoLoc(),
diag::err_indirect_goto_without_addrlabel);
return;
}
// Collect a single representative of every scope containing an
// indirect goto. For most code bases, this substantially cuts
// down on the number of jump sites we'll have to consider later.
typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope;
SmallVector<JumpScope, 32> JumpScopes;
{
llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap;
for (SmallVectorImpl<IndirectGotoStmt*>::iterator
I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) {
IndirectGotoStmt *IG = *I;
if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(IG)))
continue;
unsigned IGScope = LabelAndGotoScopes[IG];
IndirectGotoStmt *&Entry = JumpScopesMap[IGScope];
if (!Entry) Entry = IG;
}
JumpScopes.reserve(JumpScopesMap.size());
for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator
I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I)
JumpScopes.push_back(*I);
}
// Collect a single representative of every scope containing a
// label whose address was taken somewhere in the function.
// For most code bases, there will be only one such scope.
llvm::DenseMap<unsigned, LabelDecl*> TargetScopes;
for (SmallVectorImpl<LabelDecl*>::iterator
I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end();
I != E; ++I) {
LabelDecl *TheLabel = *I;
if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(TheLabel->getStmt())))
continue;
unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()];
LabelDecl *&Target = TargetScopes[LabelScope];
if (!Target) Target = TheLabel;
}
// For each target scope, make sure it's trivially reachable from
// every scope containing a jump site.
//
// A path between scopes always consists of exitting zero or more
// scopes, then entering zero or more scopes. We build a set of
// of scopes S from which the target scope can be trivially
// entered, then verify that every jump scope can be trivially
// exitted to reach a scope in S.
llvm::BitVector Reachable(Scopes.size(), false);
for (llvm::DenseMap<unsigned,LabelDecl*>::iterator
TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) {
unsigned TargetScope = TI->first;
LabelDecl *TargetLabel = TI->second;
Reachable.reset();
// Mark all the enclosing scopes from which you can safely jump
// into the target scope. 'Min' will end up being the index of
// the shallowest such scope.
unsigned Min = TargetScope;
while (true) {
Reachable.set(Min);
// Don't go beyond the outermost scope.
if (Min == 0) break;
// Stop if we can't trivially enter the current scope.
if (Scopes[Min].InDiag) break;
Min = Scopes[Min].ParentScope;
}
// Walk through all the jump sites, checking that they can trivially
// reach this label scope.
for (SmallVectorImpl<JumpScope>::iterator
I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) {
unsigned Scope = I->first;
// Walk out the "scope chain" for this scope, looking for a scope
// we've marked reachable. For well-formed code this amortizes
// to O(JumpScopes.size() / Scopes.size()): we only iterate
// when we see something unmarked, and in well-formed code we
// mark everything we iterate past.
bool IsReachable = false;
while (true) {
if (Reachable.test(Scope)) {
// If we find something reachable, mark all the scopes we just
// walked through as reachable.
for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope)
Reachable.set(S);
IsReachable = true;
break;
}
// Don't walk out if we've reached the top-level scope or we've
// gotten shallower than the shallowest reachable scope.
if (Scope == 0 || Scope < Min) break;
// Don't walk out through an out-diagnostic.
if (Scopes[Scope].OutDiag) break;
Scope = Scopes[Scope].ParentScope;
}
// Only diagnose if we didn't find something.
if (IsReachable) continue;
DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope);
}
}
}
/// Return true if a particular error+note combination must be downgraded to a
/// warning in Microsoft mode.
static bool IsMicrosoftJumpWarning(unsigned JumpDiag, unsigned InDiagNote) {
return (JumpDiag == diag::err_goto_into_protected_scope &&
(InDiagNote == diag::note_protected_by_variable_init ||
InDiagNote == diag::note_protected_by_variable_nontriv_destructor));
}
/// Return true if a particular note should be downgraded to a compatibility
/// warning in C++11 mode.
static bool IsCXX98CompatWarning(Sema &S, unsigned InDiagNote) {
return S.getLangOpts().CPlusPlus11 &&
InDiagNote == diag::note_protected_by_variable_non_pod;
}
/// Produce primary diagnostic for an indirect jump statement.
static void DiagnoseIndirectJumpStmt(Sema &S, IndirectGotoStmt *Jump,
LabelDecl *Target, bool &Diagnosed) {
if (Diagnosed)
return;
S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
Diagnosed = true;
}
/// Produce note diagnostics for a jump into a protected scope.
void JumpScopeChecker::NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes) {
if (CHECK_PERMISSIVE(ToScopes.empty()))
return;
for (unsigned I = 0, E = ToScopes.size(); I != E; ++I)
if (Scopes[ToScopes[I]].InDiag)
S.Diag(Scopes[ToScopes[I]].Loc, Scopes[ToScopes[I]].InDiag);
}
/// Diagnose an indirect jump which is known to cross scopes.
void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump,
unsigned JumpScope,
LabelDecl *Target,
unsigned TargetScope) {
if (CHECK_PERMISSIVE(JumpScope == TargetScope))
return;
unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope);
bool Diagnosed = false;
// Walk out the scope chain until we reach the common ancestor.
for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope)
if (Scopes[I].OutDiag) {
DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
S.Diag(Scopes[I].Loc, Scopes[I].OutDiag);
}
SmallVector<unsigned, 10> ToScopesCXX98Compat;
// Now walk into the scopes containing the label whose address was taken.
for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope)
if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
ToScopesCXX98Compat.push_back(I);
else if (Scopes[I].InDiag) {
DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
S.Diag(Scopes[I].Loc, Scopes[I].InDiag);
}
// Diagnose this jump if it would be ill-formed in C++98.
if (!Diagnosed && !ToScopesCXX98Compat.empty()) {
S.Diag(Jump->getGotoLoc(),
diag::warn_cxx98_compat_indirect_goto_in_protected_scope);
S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
NoteJumpIntoScopes(ToScopesCXX98Compat);
}
}
/// CheckJump - Validate that the specified jump statement is valid: that it is
/// jumping within or out of its current scope, not into a deeper one.
void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
unsigned JumpDiagError, unsigned JumpDiagWarning,
unsigned JumpDiagCXX98Compat) {
if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(From)))
return;
if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(To)))
return;
unsigned FromScope = LabelAndGotoScopes[From];
unsigned ToScope = LabelAndGotoScopes[To];
// Common case: exactly the same scope, which is fine.
if (FromScope == ToScope) return;
// Warn on gotos out of __finally blocks.
if (isa<GotoStmt>(From) || isa<IndirectGotoStmt>(From)) {
// If FromScope > ToScope, FromScope is more nested and the jump goes to a
// less nested scope. Check if it crosses a __finally along the way.
for (unsigned I = FromScope; I > ToScope; I = Scopes[I].ParentScope) {
if (Scopes[I].InDiag == diag::note_protected_by_seh_finally) {
S.Diag(From->getLocStart(), diag::warn_jump_out_of_seh_finally);
break;
}
}
}
unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope);
// It's okay to jump out from a nested scope.
if (CommonScope == ToScope) return;
// Pull out (and reverse) any scopes we might need to diagnose skipping.
SmallVector<unsigned, 10> ToScopesCXX98Compat;
SmallVector<unsigned, 10> ToScopesError;
SmallVector<unsigned, 10> ToScopesWarning;
for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope) {
if (S.getLangOpts().MSVCCompat && JumpDiagWarning != 0 &&
IsMicrosoftJumpWarning(JumpDiagError, Scopes[I].InDiag))
ToScopesWarning.push_back(I);
else if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
ToScopesCXX98Compat.push_back(I);
else if (Scopes[I].InDiag)
ToScopesError.push_back(I);
}
// Handle warnings.
if (!ToScopesWarning.empty()) {
S.Diag(DiagLoc, JumpDiagWarning);
NoteJumpIntoScopes(ToScopesWarning);
}
// Handle errors.
if (!ToScopesError.empty()) {
S.Diag(DiagLoc, JumpDiagError);
NoteJumpIntoScopes(ToScopesError);
}
// Handle -Wc++98-compat warnings if the jump is well-formed.
if (ToScopesError.empty() && !ToScopesCXX98Compat.empty()) {
S.Diag(DiagLoc, JumpDiagCXX98Compat);
NoteJumpIntoScopes(ToScopesCXX98Compat);
}
}
void JumpScopeChecker::CheckGotoStmt(GotoStmt *GS) {
if (GS->getLabel()->isMSAsmLabel()) {
S.Diag(GS->getGotoLoc(), diag::err_goto_ms_asm_label)
<< GS->getLabel()->getIdentifier();
S.Diag(GS->getLabel()->getLocation(), diag::note_goto_ms_asm_label)
<< GS->getLabel()->getIdentifier();
}
}
void Sema::DiagnoseInvalidJumps(Stmt *Body) {
(void)JumpScopeChecker(Body, *this);
}
|
Java
|
// Copyright 2009-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "trianglei.h"
#include "triangle_intersector_moeller.h"
#include "triangle_intersector_pluecker.h"
namespace embree
{
namespace isa
{
/*! Intersects M triangles with 1 ray */
template<int M, int Mx, bool filter>
struct TriangleMiIntersector1Moeller
{
typedef TriangleMi<M> Primitive;
typedef MoellerTrumboreIntersector1<Mx> Precalculations;
static __forceinline void intersect(const Precalculations& pre, RayHit& ray, IntersectContext* context, const Primitive& tri)
{
STAT3(normal.trav_prims,1,1,1);
Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
pre.intersect(ray,v0,v1,v2,/*UVIdentity<Mx>(),*/Intersect1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID()));
}
static __forceinline bool occluded(const Precalculations& pre, Ray& ray, IntersectContext* context, const Primitive& tri)
{
STAT3(shadow.trav_prims,1,1,1);
Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
return pre.intersect(ray,v0,v1,v2,/*UVIdentity<Mx>(),*/Occluded1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID()));
}
static __forceinline bool pointQuery(PointQuery* query, PointQueryContext* context, const Primitive& tri)
{
return PrimitivePointQuery1<Primitive>::pointQuery(query, context, tri);
}
};
/*! Intersects M triangles with K rays */
template<int M, int Mx, int K, bool filter>
struct TriangleMiIntersectorKMoeller
{
typedef TriangleMi<M> Primitive;
typedef MoellerTrumboreIntersectorK<Mx,K> Precalculations;
static __forceinline void intersect(const vbool<K>& valid_i, Precalculations& pre, RayHitK<K>& ray, IntersectContext* context, const Primitive& tri)
{
const Scene* scene = context->scene;
for (size_t i=0; i<Primitive::max_size(); i++)
{
if (!tri.valid(i)) break;
STAT3(normal.trav_prims,1,popcnt(valid_i),RayHitK<K>::size());
const Vec3vf<K> v0 = tri.template getVertex<0>(i,scene);
const Vec3vf<K> v1 = tri.template getVertex<1>(i,scene);
const Vec3vf<K> v2 = tri.template getVertex<2>(i,scene);
pre.intersectK(valid_i,ray,v0,v1,v2,/*UVIdentity<K>(),*/IntersectKEpilogM<M,K,filter>(ray,context,tri.geomID(),tri.primID(),i));
}
}
static __forceinline vbool<K> occluded(const vbool<K>& valid_i, Precalculations& pre, RayK<K>& ray, IntersectContext* context, const Primitive& tri)
{
vbool<K> valid0 = valid_i;
const Scene* scene = context->scene;
for (size_t i=0; i<Primitive::max_size(); i++)
{
if (!tri.valid(i)) break;
STAT3(shadow.trav_prims,1,popcnt(valid_i),RayHitK<K>::size());
const Vec3vf<K> v0 = tri.template getVertex<0>(i,scene);
const Vec3vf<K> v1 = tri.template getVertex<1>(i,scene);
const Vec3vf<K> v2 = tri.template getVertex<2>(i,scene);
pre.intersectK(valid0,ray,v0,v1,v2,/*UVIdentity<K>(),*/OccludedKEpilogM<M,K,filter>(valid0,ray,context,tri.geomID(),tri.primID(),i));
if (none(valid0)) break;
}
return !valid0;
}
static __forceinline void intersect(Precalculations& pre, RayHitK<K>& ray, size_t k, IntersectContext* context, const Primitive& tri)
{
STAT3(normal.trav_prims,1,1,1);
Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
pre.intersect(ray,k,v0,v1,v2,/*UVIdentity<Mx>(),*/Intersect1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID()));
}
static __forceinline bool occluded(Precalculations& pre, RayK<K>& ray, size_t k, IntersectContext* context, const Primitive& tri)
{
STAT3(shadow.trav_prims,1,1,1);
Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
return pre.intersect(ray,k,v0,v1,v2,/*UVIdentity<Mx>(),*/Occluded1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID()));
}
};
/*! Intersects M triangles with 1 ray */
template<int M, int Mx, bool filter>
struct TriangleMiIntersector1Pluecker
{
typedef TriangleMi<M> Primitive;
typedef PlueckerIntersector1<Mx> Precalculations;
static __forceinline void intersect(const Precalculations& pre, RayHit& ray, IntersectContext* context, const Primitive& tri)
{
STAT3(normal.trav_prims,1,1,1);
Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
pre.intersect(ray,v0,v1,v2,UVIdentity<Mx>(),Intersect1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID()));
}
static __forceinline bool occluded(const Precalculations& pre, Ray& ray, IntersectContext* context, const Primitive& tri)
{
STAT3(shadow.trav_prims,1,1,1);
Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
return pre.intersect(ray,v0,v1,v2,UVIdentity<Mx>(),Occluded1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID()));
}
static __forceinline bool pointQuery(PointQuery* query, PointQueryContext* context, const Primitive& tri)
{
return PrimitivePointQuery1<Primitive>::pointQuery(query, context, tri);
}
};
/*! Intersects M triangles with K rays */
template<int M, int Mx, int K, bool filter>
struct TriangleMiIntersectorKPluecker
{
typedef TriangleMi<M> Primitive;
typedef PlueckerIntersectorK<Mx,K> Precalculations;
static __forceinline void intersect(const vbool<K>& valid_i, Precalculations& pre, RayHitK<K>& ray, IntersectContext* context, const Primitive& tri)
{
const Scene* scene = context->scene;
for (size_t i=0; i<Primitive::max_size(); i++)
{
if (!tri.valid(i)) break;
STAT3(normal.trav_prims,1,popcnt(valid_i),RayHitK<K>::size());
const Vec3vf<K> v0 = tri.template getVertex<0>(i,scene);
const Vec3vf<K> v1 = tri.template getVertex<1>(i,scene);
const Vec3vf<K> v2 = tri.template getVertex<2>(i,scene);
pre.intersectK(valid_i,ray,v0,v1,v2,UVIdentity<K>(),IntersectKEpilogM<M,K,filter>(ray,context,tri.geomID(),tri.primID(),i));
}
}
static __forceinline vbool<K> occluded(const vbool<K>& valid_i, Precalculations& pre, RayK<K>& ray, IntersectContext* context, const Primitive& tri)
{
vbool<K> valid0 = valid_i;
const Scene* scene = context->scene;
for (size_t i=0; i<Primitive::max_size(); i++)
{
if (!tri.valid(i)) break;
STAT3(shadow.trav_prims,1,popcnt(valid_i),RayHitK<K>::size());
const Vec3vf<K> v0 = tri.template getVertex<0>(i,scene);
const Vec3vf<K> v1 = tri.template getVertex<1>(i,scene);
const Vec3vf<K> v2 = tri.template getVertex<2>(i,scene);
pre.intersectK(valid0,ray,v0,v1,v2,UVIdentity<K>(),OccludedKEpilogM<M,K,filter>(valid0,ray,context,tri.geomID(),tri.primID(),i));
if (none(valid0)) break;
}
return !valid0;
}
static __forceinline void intersect(Precalculations& pre, RayHitK<K>& ray, size_t k, IntersectContext* context, const Primitive& tri)
{
STAT3(normal.trav_prims,1,1,1);
Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
pre.intersect(ray,k,v0,v1,v2,UVIdentity<Mx>(),Intersect1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID()));
}
static __forceinline bool occluded(Precalculations& pre, RayK<K>& ray, size_t k, IntersectContext* context, const Primitive& tri)
{
STAT3(shadow.trav_prims,1,1,1);
Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
return pre.intersect(ray,k,v0,v1,v2,UVIdentity<Mx>(),Occluded1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID()));
}
};
/*! Intersects M motion blur triangles with 1 ray */
template<int M, int Mx, bool filter>
struct TriangleMiMBIntersector1Moeller
{
typedef TriangleMi<M> Primitive;
typedef MoellerTrumboreIntersector1<Mx> Precalculations;
/*! Intersect a ray with the M triangles and updates the hit. */
static __forceinline void intersect(const Precalculations& pre, RayHit& ray, IntersectContext* context, const Primitive& tri)
{
STAT3(normal.trav_prims,1,1,1);
Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time());
pre.intersect(ray,v0,v1,v2,/*UVIdentity<Mx>(),*/Intersect1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID()));
}
/*! Test if the ray is occluded by one of M triangles. */
static __forceinline bool occluded(const Precalculations& pre, Ray& ray, IntersectContext* context, const Primitive& tri)
{
STAT3(shadow.trav_prims,1,1,1);
Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time());
return pre.intersect(ray,v0,v1,v2,/*UVIdentity<Mx>(),*/Occluded1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID()));
}
static __forceinline bool pointQuery(PointQuery* query, PointQueryContext* context, const Primitive& tri)
{
return PrimitivePointQuery1<Primitive>::pointQuery(query, context, tri);
}
};
/*! Intersects M motion blur triangles with K rays. */
template<int M, int Mx, int K, bool filter>
struct TriangleMiMBIntersectorKMoeller
{
typedef TriangleMi<M> Primitive;
typedef MoellerTrumboreIntersectorK<Mx,K> Precalculations;
/*! Intersects K rays with M triangles. */
static __forceinline void intersect(const vbool<K>& valid_i, Precalculations& pre, RayHitK<K>& ray, IntersectContext* context, const TriangleMi<M>& tri)
{
for (size_t i=0; i<TriangleMi<M>::max_size(); i++)
{
if (!tri.valid(i)) break;
STAT3(normal.trav_prims,1,popcnt(valid_i),K);
Vec3vf<K> v0,v1,v2; tri.gather(valid_i,v0,v1,v2,i,context->scene,ray.time());
pre.intersectK(valid_i,ray,v0,v1,v2,/*UVIdentity<K>(),*/IntersectKEpilogM<M,K,filter>(ray,context,tri.geomID(),tri.primID(),i));
}
}
/*! Test for K rays if they are occluded by any of the M triangles. */
static __forceinline vbool<K> occluded(const vbool<K>& valid_i, Precalculations& pre, RayK<K>& ray, IntersectContext* context, const TriangleMi<M>& tri)
{
vbool<K> valid0 = valid_i;
for (size_t i=0; i<TriangleMi<M>::max_size(); i++)
{
if (!tri.valid(i)) break;
STAT3(shadow.trav_prims,1,popcnt(valid0),K);
Vec3vf<K> v0,v1,v2; tri.gather(valid_i,v0,v1,v2,i,context->scene,ray.time());
pre.intersectK(valid0,ray,v0,v1,v2,/*UVIdentity<K>(),*/OccludedKEpilogM<M,K,filter>(valid0,ray,context,tri.geomID(),tri.primID(),i));
if (none(valid0)) break;
}
return !valid0;
}
/*! Intersect a ray with M triangles and updates the hit. */
static __forceinline void intersect(Precalculations& pre, RayHitK<K>& ray, size_t k, IntersectContext* context, const TriangleMi<M>& tri)
{
STAT3(normal.trav_prims,1,1,1);
Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time()[k]);
pre.intersect(ray,k,v0,v1,v2,/*UVIdentity<Mx>(),*/Intersect1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID()));
}
/*! Test if the ray is occluded by one of the M triangles. */
static __forceinline bool occluded(Precalculations& pre, RayK<K>& ray, size_t k, IntersectContext* context, const TriangleMi<M>& tri)
{
STAT3(shadow.trav_prims,1,1,1);
Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time()[k]);
return pre.intersect(ray,k,v0,v1,v2,/*UVIdentity<Mx>(),*/Occluded1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID()));
}
};
/*! Intersects M motion blur triangles with 1 ray */
template<int M, int Mx, bool filter>
struct TriangleMiMBIntersector1Pluecker
{
typedef TriangleMi<M> Primitive;
typedef PlueckerIntersector1<Mx> Precalculations;
/*! Intersect a ray with the M triangles and updates the hit. */
static __forceinline void intersect(const Precalculations& pre, RayHit& ray, IntersectContext* context, const Primitive& tri)
{
STAT3(normal.trav_prims,1,1,1);
Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time());
pre.intersect(ray,v0,v1,v2,UVIdentity<Mx>(),Intersect1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID()));
}
/*! Test if the ray is occluded by one of M triangles. */
static __forceinline bool occluded(const Precalculations& pre, Ray& ray, IntersectContext* context, const Primitive& tri)
{
STAT3(shadow.trav_prims,1,1,1);
Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time());
return pre.intersect(ray,v0,v1,v2,UVIdentity<Mx>(),Occluded1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID()));
}
static __forceinline bool pointQuery(PointQuery* query, PointQueryContext* context, const Primitive& tri)
{
return PrimitivePointQuery1<Primitive>::pointQuery(query, context, tri);
}
};
/*! Intersects M motion blur triangles with K rays. */
template<int M, int Mx, int K, bool filter>
struct TriangleMiMBIntersectorKPluecker
{
typedef TriangleMi<M> Primitive;
typedef PlueckerIntersectorK<Mx,K> Precalculations;
/*! Intersects K rays with M triangles. */
static __forceinline void intersect(const vbool<K>& valid_i, Precalculations& pre, RayHitK<K>& ray, IntersectContext* context, const TriangleMi<M>& tri)
{
for (size_t i=0; i<TriangleMi<M>::max_size(); i++)
{
if (!tri.valid(i)) break;
STAT3(normal.trav_prims,1,popcnt(valid_i),K);
Vec3vf<K> v0,v1,v2; tri.gather(valid_i,v0,v1,v2,i,context->scene,ray.time());
pre.intersectK(valid_i,ray,v0,v1,v2,UVIdentity<K>(),IntersectKEpilogM<M,K,filter>(ray,context,tri.geomID(),tri.primID(),i));
}
}
/*! Test for K rays if they are occluded by any of the M triangles. */
static __forceinline vbool<K> occluded(const vbool<K>& valid_i, Precalculations& pre, RayK<K>& ray, IntersectContext* context, const TriangleMi<M>& tri)
{
vbool<K> valid0 = valid_i;
for (size_t i=0; i<TriangleMi<M>::max_size(); i++)
{
if (!tri.valid(i)) break;
STAT3(shadow.trav_prims,1,popcnt(valid0),K);
Vec3vf<K> v0,v1,v2; tri.gather(valid_i,v0,v1,v2,i,context->scene,ray.time());
pre.intersectK(valid0,ray,v0,v1,v2,UVIdentity<K>(),OccludedKEpilogM<M,K,filter>(valid0,ray,context,tri.geomID(),tri.primID(),i));
if (none(valid0)) break;
}
return !valid0;
}
/*! Intersect a ray with M triangles and updates the hit. */
static __forceinline void intersect(Precalculations& pre, RayHitK<K>& ray, size_t k, IntersectContext* context, const TriangleMi<M>& tri)
{
STAT3(normal.trav_prims,1,1,1);
Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time()[k]);
pre.intersect(ray,k,v0,v1,v2,UVIdentity<Mx>(),Intersect1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID()));
}
/*! Test if the ray is occluded by one of the M triangles. */
static __forceinline bool occluded(Precalculations& pre, RayK<K>& ray, size_t k, IntersectContext* context, const TriangleMi<M>& tri)
{
STAT3(shadow.trav_prims,1,1,1);
Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time()[k]);
return pre.intersect(ray,k,v0,v1,v2,UVIdentity<Mx>(),Occluded1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID()));
}
};
}
}
|
Java
|
<div class="container-fluid landing">
<div id="almari">
<center>
<h1 id="alm">Almari</h1>
<h2 id="sub">Elegant clothing. Delivered.</h2>
</center>
</div>
<div class="sec1">
<div class="row" id="toprow">
<div class="col-md-6" id="borrow">
<center>
<img src="clothing285.png" class="icon">
<p> Prom, party or wedding, but nothing to wear? <br> Your virtual wardrobe has some exotic clothing...</p>
<div class="col-md-4 col-centered btn" type="button">
<h3 class = "box" ng-click="borrow()">BORROW</h3>
</div>
</center>
</div>
<div class="col-md-6">
<center>
<img src="pricetag.png" class="icon">
<p> Bought an expensive dress, but wore it only once? <br> Monetize your wardrobe </p>
<div class="col-md-4 col-centered btn" type="button">
<h3 class="box" ng-click="lend()">LEND</h3>
</div>
</center>
</div>
</div>
<br><br>
</div>
<div id="sec2">
<br>
<br>
</div>
</div>
|
Java
|
// 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.
// ==++==
//
//
// ==--==
// ****************************************************************************
// File: controller.cpp
//
//
// controller.cpp: Debugger execution control routines
//
// ****************************************************************************
// Putting code & #includes, #defines, etc, before the stdafx.h will
// cause the code,etc, to be silently ignored
#include "stdafx.h"
#include "openum.h"
#include "../inc/common.h"
#include "eeconfig.h"
#include "../../vm/methoditer.h"
const char *GetTType( TraceType tt);
#define IsSingleStep(exception) (exception == EXCEPTION_SINGLE_STEP)
// -------------------------------------------------------------------------
// DebuggerController routines
// -------------------------------------------------------------------------
SPTR_IMPL_INIT(DebuggerPatchTable, DebuggerController, g_patches, NULL);
SVAL_IMPL_INIT(BOOL, DebuggerController, g_patchTableValid, FALSE);
#if !defined(DACCESS_COMPILE)
DebuggerController *DebuggerController::g_controllers = NULL;
DebuggerControllerPage *DebuggerController::g_protections = NULL;
CrstStatic DebuggerController::g_criticalSection;
int DebuggerController::g_cTotalMethodEnter = 0;
// Is this patch at a position at which it's safe to take a stack?
bool DebuggerControllerPatch::IsSafeForStackTrace()
{
LIMITED_METHOD_CONTRACT;
TraceType tt = this->trace.GetTraceType();
Module *module = this->key.module;
BOOL managed = this->IsManagedPatch();
// Patches placed by MgrPush can come at lots of illegal spots. Can't take a stack trace here.
if ((module == NULL) && managed && (tt == TRACE_MGR_PUSH))
{
return false;
}
// Consider everything else legal.
// This is a little shady for TRACE_FRAME_PUSH. But TraceFrame() needs a stackInfo
// to get a RegDisplay (though almost nobody uses it, so perhaps it could be removed).
return true;
}
#ifndef _TARGET_ARM_
// returns a pointer to the shared buffer. each call will AddRef() the object
// before returning it so callers only need to Release() when they're finished with it.
SharedPatchBypassBuffer* DebuggerControllerPatch::GetOrCreateSharedPatchBypassBuffer()
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
}
CONTRACTL_END;
if (m_pSharedPatchBypassBuffer == NULL)
{
m_pSharedPatchBypassBuffer = new (interopsafeEXEC) SharedPatchBypassBuffer();
_ASSERTE(m_pSharedPatchBypassBuffer);
TRACE_ALLOC(m_pSharedPatchBypassBuffer);
}
m_pSharedPatchBypassBuffer->AddRef();
return m_pSharedPatchBypassBuffer;
}
#endif // _TARGET_ARM_
// @todo - remove all this splicing trash
// This Sort/Splice stuff just reorders the patches within a particular chain such
// that when we iterate through by calling GetPatch() and GetNextPatch(DebuggerControllerPatch),
// we'll get patches in increasing order of DebuggerControllerTypes.
// Practically, this means that calling GetPatch() will return EnC patches before stepping patches.
//
#if 1
void DebuggerPatchTable::SortPatchIntoPatchList(DebuggerControllerPatch **ppPatch)
{
LOG((LF_CORDB, LL_EVERYTHING, "DPT::SPIPL called.\n"));
#ifdef _DEBUG
DebuggerControllerPatch *patchFirst
= (DebuggerControllerPatch *) Find(Hash((*ppPatch)), Key((*ppPatch)));
_ASSERTE(patchFirst == (*ppPatch));
_ASSERTE((*ppPatch)->controller->GetDCType() != DEBUGGER_CONTROLLER_STATIC);
#endif //_DEBUG
DebuggerControllerPatch *patchNext = GetNextPatch((*ppPatch));
LOG((LF_CORDB, LL_EVERYTHING, "DPT::SPIPL GetNextPatch passed\n"));
//List contains one, (sorted) element
if (patchNext == NULL)
{
LOG((LF_CORDB, LL_INFO10000,
"DPT::SPIPL: Patch 0x%x is a sorted singleton\n", (*ppPatch)));
return;
}
// If we decide to reorder the list, we'll need to keep the element
// indexed by the hash function as the (sorted)first item. Everything else
// chains off this element, can can thus stay put.
// Thus, either the element we just added is already sorted, or else we'll
// have to move it elsewhere in the list, meaning that we'll have to swap
// the second item & the new item, so that the index points to the proper
// first item in the list.
//use Cur ptr for case where patch gets appended to list
DebuggerControllerPatch *patchCur = patchNext;
while (patchNext != NULL &&
((*ppPatch)->controller->GetDCType() >
patchNext->controller->GetDCType()) )
{
patchCur = patchNext;
patchNext = GetNextPatch(patchNext);
}
if (patchNext == GetNextPatch((*ppPatch)))
{
LOG((LF_CORDB, LL_INFO10000,
"DPT::SPIPL: Patch 0x%x is already sorted\n", (*ppPatch)));
return; //already sorted
}
LOG((LF_CORDB, LL_INFO10000,
"DPT::SPIPL: Patch 0x%x will be moved \n", (*ppPatch)));
//remove it from the list
SpliceOutOfList((*ppPatch));
// the kinda neat thing is: since we put it originally at the front of the list,
// and it's not in order, then it must be behind another element of this list,
// so we don't have to write any 'SpliceInFrontOf' code.
_ASSERTE(patchCur != NULL);
SpliceInBackOf((*ppPatch), patchCur);
LOG((LF_CORDB, LL_INFO10000,
"DPT::SPIPL: Patch 0x%x is now sorted\n", (*ppPatch)));
}
// This can leave the list empty, so don't do this unless you put
// the patch back somewhere else.
void DebuggerPatchTable::SpliceOutOfList(DebuggerControllerPatch *patch)
{
// We need to get iHash, the index of the ptr within
// m_piBuckets, ie it's entry in the hashtable.
ULONG iHash = Hash(patch) % m_iBuckets;
ULONG iElement = m_piBuckets[iHash];
DebuggerControllerPatch *patchFirst
= (DebuggerControllerPatch *) EntryPtr(iElement);
// Fix up pointers to chain
if (patchFirst == patch)
{
// The first patch shouldn't have anything behind it.
_ASSERTE(patch->entry.iPrev == DPT_INVALID_SLOT);
if (patch->entry.iNext != DPT_INVALID_SLOT)
{
m_piBuckets[iHash] = patch->entry.iNext;
}
else
{
m_piBuckets[iHash] = DPT_INVALID_SLOT;
}
}
if (patch->entry.iNext != DPT_INVALID_SLOT)
{
EntryPtr(patch->entry.iNext)->iPrev = patch->entry.iPrev;
}
if (patch->entry.iPrev != DPT_INVALID_SLOT)
{
EntryPtr(patch->entry.iNext)->iNext = patch->entry.iNext;
}
patch->entry.iNext = DPT_INVALID_SLOT;
patch->entry.iPrev = DPT_INVALID_SLOT;
}
void DebuggerPatchTable::SpliceInBackOf(DebuggerControllerPatch *patchAppend,
DebuggerControllerPatch *patchEnd)
{
ULONG iAppend = ItemIndex((HASHENTRY*)patchAppend);
ULONG iEnd = ItemIndex((HASHENTRY*)patchEnd);
patchAppend->entry.iPrev = iEnd;
patchAppend->entry.iNext = patchEnd->entry.iNext;
if (patchAppend->entry.iNext != DPT_INVALID_SLOT)
EntryPtr(patchAppend->entry.iNext)->iPrev = iAppend;
patchEnd->entry.iNext = iAppend;
}
#endif
//-----------------------------------------------------------------------------
// Stack safety rules.
// In general, we're safe to crawl whenever we're in preemptive mode.
// We're also must be safe at any spot the thread could get synchronized,
// because that means that the thread will be stopped to let the debugger shell
// inspect it and that can definitely take stack traces.
// Basically the only unsafe spot is in the middle of goofy stub with some
// partially constructed frame while in coop mode.
//-----------------------------------------------------------------------------
// Safe if we're at certain types of patches.
// See Patch::IsSafeForStackTrace for details.
StackTraceTicket::StackTraceTicket(DebuggerControllerPatch * patch)
{
_ASSERTE(patch != NULL);
_ASSERTE(patch->IsSafeForStackTrace());
}
// Safe if there was already another stack trace at this spot. (Grandfather clause)
// This is commonly used for StepOut, which takes runs stacktraces to crawl up
// the stack to find a place to patch.
StackTraceTicket::StackTraceTicket(ControllerStackInfo * info)
{
_ASSERTE(info != NULL);
// Ensure that the other stack info object actually executed (and thus was
// actually valid).
_ASSERTE(info->m_dbgExecuted);
}
// Safe b/c the context shows we're in native managed code.
// This must be safe because we could always set a managed breakpoint by native
// offset and thus synchronize the shell at this spot. So this is
// a specific example of the Synchronized case. The fact that we don't actually
// synchronize doesn't make us any less safe.
StackTraceTicket::StackTraceTicket(const BYTE * ip)
{
_ASSERTE(g_pEEInterface->IsManagedNativeCode(ip));
}
// Safe it we're at a Synchronized point point.
StackTraceTicket::StackTraceTicket(Thread * pThread)
{
_ASSERTE(pThread != NULL);
// If we're synchronized, the debugger should be stopped.
// That means all threads are synced and must be safe to take a stacktrace.
// Thus we don't even need to do a thread-specific check.
_ASSERTE(g_pDebugger->IsStopped());
}
// DebuggerUserBreakpoint has a special case of safety. See that ctor for details.
StackTraceTicket::StackTraceTicket(DebuggerUserBreakpoint * p)
{
_ASSERTE(p != NULL);
}
//void ControllerStackInfo::GetStackInfo(): GetStackInfo
// is invoked by the user to trigger the stack walk. This will
// cause the stack walk detailed in the class description to happen.
// Thread* thread: The thread to do the stack walk on.
// void* targetFP: Can be either NULL (meaning that the bottommost
// frame is the target), or an frame pointer, meaning that the
// caller wants information about a specific frame.
// CONTEXT* pContext: A pointer to a CONTEXT structure. Can be null,
// we use our temp context.
// bool suppressUMChainFromComPlusMethodFrameGeneric - A ridiculous flag that is trying to narrowly
// target a fix for issue 650903.
// StackTraceTicket - ticket to ensure that we actually have permission for this stacktrace
void ControllerStackInfo::GetStackInfo(
StackTraceTicket ticket,
Thread *thread,
FramePointer targetFP,
CONTEXT *pContext,
bool suppressUMChainFromComPlusMethodFrameGeneric
)
{
_ASSERTE(thread != NULL);
BOOL contextValid = (pContext != NULL);
if (!contextValid)
{
// We're assuming the thread is protected w/ a frame (which includes the redirection
// case). The stackwalker will use that protection to prime the context.
pContext = &this->m_tempContext;
}
else
{
// If we provided an explicit context for this thread, it better not be redirected.
_ASSERTE(!ISREDIRECTEDTHREAD(thread));
}
// Mark this stackwalk as valid so that it can in turn be used to grandfather
// in other stackwalks.
INDEBUG(m_dbgExecuted = true);
m_activeFound = false;
m_returnFound = false;
m_bottomFP = LEAF_MOST_FRAME;
m_targetFP = targetFP;
m_targetFrameFound = (m_targetFP == LEAF_MOST_FRAME);
m_specialChainReason = CHAIN_NONE;
m_suppressUMChainFromComPlusMethodFrameGeneric = suppressUMChainFromComPlusMethodFrameGeneric;
int result = DebuggerWalkStack(thread,
LEAF_MOST_FRAME,
pContext,
contextValid,
WalkStack,
(void *) this,
FALSE);
_ASSERTE(m_activeFound); // All threads have at least one unmanaged frame
if (result == SWA_DONE)
{
_ASSERTE(!m_returnFound);
m_returnFrame = m_activeFrame;
}
}
//---------------------------------------------------------------------------------------
//
// This function "undoes" an unwind, i.e. it takes the active frame (the current frame)
// and sets it to be the return frame (the caller frame). Currently it is only used by
// the stepper to step out of an LCG method. See DebuggerStepper::DetectHandleLCGMethods()
// for more information.
//
// Assumptions:
// The current frame is valid on entry.
//
// Notes:
// After this function returns, the active frame on this instance of ControllerStackInfo will no longer be valid.
//
// This function is specifically for DebuggerStepper::DetectHandleLCGMethods(). Using it in other scencarios may
// require additional changes.
//
void ControllerStackInfo::SetReturnFrameWithActiveFrame()
{
// Copy the active frame into the return frame.
m_returnFound = true;
m_returnFrame = m_activeFrame;
// Invalidate the active frame.
m_activeFound = false;
memset(&(m_activeFrame), 0, sizeof(m_activeFrame));
m_activeFrame.fp = LEAF_MOST_FRAME;
}
// Fill in a controller-stack info.
StackWalkAction ControllerStackInfo::WalkStack(FrameInfo *pInfo, void *data)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(!pInfo->HasStubFrame()); // we didn't ask for stub frames.
ControllerStackInfo *i = (ControllerStackInfo *) data;
//save this info away for later use
if (i->m_bottomFP == LEAF_MOST_FRAME)
i->m_bottomFP = pInfo->fp;
// This is part of the targetted fix for issue 650903. (See the other
// parts in in code:TrackUMChain and code:DebuggerStepper::TrapStepOut.)
// pInfo->fIgnoreThisFrameIfSuppressingUMChainFromComPlusMethodFrameGeneric has been
// set by TrackUMChain to help us remember that the current frame we're looking at is
// ComPlusMethodFrameGeneric (we can't rely on looking at pInfo->frame to check
// this), and i->m_suppressUMChainFromComPlusMethodFrameGeneric has been set by the
// dude initiating this walk to remind us that our goal in life is to do a Step Out
// during managed-only debugging. These two things together tell us we should ignore
// this frame, rather than erroneously identifying it as the target frame.
#ifdef FEATURE_COMINTEROP
if(i->m_suppressUMChainFromComPlusMethodFrameGeneric &&
(pInfo->chainReason == CHAIN_ENTER_UNMANAGED) &&
(pInfo->fIgnoreThisFrameIfSuppressingUMChainFromComPlusMethodFrameGeneric))
{
return SWA_CONTINUE;
}
#endif // FEATURE_COMINTEROP
//have we reached the correct frame yet?
if (!i->m_targetFrameFound &&
IsEqualOrCloserToLeaf(i->m_targetFP, pInfo->fp))
{
i->m_targetFrameFound = true;
}
if (i->m_targetFrameFound )
{
// Ignore Enter-managed chains.
if (pInfo->chainReason == CHAIN_ENTER_MANAGED)
{
return SWA_CONTINUE;
}
if (i->m_activeFound )
{
// We care if the current frame is unmanaged (in case a managed stepper is initiated
// on a thread currently in unmanaged code). But since we can't step-out to UM frames,
// we can just skip them in the stack walk.
if (!pInfo->managed)
{
return SWA_CONTINUE;
}
if (pInfo->chainReason == CHAIN_CLASS_INIT)
i->m_specialChainReason = pInfo->chainReason;
if (pInfo->fp != i->m_activeFrame.fp) // avoid dups
{
i->m_returnFrame = *pInfo;
#if defined(WIN64EXCEPTIONS)
CopyREGDISPLAY(&(i->m_returnFrame.registers), &(pInfo->registers));
#endif // WIN64EXCEPTIONS
i->m_returnFound = true;
return SWA_ABORT;
}
}
else
{
i->m_activeFrame = *pInfo;
#if defined(WIN64EXCEPTIONS)
CopyREGDISPLAY(&(i->m_activeFrame.registers), &(pInfo->registers));
#endif // WIN64EXCEPTIONS
i->m_activeFound = true;
return SWA_CONTINUE;
}
}
return SWA_CONTINUE;
}
//
// Note that patches may be reallocated - do not keep a pointer to a patch.
//
DebuggerControllerPatch *DebuggerPatchTable::AddPatchForMethodDef(DebuggerController *controller,
Module *module,
mdMethodDef md,
size_t offset,
DebuggerPatchKind kind,
FramePointer fp,
AppDomain *pAppDomain,
SIZE_T masterEnCVersion,
DebuggerJitInfo *dji)
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_NOTRIGGER;
}
CONTRACTL_END;
LOG( (LF_CORDB,LL_INFO10000,"DCP:AddPatchForMethodDef unbound "
"relative in methodDef 0x%x with dji 0x%x "
"controller:0x%x AD:0x%x\n", md,
dji, controller, pAppDomain));
DebuggerFunctionKey key;
key.module = module;
key.md = md;
// Get a new uninitialized patch object
DebuggerControllerPatch *patch =
(DebuggerControllerPatch *) Add(HashKey(&key));
if (patch == NULL)
{
ThrowOutOfMemory();
}
#ifndef _TARGET_ARM_
patch->Initialize();
#endif
//initialize the patch data structure.
InitializePRD(&(patch->opcode));
patch->controller = controller;
patch->key.module = module;
patch->key.md = md;
patch->offset = offset;
patch->offsetIsIL = (kind == PATCH_KIND_IL_MASTER);
patch->address = NULL;
patch->fp = fp;
patch->trace.Bad_SetTraceType(DPT_DEFAULT_TRACE_TYPE); // TRACE_OTHER
patch->refCount = 1; // AddRef()
patch->fSaveOpcode = false;
patch->pAppDomain = pAppDomain;
patch->pid = m_pid++;
if (kind == PATCH_KIND_IL_MASTER)
{
_ASSERTE(dji == NULL);
patch->encVersion = masterEnCVersion;
}
else
{
patch->dji = dji;
}
patch->kind = kind;
if (dji)
LOG((LF_CORDB,LL_INFO10000,"AddPatchForMethodDef w/ version 0x%04x, "
"pid:0x%x\n", dji->m_encVersion, patch->pid));
else if (kind == PATCH_KIND_IL_MASTER)
LOG((LF_CORDB,LL_INFO10000,"AddPatchForMethodDef w/ version 0x%04x, "
"pid:0x%x\n", masterEnCVersion,patch->pid));
else
LOG((LF_CORDB,LL_INFO10000,"AddPatchForMethodDef w/ no dji or dmi, pid:0x%x\n",patch->pid));
// This patch is not yet bound or activated
_ASSERTE( !patch->IsBound() );
_ASSERTE( !patch->IsActivated() );
// The only kind of patch with IL offset is the IL master patch.
_ASSERTE(patch->IsILMasterPatch() || patch->offsetIsIL == FALSE);
return patch;
}
// Create and bind a patch to the specified address
// The caller should immediately activate the patch since we typically expect bound patches
// will always be activated.
DebuggerControllerPatch *DebuggerPatchTable::AddPatchForAddress(DebuggerController *controller,
MethodDesc *fd,
size_t offset,
DebuggerPatchKind kind,
CORDB_ADDRESS_TYPE *address,
FramePointer fp,
AppDomain *pAppDomain,
DebuggerJitInfo *dji,
SIZE_T pid,
TraceType traceType)
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(kind == PATCH_KIND_NATIVE_MANAGED || kind == PATCH_KIND_NATIVE_UNMANAGED);
LOG((LF_CORDB,LL_INFO10000,"DCP:AddPatchForAddress bound "
"absolute to 0x%x with dji 0x%x (mdDef:0x%x) "
"controller:0x%x AD:0x%x\n",
address, dji, (fd!=NULL?fd->GetMemberDef():0), controller,
pAppDomain));
// get new uninitialized patch object
DebuggerControllerPatch *patch =
(DebuggerControllerPatch *) Add(HashAddress(address));
if (patch == NULL)
{
ThrowOutOfMemory();
}
#ifndef _TARGET_ARM_
patch->Initialize();
#endif
// initialize the patch data structure
InitializePRD(&(patch->opcode));
patch->controller = controller;
if (fd == NULL)
{
patch->key.module = NULL;
patch->key.md = mdTokenNil;
}
else
{
patch->key.module = g_pEEInterface->MethodDescGetModule(fd);
patch->key.md = fd->GetMemberDef();
}
patch->offset = offset;
patch->offsetIsIL = FALSE;
patch->address = address;
patch->fp = fp;
patch->trace.Bad_SetTraceType(traceType);
patch->refCount = 1; // AddRef()
patch->fSaveOpcode = false;
patch->pAppDomain = pAppDomain;
if (pid == DCP_PID_INVALID)
patch->pid = m_pid++;
else
patch->pid = pid;
patch->dji = dji;
patch->kind = kind;
if (dji == NULL)
LOG((LF_CORDB,LL_INFO10000,"AddPatchForAddress w/ version with no dji, pid:0x%x\n", patch->pid));
else
{
LOG((LF_CORDB,LL_INFO10000,"AddPatchForAddress w/ version 0x%04x, "
"pid:0x%x\n", dji->m_methodInfo->GetCurrentEnCVersion(), patch->pid));
_ASSERTE( fd==NULL || fd == dji->m_fd );
}
SortPatchIntoPatchList(&patch);
// This patch is bound but not yet activated
_ASSERTE( patch->IsBound() );
_ASSERTE( !patch->IsActivated() );
// The only kind of patch with IL offset is the IL master patch.
_ASSERTE(patch->IsILMasterPatch() || patch->offsetIsIL == FALSE);
return patch;
}
// Set the native address for this patch.
void DebuggerPatchTable::BindPatch(DebuggerControllerPatch *patch, CORDB_ADDRESS_TYPE *address)
{
_ASSERTE(patch != NULL);
_ASSERTE(address != NULL);
_ASSERTE( !patch->IsILMasterPatch() );
_ASSERTE(!patch->IsBound() );
//Since the actual patch doesn't move, we don't have to worry about
//zeroing out the opcode field (see lenghty comment above)
// Since the patch is double-hashed based off Address, if we change the address,
// we must remove and reinsert the patch.
CHashTable::Delete(HashKey(&patch->key), ItemIndex((HASHENTRY*)patch));
patch->address = address;
CHashTable::Add(HashAddress(address), ItemIndex((HASHENTRY*)patch));
SortPatchIntoPatchList(&patch);
_ASSERTE(patch->IsBound() );
_ASSERTE(!patch->IsActivated() );
}
// Disassociate a patch from a specific code address.
void DebuggerPatchTable::UnbindPatch(DebuggerControllerPatch *patch)
{
_ASSERTE(patch != NULL);
_ASSERTE(patch->kind != PATCH_KIND_IL_MASTER);
_ASSERTE(patch->IsBound() );
_ASSERTE(!patch->IsActivated() );
//<REVISIT_TODO>@todo We're hosed if the patch hasn't been primed with
// this info & we can't get it...</REVISIT_TODO>
if (patch->key.module == NULL ||
patch->key.md == mdTokenNil)
{
MethodDesc *fd = g_pEEInterface->GetNativeCodeMethodDesc(
dac_cast<PCODE>(patch->address));
_ASSERTE( fd != NULL );
patch->key.module = g_pEEInterface->MethodDescGetModule(fd);
patch->key.md = fd->GetMemberDef();
}
// Update it's index entry in the table to use it's unbound key
// Since the patch is double-hashed based off Address, if we change the address,
// we must remove and reinsert the patch.
CHashTable::Delete( HashAddress(patch->address),
ItemIndex((HASHENTRY*)patch));
patch->address = NULL; // we're no longer bound to this address
CHashTable::Add( HashKey(&patch->key),
ItemIndex((HASHENTRY*)patch));
_ASSERTE(!patch->IsBound() );
}
void DebuggerPatchTable::RemovePatch(DebuggerControllerPatch *patch)
{
// Since we're deleting this patch, it must not be activated (i.e. it must not have a stored opcode)
_ASSERTE( !patch->IsActivated() );
#ifndef _TARGET_ARM_
patch->DoCleanup();
#endif
//
// Because of the implementation of CHashTable, we can safely
// delete elements while iterating through the table. This
// behavior is relied upon - do not change to a different
// implementation without considering this fact.
//
Delete(Hash(patch), (HASHENTRY *) patch);
}
DebuggerControllerPatch *DebuggerPatchTable::GetNextPatch(DebuggerControllerPatch *prev)
{
ULONG iNext;
HASHENTRY *psEntry;
// Start at the next entry in the chain.
// @todo - note that: EntryPtr(ItemIndex(x)) == x
iNext = EntryPtr(ItemIndex((HASHENTRY*)prev))->iNext;
// Search until we hit the end.
while (iNext != UINT32_MAX)
{
// Compare the keys.
psEntry = EntryPtr(iNext);
// Careful here... we can hash the entries in this table
// by two types of keys. In this type of search, the type
// of the second key (psEntry) does not necessarily
// indicate the type of the first key (prev), so we have
// to check for sure.
DebuggerControllerPatch *pc2 = (DebuggerControllerPatch*)psEntry;
if (((pc2->address == NULL) && (prev->address == NULL)) ||
((pc2->address != NULL) && (prev->address != NULL)))
if (!Cmp(Key(prev), psEntry))
return pc2;
// Advance to the next item in the chain.
iNext = psEntry->iNext;
}
return NULL;
}
#ifdef _DEBUG_PATCH_TABLE
// DEBUG An internal debugging routine, it iterates
// through the hashtable, stopping at every
// single entry, no matter what it's state. For this to
// compile, you're going to have to add friend status
// of this class to CHashTableAndData in
// to $\Com99\Src\inc\UtilCode.h
void DebuggerPatchTable::CheckPatchTable()
{
if (NULL != m_pcEntries)
{
DebuggerControllerPatch *dcp;
int i = 0;
while (i++ <m_iEntries)
{
dcp = (DebuggerControllerPatch*)&(((DebuggerControllerPatch *)m_pcEntries)[i]);
if (dcp->opcode != 0 )
{
LOG((LF_CORDB,LL_INFO1000, "dcp->addr:0x%8x "
"mdMD:0x%8x, offset:0x%x, native:%d\n",
dcp->address, dcp->key.md, dcp->offset,
dcp->IsNativePatch()));
}
}
}
}
#endif // _DEBUG_PATCH_TABLE
// Count how many patches are in the table.
// Use for asserts
int DebuggerPatchTable::GetNumberOfPatches()
{
int total = 0;
if (NULL != m_pcEntries)
{
DebuggerControllerPatch *dcp;
ULONG i = 0;
while (i++ <m_iEntries)
{
dcp = (DebuggerControllerPatch*)&(((DebuggerControllerPatch *)m_pcEntries)[i]);
if (dcp->IsActivated() || !dcp->IsFree())
total++;
}
}
return total;
}
#if defined(_DEBUG)
//-----------------------------------------------------------------------------
// Debug check that we only have 1 thread-starter per thread.
// pNew - the new DTS. We'll make sure there's not already a DTS on this thread.
//-----------------------------------------------------------------------------
void DebuggerController::EnsureUniqueThreadStarter(DebuggerThreadStarter * pNew)
{
// This lock should be safe to take since our base class ctor takes it.
ControllerLockHolder lockController;
DebuggerController * pExisting = g_controllers;
while(pExisting != NULL)
{
if (pExisting->GetDCType() == DEBUGGER_CONTROLLER_THREAD_STARTER)
{
if (pExisting != pNew)
{
// If we have 2 thread starters, they'd better be on different threads.
_ASSERTE((pExisting->GetThread() != pNew->GetThread()));
}
}
pExisting = pExisting->m_next;
}
}
#endif
//-----------------------------------------------------------------------------
// If we have a thread-starter on the given EE thread, make sure it's cancel.
// Thread-Starters normally delete themselves when they fire. But if the EE
// destroys the thread before it fires, then we'd still have an active DTS.
//-----------------------------------------------------------------------------
void DebuggerController::CancelOutstandingThreadStarter(Thread * pThread)
{
_ASSERTE(pThread != NULL);
LOG((LF_CORDB, LL_EVERYTHING, "DC:CancelOutstandingThreadStarter - checking on thread =0x%p\n", pThread));
ControllerLockHolder lockController;
DebuggerController * p = g_controllers;
while(p != NULL)
{
if (p->GetDCType() == DEBUGGER_CONTROLLER_THREAD_STARTER)
{
if (p->GetThread() == pThread)
{
LOG((LF_CORDB, LL_EVERYTHING, "DC:CancelOutstandingThreadStarter, pThread=0x%p, Found=0x%p\n", p));
// There's only 1 DTS per thread, so once we find it, we can quit.
p->Delete();
p = NULL;
break;
}
}
p = p->m_next;
}
// The common case is that our DTS hit its patch and did a SendEvent (and
// deleted itself). So usually we'll get through the whole list w/o deleting anything.
}
//void DebuggerController::Initialize() Sets up the static
// variables for the static DebuggerController class.
// How: Sets g_runningOnWin95, initializes the critical section
HRESULT DebuggerController::Initialize()
{
CONTRACT(HRESULT)
{
THROWS;
GC_NOTRIGGER;
// This can be called in an "early attach" case, so DebuggerIsInvolved()
// will be b/c we don't realize the debugger's attaching to us.
//PRECONDITION(DebuggerIsInvolved());
POSTCONDITION(CheckPointer(g_patches));
POSTCONDITION(RETVAL == S_OK);
}
CONTRACT_END;
if (g_patches == NULL)
{
ZeroMemory(&g_criticalSection, sizeof(g_criticalSection)); // Init() expects zero-init memory.
// NOTE: CRST_UNSAFE_ANYMODE prevents a GC mode switch when entering this crst.
// If you remove this flag, we will switch to preemptive mode when entering
// g_criticalSection, which means all functions that enter it will become
// GC_TRIGGERS. (This includes all uses of ControllerLockHolder.) So be sure
// to update the contracts if you remove this flag.
g_criticalSection.Init(CrstDebuggerController,
(CrstFlags)(CRST_UNSAFE_ANYMODE | CRST_REENTRANCY | CRST_DEBUGGER_THREAD));
g_patches = new (interopsafe) DebuggerPatchTable();
_ASSERTE(g_patches != NULL); // throws on oom
HRESULT hr = g_patches->Init();
if (FAILED(hr))
{
DeleteInteropSafe(g_patches);
ThrowHR(hr);
}
g_patchTableValid = TRUE;
TRACE_ALLOC(g_patches);
}
_ASSERTE(g_patches != NULL);
RETURN (S_OK);
}
//---------------------------------------------------------------------------------------
//
// Constructor for a controller
//
// Arguments:
// pThread - thread that controller has affinity to. NULL if no thread - affinity.
// pAppdomain - appdomain that controller has affinity to. NULL if no AD affinity.
//
//
// Notes:
// "Affinity" is per-controller specific. Affinity is generally passed on to
// any patches the controller creates. So if a controller has affinity to Thread X,
// then any patches it creates will only fire on Thread-X.
//
//---------------------------------------------------------------------------------------
DebuggerController::DebuggerController(Thread * pThread, AppDomain * pAppDomain)
: m_pAppDomain(pAppDomain),
m_thread(pThread),
m_singleStep(false),
m_exceptionHook(false),
m_traceCall(0),
m_traceCallFP(ROOT_MOST_FRAME),
m_unwindFP(LEAF_MOST_FRAME),
m_eventQueuedCount(0),
m_deleted(false),
m_fEnableMethodEnter(false)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
CONSTRUCTOR_CHECK;
}
CONTRACTL_END;
LOG((LF_CORDB, LL_INFO10000, "DC: 0x%x m_eventQueuedCount to 0 - DC::DC\n", this));
ControllerLockHolder lockController;
{
m_next = g_controllers;
g_controllers = this;
}
}
//---------------------------------------------------------------------------------------
//
// Debugger::Controller::DeleteAllControlers - deletes all debugger contollers
//
// Arguments:
// None
//
// Return Value:
// None
//
// Notes:
// This is used at detach time to remove all DebuggerControllers. This will remove all
// patches and do whatever other cleanup individual DebuggerControllers consider
// necessary to allow the debugger to detach and the process to run normally.
//
void DebuggerController::DeleteAllControllers()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
ControllerLockHolder lockController;
DebuggerController * pDebuggerController = g_controllers;
DebuggerController * pNextDebuggerController = NULL;
while (pDebuggerController != NULL)
{
pNextDebuggerController = pDebuggerController->m_next;
pDebuggerController->DebuggerDetachClean();
pDebuggerController->Delete();
pDebuggerController = pNextDebuggerController;
}
}
DebuggerController::~DebuggerController()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
DESTRUCTOR_CHECK;
}
CONTRACTL_END;
ControllerLockHolder lockController;
_ASSERTE(m_eventQueuedCount == 0);
DisableAll();
//
// Remove controller from list
//
DebuggerController **c;
c = &g_controllers;
while (*c != this)
c = &(*c)->m_next;
*c = m_next;
}
// void DebuggerController::Delete()
// What: Marks an instance as deletable. If it's ref count
// (see Enqueue, Dequeue) is currently zero, it actually gets deleted
// How: Set m_deleted to true. If m_eventQueuedCount==0, delete this
void DebuggerController::Delete()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
if (m_eventQueuedCount == 0)
{
LOG((LF_CORDB|LF_ENC, LL_INFO100000, "DC::Delete: actual delete of this:0x%x!\n", this));
TRACE_FREE(this);
DeleteInteropSafe(this);
}
else
{
LOG((LF_CORDB|LF_ENC, LL_INFO100000, "DC::Delete: marked for "
"future delete of this:0x%x!\n", this));
LOG((LF_CORDB|LF_ENC, LL_INFO10000, "DC:0x%x m_eventQueuedCount at 0x%x\n",
this, m_eventQueuedCount));
m_deleted = true;
}
}
void DebuggerController::DebuggerDetachClean()
{
//do nothing here
}
//static
void DebuggerController::AddRef(DebuggerControllerPatch *patch)
{
patch->refCount++;
}
//static
void DebuggerController::Release(DebuggerControllerPatch *patch)
{
patch->refCount--;
if (patch->refCount == 0)
{
LOG((LF_CORDB, LL_INFO10000, "DCP::R: patch deleted, deactivating\n"));
DeactivatePatch(patch);
GetPatchTable()->RemovePatch(patch);
}
}
// void DebuggerController::DisableAll() DisableAll removes
// all control from the controller. This includes all patches & page
// protection. This will invoke Disable* for unwind,singlestep,
// exceptionHook, and tracecall. It will also go through the patch table &
// attempt to remove any and all patches that belong to this controller.
// If the patch is currently triggering, then a Dispatch* method expects the
// patch to be there after we return, so we instead simply mark the patch
// itself as deleted.
void DebuggerController::DisableAll()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
LOG((LF_CORDB,LL_INFO1000, "DC::DisableAll\n"));
_ASSERTE(g_patches != NULL);
ControllerLockHolder ch;
{
//
// Remove controller's patches from list.
// Don't do this on shutdown because the shutdown thread may have killed another thread asynchronously
// thus leaving the patchtable in an inconsistent state such that we may fail trying to walk it.
// Since we're exiting anyways, leaving int3 in the code can't harm anybody.
//
if (!g_fProcessDetach)
{
HASHFIND f;
for (DebuggerControllerPatch *patch = g_patches->GetFirstPatch(&f);
patch != NULL;
patch = g_patches->GetNextPatch(&f))
{
if (patch->controller == this)
{
Release(patch);
}
}
}
if (m_singleStep)
DisableSingleStep();
if (m_exceptionHook)
DisableExceptionHook();
if (m_unwindFP != LEAF_MOST_FRAME)
DisableUnwind();
if (m_traceCall)
DisableTraceCall();
if (m_fEnableMethodEnter)
DisableMethodEnter();
}
}
// void DebuggerController::Enqueue() What: Does
// reference counting so we don't toast a
// DebuggerController while it's in a Dispatch queue.
// Why: In DispatchPatchOrSingleStep, we can't hold locks when going
// into PreEmptiveGC mode b/c we'll create a deadlock.
// So we have to UnLock() prior to
// EnablePreEmptiveGC(). But somebody else can show up and delete the
// DebuggerControllers since we no longer have the lock. So we have to
// do this reference counting thing to make sure that the controllers
// don't get toasted as we're trying to invoke SendEvent on them. We have to
// reaquire the lock before invoking Dequeue because Dequeue may
// result in the controller being deleted, which would change the global
// controller list.
// How: InterlockIncrement( m_eventQueuedCount )
void DebuggerController::Enqueue()
{
LIMITED_METHOD_CONTRACT;
m_eventQueuedCount++;
LOG((LF_CORDB, LL_INFO10000, "DC::Enq DC:0x%x m_eventQueuedCount at 0x%x\n",
this, m_eventQueuedCount));
}
// void DebuggerController::Dequeue() What: Does
// reference counting so we don't toast a
// DebuggerController while it's in a Dispatch queue.
// How: InterlockDecrement( m_eventQueuedCount ), delete this if
// m_eventQueuedCount == 0 AND m_deleted has been set to true
void DebuggerController::Dequeue()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
LOG((LF_CORDB, LL_INFO10000, "DC::Deq DC:0x%x m_eventQueuedCount at 0x%x\n",
this, m_eventQueuedCount));
if (--m_eventQueuedCount == 0)
{
if (m_deleted)
{
TRACE_FREE(this);
DeleteInteropSafe(this);
}
}
}
// bool DebuggerController::BindPatch() If the method has
// been JITted and isn't hashed by address already, then hash
// it into the hashtable by address and not DebuggerFunctionKey.
// If the patch->address field is nonzero, we're done.
// Otherwise ask g_pEEInterface to FindLoadedMethodRefOrDef, then
// GetFunctionAddress of the method, if the method is in IL,
// MapILOffsetToNative. If everything else went Ok, we can now invoke
// g_patches->BindPatch.
// Returns: false if we know that we can't bind the patch immediately.
// true if we either can bind the patch right now, or can't right now,
// but might be able to in the future (eg, the method hasn't been JITted)
// Have following outcomes:
// 1) Succeeded in binding the patch to a raw address. patch->address is set.
// (Note we still must apply the patch to put the int 3 in.)
// returns true, *pFail = false
//
// 2) Fails to bind, but a future attempt may succeed. Obvious ex, for an IL-only
// patch on an unjitted method.
// returns false, *pFail = false
//
// 3) Fails to bind because something's wrong. Ex: bad IL offset, no DJI to do a
// mapping with. Future calls will fail too.
// returns false, *pFail = true
bool DebuggerController::BindPatch(DebuggerControllerPatch *patch,
MethodDesc *fd,
CORDB_ADDRESS_TYPE *startAddr)
{
CONTRACTL
{
SO_NOT_MAINLINE;
THROWS; // from GetJitInfo
GC_NOTRIGGER;
MODE_ANY; // don't really care what mode we're in.
PRECONDITION(ThisMaybeHelperThread());
}
CONTRACTL_END;
_ASSERTE(patch != NULL);
_ASSERTE(!patch->IsILMasterPatch());
_ASSERTE(fd != NULL);
//
// Translate patch to address, if it hasn't been already.
//
if (patch->address != NULL)
{
return true;
}
if (startAddr == NULL)
{
if (patch->HasDJI() && patch->GetDJI()->m_jitComplete)
{
startAddr = (CORDB_ADDRESS_TYPE *) CORDB_ADDRESS_TO_PTR(patch->GetDJI()->m_addrOfCode);
_ASSERTE(startAddr != NULL);
}
if (startAddr == NULL)
{
// Should not be trying to place patches on MethodDecs's for stubs.
// These stubs will never get jitted.
CONSISTENCY_CHECK_MSGF(!fd->IsWrapperStub(), ("Can't place patch at stub md %p, %s::%s",
fd, fd->m_pszDebugClassName, fd->m_pszDebugMethodName));
startAddr = (CORDB_ADDRESS_TYPE *)g_pEEInterface->GetFunctionAddress(fd);
//
// Code is not available yet to patch. The prestub should
// notify us when it is executed.
//
if (startAddr == NULL)
{
LOG((LF_CORDB, LL_INFO10000,
"DC::BP:Patch at 0x%x not bindable yet.\n", patch->offset));
return false;
}
}
}
_ASSERTE(!g_pEEInterface->IsStub((const BYTE *)startAddr));
// If we've jitted, map to a native offset.
DebuggerJitInfo *info = g_pDebugger->GetJitInfo(fd, (const BYTE *)startAddr);
#ifdef LOGGING
if (info == NULL)
{
LOG((LF_CORDB,LL_INFO10000, "DC::BindPa: For startAddr 0x%x, didn't find a DJI\n", startAddr));
}
#endif //LOGGING
if (info != NULL)
{
// There is a strange case with prejitted code and unjitted trace patches. We can enter this function
// with no DebuggerJitInfo created, then have the call just above this actually create the
// DebuggerJitInfo, which causes JitComplete to be called, which causes all patches to be bound! If this
// happens, then we don't need to continue here (its already been done recursivley) and we don't need to
// re-active the patch, so we return false from right here. We can check this by seeing if we suddently
// have the address in the patch set.
if (patch->address != NULL)
{
LOG((LF_CORDB,LL_INFO10000, "DC::BindPa: patch bound recursivley by GetJitInfo, bailing...\n"));
return false;
}
LOG((LF_CORDB,LL_INFO10000, "DC::BindPa: For startAddr 0x%x, got DJI "
"0x%x, from 0x%x size: 0x%x\n", startAddr, info, info->m_addrOfCode, info->m_sizeOfCode));
}
LOG((LF_CORDB, LL_INFO10000, "DC::BP:Trying to bind patch in %s::%s version %d\n",
fd->m_pszDebugClassName, fd->m_pszDebugMethodName, info ? info->m_encVersion : (SIZE_T)-1));
_ASSERTE(g_patches != NULL);
CORDB_ADDRESS_TYPE *addr = (CORDB_ADDRESS_TYPE *)
CodeRegionInfo::GetCodeRegionInfo(NULL, NULL, startAddr).OffsetToAddress(patch->offset);
g_patches->BindPatch(patch, addr);
LOG((LF_CORDB, LL_INFO10000, "DC::BP:Binding patch at 0x%x(off:%x)\n", addr, patch->offset));
return true;
}
// bool DebuggerController::ApplyPatch() applies
// the patch described to the code, and
// remembers the replaced opcode. Note that the same address
// cannot be patched twice at the same time.
// Grabs the opcode & stores in patch, then sets a break
// instruction for either native or IL.
// VirtualProtect & some macros. Returns false if anything
// went bad.
// DebuggerControllerPatch *patch: The patch, indicates where
// to set the INT3 instruction
// Returns: true if the user break instruction was successfully
// placed into the code-stream, false otherwise
bool DebuggerController::ApplyPatch(DebuggerControllerPatch *patch)
{
LOG((LF_CORDB, LL_INFO10000, "DC::ApplyPatch at addr 0x%p\n",
patch->address));
// If we try to apply an already applied patch, we'll overide our saved opcode
// with the break opcode and end up getting a break in out patch bypass buffer.
_ASSERTE(!patch->IsActivated() );
_ASSERTE(patch->IsBound());
// Note we may be patching at certain "blessed" points in mscorwks.
// This is very dangerous b/c we can't be sure patch->Address is blessed or not.
//
// Apply the patch.
//
_ASSERTE(!(g_pConfig->GetGCStressLevel() & (EEConfig::GCSTRESS_INSTR_JIT|EEConfig::GCSTRESS_INSTR_NGEN))
&& "Debugger does not work with GCSTRESS 4");
if (patch->IsNativePatch())
{
if (patch->fSaveOpcode)
{
// We only used SaveOpcode for when we've moved code, so
// the patch should already be there.
patch->opcode = patch->opcodeSaved;
_ASSERTE( AddressIsBreakpoint(patch->address) );
return true;
}
#if _DEBUG
VerifyExecutableAddress((BYTE*)patch->address);
#endif
LPVOID baseAddress = (LPVOID)(patch->address);
DWORD oldProt;
if (!VirtualProtect(baseAddress,
CORDbg_BREAK_INSTRUCTION_SIZE,
PAGE_EXECUTE_READWRITE, &oldProt))
{
_ASSERTE(!"VirtualProtect of code page failed");
return false;
}
patch->opcode = CORDbgGetInstruction(patch->address);
CORDbgInsertBreakpoint((CORDB_ADDRESS_TYPE *)patch->address);
LOG((LF_CORDB, LL_EVERYTHING, "Breakpoint was inserted at %p for opcode %x\n", patch->address, patch->opcode));
if (!VirtualProtect(baseAddress,
CORDbg_BREAK_INSTRUCTION_SIZE,
oldProt, &oldProt))
{
_ASSERTE(!"VirtualProtect of code page failed");
return false;
}
}
// TODO: : determine if this is needed for AMD64
#if defined(_TARGET_X86_) //REVISIT_TODO what is this?!
else
{
DWORD oldProt;
//
// !!! IL patch logic assumes reference insruction encoding
//
if (!VirtualProtect((void *) patch->address, 2,
PAGE_EXECUTE_READWRITE, &oldProt))
{
_ASSERTE(!"VirtualProtect of code page failed");
return false;
}
patch->opcode =
(unsigned int) *(unsigned short*)(patch->address+1);
_ASSERTE(patch->opcode != CEE_BREAK);
*(unsigned short *) (patch->address+1) = CEE_BREAK;
if (!VirtualProtect((void *) patch->address, 2, oldProt, &oldProt))
{
_ASSERTE(!"VirtualProtect of code page failed");
return false;
}
}
#endif //_TARGET_X86_
return true;
}
// bool DebuggerController::UnapplyPatch()
// UnapplyPatch removes the patch described by the patch.
// (CopyOpcodeFromAddrToPatch, in reverse.)
// Looks a lot like CopyOpcodeFromAddrToPatch, except that we use a macro to
// copy the instruction back to the code-stream & immediately set the
// opcode field to 0 so ReadMemory,WriteMemory will work right.
// Note that it's very important to zero out the opcode field, as it
// is used by the right side to determine if a patch is
// valid or not.
// NO LOCKING
// DebuggerControllerPatch * patch: Patch to remove
// Returns: true if the patch was unapplied, false otherwise
bool DebuggerController::UnapplyPatch(DebuggerControllerPatch *patch)
{
_ASSERTE(patch->address != NULL);
_ASSERTE(patch->IsActivated() );
LOG((LF_CORDB,LL_INFO1000, "DC::UP unapply patch at addr 0x%p\n",
patch->address));
if (patch->IsNativePatch())
{
if (patch->fSaveOpcode)
{
// We're doing this for MoveCode, and we don't want to
// overwrite something if we don't get moved far enough.
patch->opcodeSaved = patch->opcode;
InitializePRD(&(patch->opcode));
_ASSERTE( !patch->IsActivated() );
return true;
}
LPVOID baseAddress = (LPVOID)(patch->address);
DWORD oldProt;
if (!VirtualProtect(baseAddress,
CORDbg_BREAK_INSTRUCTION_SIZE,
PAGE_EXECUTE_READWRITE, &oldProt))
{
//
// We may be trying to remove a patch from memory
// which has been unmapped. We can ignore the
// error in this case.
//
InitializePRD(&(patch->opcode));
return false;
}
CORDbgSetInstruction((CORDB_ADDRESS_TYPE *)patch->address, patch->opcode);
//VERY IMPORTANT to zero out opcode, else we might mistake
//this patch for an active on on ReadMem/WriteMem (see
//header file comment)
InitializePRD(&(patch->opcode));
if (!VirtualProtect(baseAddress,
CORDbg_BREAK_INSTRUCTION_SIZE,
oldProt, &oldProt))
{
_ASSERTE(!"VirtualProtect of code page failed");
return false;
}
}
else
{
DWORD oldProt;
if (!VirtualProtect((void *) patch->address, 2,
PAGE_EXECUTE_READWRITE, &oldProt))
{
//
// We may be trying to remove a patch from memory
// which has been unmapped. We can ignore the
// error in this case.
//
InitializePRD(&(patch->opcode));
return false;
}
//
// !!! IL patch logic assumes reference encoding
//
// TODO: : determine if this is needed for AMD64
#if defined(_TARGET_X86_)
_ASSERTE(*(unsigned short*)(patch->address+1) == CEE_BREAK);
*(unsigned short *) (patch->address+1)
= (unsigned short) patch->opcode;
#endif //this makes no sense on anything but X86
//VERY IMPORTANT to zero out opcode, else we might mistake
//this patch for an active on on ReadMem/WriteMem (see
//header file comment
InitializePRD(&(patch->opcode));
if (!VirtualProtect((void *) patch->address, 2, oldProt, &oldProt))
{
_ASSERTE(!"VirtualProtect of code page failed");
return false;
}
}
_ASSERTE( !patch->IsActivated() );
_ASSERTE( patch->IsBound() );
return true;
}
// void DebuggerController::UnapplyPatchAt()
// NO LOCKING
// UnapplyPatchAt removes the patch from a copy of the patched code.
// Like UnapplyPatch, except that we don't bother checking
// memory permissions, but instead replace the breakpoint instruction
// with the opcode at an arbitrary memory address.
void DebuggerController::UnapplyPatchAt(DebuggerControllerPatch *patch,
CORDB_ADDRESS_TYPE *address)
{
_ASSERTE(patch->IsBound() );
if (patch->IsNativePatch())
{
CORDbgSetInstruction((CORDB_ADDRESS_TYPE *)address, patch->opcode);
//note that we don't have to zero out opcode field
//since we're unapplying at something other than
//the original spot. We assert this is true:
_ASSERTE( patch->address != address );
}
else
{
//
// !!! IL patch logic assumes reference encoding
//
// TODO: : determine if this is needed for AMD64
#ifdef _TARGET_X86_
_ASSERTE(*(unsigned short*)(address+1) == CEE_BREAK);
*(unsigned short *) (address+1)
= (unsigned short) patch->opcode;
_ASSERTE( patch->address != address );
#endif // this makes no sense on anything but X86
}
}
// bool DebuggerController::IsPatched() Is there a patch at addr?
// How: if fNative && the instruction at addr is the break
// instruction for this platform.
bool DebuggerController::IsPatched(CORDB_ADDRESS_TYPE *address, BOOL native)
{
LIMITED_METHOD_CONTRACT;
if (native)
{
return AddressIsBreakpoint(address);
}
else
return false;
}
// DWORD DebuggerController::GetPatchedOpcode() Gets the opcode
// at addr, 'looking underneath' any patches if needed.
// GetPatchedInstruction is a function for the EE to call to "see through"
// a patch to the opcodes which was patched.
// How: Lock() grab opcode directly unless there's a patch, in
// which case grab it out of the patch table.
// BYTE * address: The address that we want to 'see through'
// Returns: DWORD value, that is the opcode that should really be there,
// if we hadn't placed a patch there. If we haven't placed a patch
// there, then we'll see the actual opcode at that address.
PRD_TYPE DebuggerController::GetPatchedOpcode(CORDB_ADDRESS_TYPE *address)
{
_ASSERTE(g_patches != NULL);
PRD_TYPE opcode;
ZeroMemory(&opcode, sizeof(opcode));
ControllerLockHolder lockController;
//
// Look for a patch at the address
//
DebuggerControllerPatch *patch = g_patches->GetPatch((CORDB_ADDRESS_TYPE *)address);
if (patch != NULL)
{
// Since we got the patch at this address, is must by definition be bound to that address
_ASSERTE( patch->IsBound() );
_ASSERTE( patch->address == address );
// If we're going to be returning it's opcode, then the patch must also be activated
_ASSERTE( patch->IsActivated() );
opcode = patch->opcode;
}
else
{
//
// Patch was not found - it either is not our patch, or it has
// just been removed. In either case, just return the current
// opcode.
//
if (g_pEEInterface->IsManagedNativeCode((const BYTE *)address))
{
opcode = CORDbgGetInstruction((CORDB_ADDRESS_TYPE *)address);
}
// <REVISIT_TODO>
// TODO: : determine if this is needed for AMD64
// </REVISIT_TODO>
#ifdef _TARGET_X86_ //what is this?!
else
{
//
// !!! IL patch logic assumes reference encoding
//
opcode = *(unsigned short*)(address+1);
}
#endif //_TARGET_X86_
}
return opcode;
}
// Holding the controller lock, this will check if an address is patched,
// and if so will then set the PRT_TYPE out parameter to the unpatched value.
BOOL DebuggerController::CheckGetPatchedOpcode(CORDB_ADDRESS_TYPE *address,
/*OUT*/ PRD_TYPE *pOpcode)
{
CONTRACTL
{
SO_NOT_MAINLINE; // take Controller lock.
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(g_patches != NULL);
BOOL res;
ControllerLockHolder lockController;
//
// Look for a patch at the address
//
if (IsAddressPatched(address))
{
*pOpcode = GetPatchedOpcode(address);
res = TRUE;
}
else
{
InitializePRD(pOpcode);
res = FALSE;
}
return res;
}
// void DebuggerController::ActivatePatch() Place a breakpoint
// so that threads will trip over this patch.
// If there any patches at the address already, then copy
// their opcode into this one & return. Otherwise,
// call ApplyPatch(patch). There is an implicit list of patches at this
// address by virtue of the fact that we can iterate through all the
// patches in the patch with the same address.
// DebuggerControllerPatch *patch: The patch to activate
/* static */ void DebuggerController::ActivatePatch(DebuggerControllerPatch *patch)
{
_ASSERTE(g_patches != NULL);
_ASSERTE(patch != NULL);
_ASSERTE(patch->IsBound() );
_ASSERTE(!patch->IsActivated() );
bool fApply = true;
//
// See if we already have an active patch at this address.
//
for (DebuggerControllerPatch *p = g_patches->GetPatch(patch->address);
p != NULL;
p = g_patches->GetNextPatch(p))
{
if (p != patch)
{
// If we're going to skip activating 'patch' because 'p' already exists at the same address
// then 'p' must be activated. We expect that all bound patches are activated.
_ASSERTE( p->IsActivated() );
patch->opcode = p->opcode;
fApply = false;
break;
}
}
//
// This is the only patch at this address - apply the patch
// to the code.
//
if (fApply)
{
ApplyPatch(patch);
}
_ASSERTE(patch->IsActivated() );
}
// void DebuggerController::DeactivatePatch() Make sure that a
// patch won't be hit.
// How: If this patch is the last one at this address, then
// UnapplyPatch. The caller should then invoke RemovePatch to remove the
// patch from the patch table.
// DebuggerControllerPatch *patch: Patch to deactivate
void DebuggerController::DeactivatePatch(DebuggerControllerPatch *patch)
{
_ASSERTE(g_patches != NULL);
if( !patch->IsBound() ) {
// patch is not bound, nothing to do
return;
}
// We expect that all bound patches are also activated.
// One exception to this is if the shutdown thread killed another thread right after
// if deactivated a patch but before it got to remove it.
_ASSERTE(patch->IsActivated() );
bool fUnapply = true;
//
// See if we already have an active patch at this address.
//
for (DebuggerControllerPatch *p = g_patches->GetPatch(patch->address);
p != NULL;
p = g_patches->GetNextPatch(p))
{
if (p != patch)
{
// There is another patch at this address, so don't remove it
// However, clear the patch data so that we no longer consider this particular patch activated
fUnapply = false;
InitializePRD(&(patch->opcode));
break;
}
}
if (fUnapply)
{
UnapplyPatch(patch);
}
_ASSERTE(!patch->IsActivated() );
//
// Patch must now be removed from the table.
//
}
// AddILMasterPatch: record a patch on IL code but do not bind it or activate it. The master b.p.
// is associated with a module/token pair. It is used later
// (e.g. in MapAndBindFunctionPatches) to create one or more "slave"
// breakpoints which are associated with particular MethodDescs/JitInfos.
//
// Rationale: For generic code a single IL patch (e.g a breakpoint)
// may give rise to several patches, one for each JITting of
// the IL (i.e. generic code may be JITted multiple times for
// different instantiations).
//
// So we keep one patch which describes
// the breakpoint but which is never actually bound or activated.
// This is then used to apply new "slave" patches to all copies of
// JITted code associated with the method.
//
// <REVISIT_TODO>In theory we could bind and apply the master patch when the
// code is known not to be generic (as used to happen to all breakpoint
// patches in V1). However this seems like a premature
// optimization.</REVISIT_TODO>
DebuggerControllerPatch *DebuggerController::AddILMasterPatch(Module *module,
mdMethodDef md,
SIZE_T offset,
SIZE_T encVersion)
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(g_patches != NULL);
ControllerLockHolder ch;
DebuggerControllerPatch *patch = g_patches->AddPatchForMethodDef(this,
module,
md,
offset,
PATCH_KIND_IL_MASTER,
LEAF_MOST_FRAME,
NULL,
encVersion,
NULL);
LOG((LF_CORDB, LL_INFO10000,
"DC::AP: Added IL master patch 0x%x for md 0x%x at offset %d encVersion %d\n", patch, md, offset, encVersion));
return patch;
}
// See notes above on AddILMasterPatch
BOOL DebuggerController::AddBindAndActivateILSlavePatch(DebuggerControllerPatch *master,
DebuggerJitInfo *dji)
{
_ASSERTE(g_patches != NULL);
_ASSERTE(master->IsILMasterPatch());
_ASSERTE(dji != NULL);
// Do not dereference the "master" pointer in the loop! The loop may add more patches,
// causing the patch table to grow and move.
BOOL result = FALSE;
SIZE_T masterILOffset = master->offset;
// Loop through all the native offsets mapped to the given IL offset. On x86 the mapping
// should be 1:1. On WIN64, because there are funclets, we have have an 1:N mapping.
DebuggerJitInfo::ILToNativeOffsetIterator it;
for (dji->InitILToNativeOffsetIterator(it, masterILOffset); !it.IsAtEnd(); it.Next())
{
BOOL fExact;
SIZE_T offsetNative = it.Current(&fExact);
// We special case offset 0, which is when a breakpoint is set
// at the beginning of a method that hasn't been jitted yet. In
// that case it's possible that offset 0 has been optimized out,
// but we still want to set the closest breakpoint to that.
if (!fExact && (masterILOffset != 0))
{
LOG((LF_CORDB, LL_INFO10000, "DC::BP:Failed to bind patch at IL offset 0x%p in %s::%s\n",
masterILOffset, dji->m_fd->m_pszDebugClassName, dji->m_fd->m_pszDebugMethodName));
continue;
}
else
{
result = TRUE;
}
INDEBUG(BOOL fOk = )
AddBindAndActivatePatchForMethodDesc(dji->m_fd, dji,
offsetNative, PATCH_KIND_IL_SLAVE,
LEAF_MOST_FRAME, m_pAppDomain);
_ASSERTE(fOk);
}
// As long as we have successfully bound at least one patch, we consider the operation successful.
return result;
}
// This routine places a patch that is conceptually a patch on the IL code.
// The IL code may be jitted multiple times, e.g. due to generics.
// This routine ensures that both present and subsequent JITtings of code will
// also be patched.
//
// This routine will return FALSE only if we will _never_ be able to
// place the patch in any native code corresponding to the given offset.
// Otherwise it will:
// (a) record a "master" patch
// (b) apply as many slave patches as it can to existing copies of code
// that have debugging information
BOOL DebuggerController::AddILPatch(AppDomain * pAppDomain, Module *module,
mdMethodDef md,
SIZE_T encVersion, // what encVersion does this apply to?
SIZE_T offset)
{
_ASSERTE(g_patches != NULL);
_ASSERTE(md != NULL);
_ASSERTE(module != NULL);
BOOL fOk = FALSE;
DebuggerMethodInfo *dmi = g_pDebugger->GetOrCreateMethodInfo(module, md); // throws
if (dmi == NULL)
{
return false;
}
EX_TRY
{
// OK, we either have (a) no code at all or (b) we have both JIT information and code
//.
// Either way, lay down the MasterPatch.
//
// MapAndBindFunctionPatches will take care of any instantiations that haven't
// finished JITting, by making a copy of the master breakpoint.
DebuggerControllerPatch *master = AddILMasterPatch(module, md, offset, encVersion);
// We have to keep the index here instead of the pointer. The loop below adds more patches,
// which may cause the patch table to grow and move.
ULONG masterIndex = g_patches->GetItemIndex((HASHENTRY*)master);
// Iterate through every existing NativeCodeBlob (with the same EnC version).
// This includes generics + prejitted code.
DebuggerMethodInfo::DJIIterator it;
dmi->IterateAllDJIs(pAppDomain, NULL /* module filter */, &it);
if (it.IsAtEnd())
{
// It is okay if we don't have any DJIs yet. It just means that the method hasn't been jitted.
fOk = TRUE;
}
else
{
// On the other hand, if the method has been jitted, then we expect to be able to bind at least
// one breakpoint. The exception is when we have multiple EnC versions of the method, in which
// case it is ok if we don't bind any breakpoint. One scenario is when a method has been updated
// via EnC but it's not yet jitted. We need to allow a debugger to put a breakpoint on the new
// version of the method, but the new version won't have a DJI yet.
BOOL fVersionMatch = FALSE;
while(!it.IsAtEnd())
{
DebuggerJitInfo *dji = it.Current();
_ASSERTE(dji->m_jitComplete);
if (dji->m_encVersion == encVersion)
{
fVersionMatch = TRUE;
master = (DebuggerControllerPatch *)g_patches->GetEntryPtr(masterIndex);
// <REVISIT_TODO> If we're missing JIT info for any then
// we won't have applied the bp to every instantiation. That should probably be reported
// as a new kind of condition to the debugger, i.e. report "bp only partially applied". It would be
// a shame to completely fail just because on instantiation is missing debug info: e.g. just because
// one component hasn't been prejitted with debugging information.</REVISIT_TODO>
fOk = (AddBindAndActivateILSlavePatch(master, dji) || fOk);
}
it.Next();
}
// This is the exceptional case referred to in the comment above. If we fail to put a breakpoint
// because we don't have a matching version of the method, we need to return TRUE.
if (fVersionMatch == FALSE)
{
fOk = TRUE;
}
}
}
EX_CATCH
{
fOk = FALSE;
}
EX_END_CATCH(SwallowAllExceptions)
return fOk;
}
// Add a patch at native-offset 0 in the latest version of the method.
// This is used by step-in.
// Calls to new methods always go to the latest version, so EnC is not an issue here.
// The method may be not yet jitted. Or it may be prejitted.
void DebuggerController::AddPatchToStartOfLatestMethod(MethodDesc * fd)
{
CONTRACTL
{
SO_NOT_MAINLINE;
THROWS; // from GetJitInfo
GC_NOTRIGGER;
MODE_ANY; // don't really care what mode we're in.
PRECONDITION(ThisMaybeHelperThread());
PRECONDITION(CheckPointer(fd));
}
CONTRACTL_END;
_ASSERTE(g_patches != NULL);
DebuggerController::AddBindAndActivatePatchForMethodDesc(fd, NULL, 0, PATCH_KIND_NATIVE_MANAGED, LEAF_MOST_FRAME, NULL);
return;
}
// Place patch in method at native offset.
BOOL DebuggerController::AddBindAndActivateNativeManagedPatch(MethodDesc * fd,
DebuggerJitInfo *dji,
SIZE_T offsetNative,
FramePointer fp,
AppDomain *pAppDomain)
{
CONTRACTL
{
SO_NOT_MAINLINE;
THROWS; // from GetJitInfo
GC_NOTRIGGER;
MODE_ANY; // don't really care what mode we're in.
PRECONDITION(ThisMaybeHelperThread());
PRECONDITION(CheckPointer(fd));
PRECONDITION(fd->IsDynamicMethod() || (dji != NULL));
}
CONTRACTL_END;
// For non-dynamic methods, we always expect to have a DJI, but just in case, we don't want the assert to AV.
_ASSERTE((dji == NULL) || (fd == dji->m_fd));
_ASSERTE(g_patches != NULL);
return DebuggerController::AddBindAndActivatePatchForMethodDesc(fd, dji, offsetNative, PATCH_KIND_NATIVE_MANAGED, fp, pAppDomain);
}
BOOL DebuggerController::AddBindAndActivatePatchForMethodDesc(MethodDesc *fd,
DebuggerJitInfo *dji,
SIZE_T offset,
DebuggerPatchKind kind,
FramePointer fp,
AppDomain *pAppDomain)
{
CONTRACTL
{
SO_NOT_MAINLINE;
THROWS;
GC_NOTRIGGER;
MODE_ANY; // don't really care what mode we're in.
PRECONDITION(ThisMaybeHelperThread());
}
CONTRACTL_END;
BOOL ok = FALSE;
ControllerLockHolder ch;
LOG((LF_CORDB|LF_ENC,LL_INFO10000,"DC::AP: Add to %s::%s, at offs 0x%x "
"fp:0x%x AD:0x%x\n", fd->m_pszDebugClassName,
fd->m_pszDebugMethodName,
offset, fp.GetSPValue(), pAppDomain));
DebuggerControllerPatch *patch = g_patches->AddPatchForMethodDef(
this,
g_pEEInterface->MethodDescGetModule(fd),
fd->GetMemberDef(),
offset,
kind,
fp,
pAppDomain,
NULL,
dji);
if (DebuggerController::BindPatch(patch, fd, NULL))
{
LOG((LF_CORDB|LF_ENC,LL_INFO1000,"BindPatch went fine, doing ActivatePatch\n"));
DebuggerController::ActivatePatch(patch);
ok = TRUE;
}
return ok;
}
// This version is particularly useful b/c it doesn't assume that the
// patch is inside a managed method.
DebuggerControllerPatch *DebuggerController::AddAndActivateNativePatchForAddress(CORDB_ADDRESS_TYPE *address,
FramePointer fp,
bool managed,
TraceType traceType)
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_NOTRIGGER;
PRECONDITION(g_patches != NULL);
}
CONTRACTL_END;
ControllerLockHolder ch;
DebuggerControllerPatch *patch
= g_patches->AddPatchForAddress(this,
NULL,
0,
(managed? PATCH_KIND_NATIVE_MANAGED : PATCH_KIND_NATIVE_UNMANAGED),
address,
fp,
NULL,
NULL,
DebuggerPatchTable::DCP_PID_INVALID,
traceType);
ActivatePatch(patch);
return patch;
}
void DebuggerController::RemovePatchesFromModule(Module *pModule, AppDomain *pAppDomain )
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
LOG((LF_CORDB, LL_INFO100000, "DPT::CPFM mod:0x%p (%S)\n",
pModule, pModule->GetDebugName()));
// First find all patches of interest
DebuggerController::ControllerLockHolder ch;
HASHFIND f;
for (DebuggerControllerPatch *patch = g_patches->GetFirstPatch(&f);
patch != NULL;
patch = g_patches->GetNextPatch(&f))
{
// Skip patches not in the specified domain
if ((pAppDomain != NULL) && (patch->pAppDomain != pAppDomain))
continue;
BOOL fRemovePatch = FALSE;
// Remove both native and IL patches the belong to this module
if (patch->HasDJI())
{
DebuggerJitInfo * dji = patch->GetDJI();
_ASSERTE(patch->key.module == dji->m_fd->GetModule());
// It is not necessary to check for m_fd->GetModule() here. It will
// be covered by other module unload notifications issued for the appdomain.
if ( dji->m_pLoaderModule == pModule )
fRemovePatch = TRUE;
}
else
if (patch->key.module == pModule)
{
fRemovePatch = TRUE;
}
if (fRemovePatch)
{
LOG((LF_CORDB, LL_EVERYTHING, "Removing patch 0x%p\n",
patch));
// we shouldn't be both hitting this patch AND
// unloading the module it belongs to.
_ASSERTE(!patch->IsTriggering());
Release( patch );
}
}
}
#ifdef _DEBUG
bool DebuggerController::ModuleHasPatches( Module* pModule )
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
if( g_patches == NULL )
{
// Patch table hasn't been initialized
return false;
}
// First find all patches of interest
HASHFIND f;
for (DebuggerControllerPatch *patch = g_patches->GetFirstPatch(&f);
patch != NULL;
patch = g_patches->GetNextPatch(&f))
{
//
// This mirrors logic in code:DebuggerController::RemovePatchesFromModule
//
if (patch->HasDJI())
{
DebuggerJitInfo * dji = patch->GetDJI();
_ASSERTE(patch->key.module == dji->m_fd->GetModule());
// It may be sufficient to just check m_pLoaderModule here. Since this is used for debug-only
// check, we will check for m_fd->GetModule() as well to catch more potential problems.
if ( (dji->m_pLoaderModule == pModule) || (dji->m_fd->GetModule() == pModule) )
{
return true;
}
}
if (patch->key.module == pModule)
{
return true;
}
}
return false;
}
#endif // _DEBUG
//
// Returns true if the given address is in an internal helper
// function, false if its not.
//
// This is a temporary workaround function to avoid having us stop in
// unmanaged code belonging to the Runtime during a StepIn operation.
//
static bool _AddrIsJITHelper(PCODE addr)
{
#if !defined(_WIN64) && !defined(FEATURE_PAL)
// Is the address in the runtime dll (clr.dll or coreclr.dll) at all? (All helpers are in
// that dll)
if (g_runtimeLoadedBaseAddress <= addr &&
addr < g_runtimeLoadedBaseAddress + g_runtimeVirtualSize)
{
for (int i = 0; i < CORINFO_HELP_COUNT; i++)
{
if (hlpFuncTable[i].pfnHelper == (void*)addr)
{
LOG((LF_CORDB, LL_INFO10000,
"_ANIM: address of helper function found: 0x%08x\n",
addr));
return true;
}
}
for (unsigned d = 0; d < DYNAMIC_CORINFO_HELP_COUNT; d++)
{
if (hlpDynamicFuncTable[d].pfnHelper == (void*)addr)
{
LOG((LF_CORDB, LL_INFO10000,
"_ANIM: address of helper function found: 0x%08x\n",
addr));
return true;
}
}
LOG((LF_CORDB, LL_INFO10000,
"_ANIM: address within runtime dll, but not a helper function "
"0x%08x\n", addr));
}
#else // !defined(_WIN64) && !defined(FEATURE_PAL)
// TODO: Figure out what we want to do here
#endif // !defined(_WIN64) && !defined(FEATURE_PAL)
return false;
}
// bool DebuggerController::PatchTrace() What: Invoke
// AddPatch depending on the type of the given TraceDestination.
// How: Invokes AddPatch based on the trace type: TRACE_OTHER will
// return false, the others will obtain args for a call to an AddPatch
// method & return true.
//
// Return true if we set a patch, else false
bool DebuggerController::PatchTrace(TraceDestination *trace,
FramePointer fp,
bool fStopInUnmanaged)
{
CONTRACTL
{
THROWS; // Because AddPatch may throw on oom. We may want to convert this to nothrow and return false.
MODE_ANY;
DISABLED(GC_TRIGGERS); // @todo - what should this be?
PRECONDITION(ThisMaybeHelperThread());
}
CONTRACTL_END;
DebuggerControllerPatch *dcp = NULL;
switch (trace->GetTraceType())
{
case TRACE_ENTRY_STUB: // fall through
case TRACE_UNMANAGED:
LOG((LF_CORDB, LL_INFO10000,
"DC::PT: Setting unmanaged trace patch at 0x%p(%p)\n",
trace->GetAddress(), fp.GetSPValue()));
if (fStopInUnmanaged && !_AddrIsJITHelper(trace->GetAddress()))
{
AddAndActivateNativePatchForAddress((CORDB_ADDRESS_TYPE *)trace->GetAddress(),
fp,
FALSE,
trace->GetTraceType());
return true;
}
else
{
LOG((LF_CORDB, LL_INFO10000, "DC::PT: decided to NOT "
"place a patch in unmanaged code\n"));
return false;
}
case TRACE_MANAGED:
LOG((LF_CORDB, LL_INFO10000,
"Setting managed trace patch at 0x%p(%p)\n", trace->GetAddress(), fp.GetSPValue()));
MethodDesc *fd;
fd = g_pEEInterface->GetNativeCodeMethodDesc(trace->GetAddress());
_ASSERTE(fd);
DebuggerJitInfo *dji;
dji = g_pDebugger->GetJitInfoFromAddr(trace->GetAddress());
//_ASSERTE(dji); //we'd like to assert this, but attach won't work
AddBindAndActivateNativeManagedPatch(fd,
dji,
CodeRegionInfo::GetCodeRegionInfo(dji, fd).AddressToOffset((const BYTE *)trace->GetAddress()),
fp,
NULL);
return true;
case TRACE_UNJITTED_METHOD:
// trace->address is actually a MethodDesc* of the method that we'll
// soon JIT, so put a relative bp at offset zero in.
LOG((LF_CORDB, LL_INFO10000,
"Setting unjitted method patch in MethodDesc 0x%p %s\n", trace->GetMethodDesc(), trace->GetMethodDesc() ? trace->GetMethodDesc()->m_pszDebugMethodName : ""));
// Note: we have to make sure to bind here. If this function is prejitted, this may be our only chance to get a
// DebuggerJITInfo and thereby cause a JITComplete callback.
AddPatchToStartOfLatestMethod(trace->GetMethodDesc());
return true;
case TRACE_FRAME_PUSH:
LOG((LF_CORDB, LL_INFO10000,
"Setting frame patch at 0x%p(%p)\n", trace->GetAddress(), fp.GetSPValue()));
AddAndActivateNativePatchForAddress((CORDB_ADDRESS_TYPE *)trace->GetAddress(),
fp,
TRUE,
TRACE_FRAME_PUSH);
return true;
case TRACE_MGR_PUSH:
LOG((LF_CORDB, LL_INFO10000,
"Setting frame patch (TRACE_MGR_PUSH) at 0x%p(%p)\n",
trace->GetAddress(), fp.GetSPValue()));
dcp = AddAndActivateNativePatchForAddress((CORDB_ADDRESS_TYPE *)trace->GetAddress(),
LEAF_MOST_FRAME, // But Mgr_push can't have fp affinity!
TRUE,
DPT_DEFAULT_TRACE_TYPE); // TRACE_OTHER
// Now copy over the trace field since TriggerPatch will expect this
// to be set for this case.
if (dcp != NULL)
{
dcp->trace = *trace;
}
return true;
case TRACE_OTHER:
LOG((LF_CORDB, LL_INFO10000,
"Can't set a trace patch for TRACE_OTHER...\n"));
return false;
default:
_ASSERTE(0);
return false;
}
}
//-----------------------------------------------------------------------------
// Checks if the patch matches the context + thread.
// Multiple patches can exist at a single address, so given a patch at the
// Context's current address, this does additional patch-affinity checks like
// thread, AppDomain, and frame-pointer.
// thread - thread executing the given context that hit the patch
// context - context of the thread that hit the patch
// patch - candidate patch that we're looking for a match.
// Returns:
// True if the patch matches.
// False
//-----------------------------------------------------------------------------
bool DebuggerController::MatchPatch(Thread *thread,
CONTEXT *context,
DebuggerControllerPatch *patch)
{
LOG((LF_CORDB, LL_INFO100000, "DC::MP: EIP:0x%p\n", GetIP(context)));
// Caller should have already matched our addresses.
if (patch->address != dac_cast<PTR_CORDB_ADDRESS_TYPE>(GetIP(context)))
{
return false;
}
// <BUGNUM>RAID 67173 -</BUGNUM> we'll make sure that intermediate patches have NULL
// pAppDomain so that we don't end up running to completion when
// the appdomain switches halfway through a step.
if (patch->pAppDomain != NULL)
{
AppDomain *pAppDomainCur = thread->GetDomain();
if (pAppDomainCur != patch->pAppDomain)
{
LOG((LF_CORDB, LL_INFO10000, "DC::MP: patches didn't match b/c of "
"appdomains!\n"));
return false;
}
}
if (patch->controller->m_thread != NULL && patch->controller->m_thread != thread)
{
LOG((LF_CORDB, LL_INFO10000, "DC::MP: patches didn't match b/c threads\n"));
return false;
}
if (patch->fp != LEAF_MOST_FRAME)
{
// If we specified a Frame-pointer, than it should have been safe to take a stack trace.
ControllerStackInfo info;
StackTraceTicket ticket(patch);
info.GetStackInfo(ticket, thread, LEAF_MOST_FRAME, context);
// !!! This check should really be != , but there is some ambiguity about which frame is the parent frame
// in the destination returned from Frame::TraceFrame, so this allows some slop there.
if (info.HasReturnFrame() && IsCloserToLeaf(info.m_returnFrame.fp, patch->fp))
{
LOG((LF_CORDB, LL_INFO10000, "Patch hit but frame not matched at %p (current=%p, patch=%p)\n",
patch->address, info.m_returnFrame.fp.GetSPValue(), patch->fp.GetSPValue()));
return false;
}
}
LOG((LF_CORDB, LL_INFO100000, "DC::MP: Returning true"));
return true;
}
DebuggerPatchSkip *DebuggerController::ActivatePatchSkip(Thread *thread,
const BYTE *PC,
BOOL fForEnC)
{
#ifdef _DEBUG
BOOL shouldBreak = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ActivatePatchSkip);
if (shouldBreak > 0) {
_ASSERTE(!"ActivatePatchSkip");
}
#endif
LOG((LF_CORDB,LL_INFO10000, "DC::APS thread=0x%p pc=0x%p fForEnc=%d\n",
thread, PC, fForEnC));
_ASSERTE(g_patches != NULL);
// Previously, we assumed that if we got to this point & the patch
// was still there that we'd have to skip the patch. SetIP changes
// this like so:
// A breakpoint is set, and hit (but not removed), and all the
// EE threads come to a skreeching halt. The Debugger RC thread
// continues along, and is told to SetIP of the thread that hit
// the BP to whatever. Eventually the RC thread is told to continue,
// and at that point the EE thread is released, finishes DispatchPatchOrSingleStep,
// and shows up here.
// At that point, if the thread's current PC is
// different from the patch PC, then SetIP must have moved it elsewhere
// & we shouldn't do this patch skip (which will put us back to where
// we were, which is clearly wrong). If the PC _is_ the same, then
// the thread hasn't been moved, the patch is still in the code stream,
// and we want to do the patch skip thing in order to execute this
// instruction w/o removing it from the code stream.
DebuggerControllerPatch *patch = g_patches->GetPatch((CORDB_ADDRESS_TYPE *)PC);
DebuggerPatchSkip *skip = NULL;
if (patch != NULL && patch->IsNativePatch())
{
//
// We adjust the thread's PC to someplace where we write
// the next instruction, then
// we single step over that, then we set the PC back here so
// we don't let other threads race past here while we're stepping
// this one.
//
// !!! check result
LOG((LF_CORDB,LL_INFO10000, "DC::APS: About to skip from PC=0x%p\n", PC));
skip = new (interopsafe) DebuggerPatchSkip(thread, patch, thread->GetDomain());
TRACE_ALLOC(skip);
}
return skip;
}
DPOSS_ACTION DebuggerController::ScanForTriggers(CORDB_ADDRESS_TYPE *address,
Thread *thread,
CONTEXT *context,
DebuggerControllerQueue *pDcq,
SCAN_TRIGGER stWhat,
TP_RESULT *pTpr)
{
CONTRACTL
{
SO_NOT_MAINLINE;
// @todo - should this throw or not?
NOTHROW;
// call Triggers which may invoke GC stuff... See comment in DispatchNativeException for why it's disabled.
DISABLED(GC_TRIGGERS);
PRECONDITION(!ThisIsHelperThreadWorker());
PRECONDITION(CheckPointer(address));
PRECONDITION(CheckPointer(thread));
PRECONDITION(CheckPointer(context));
PRECONDITION(CheckPointer(pDcq));
PRECONDITION(CheckPointer(pTpr));
}
CONTRACTL_END;
_ASSERTE(HasLock());
CONTRACT_VIOLATION(ThrowsViolation);
LOG((LF_CORDB, LL_INFO10000, "DC::SFT: starting scan for addr:0x%p"
" thread:0x%x\n", address, thread));
_ASSERTE( pTpr != NULL );
DebuggerControllerPatch *patch = NULL;
if (g_patches != NULL)
patch = g_patches->GetPatch(address);
ULONG iEvent = UINT32_MAX;
ULONG iEventNext = UINT32_MAX;
BOOL fDone = FALSE;
// This is a debugger exception if there's a patch here, or
// we're here for something like a single step.
DPOSS_ACTION used = DPOSS_INVALID;
if ((patch != NULL) || !IsPatched(address, TRUE))
{
// we are sure that we care for this exception but not sure
// if we will send event to the RS
used = DPOSS_USED_WITH_NO_EVENT;
}
else
{
// initialize it to don't care for now
used = DPOSS_DONT_CARE;
}
TP_RESULT tpr = TPR_IGNORE;
while (stWhat & ST_PATCH &&
patch != NULL &&
!fDone)
{
_ASSERTE(IsInUsedAction(used) == true);
DebuggerControllerPatch *patchNext
= g_patches->GetNextPatch(patch);
LOG((LF_CORDB, LL_INFO10000, "DC::SFT: patch 0x%x, patchNext 0x%x\n", patch, patchNext));
// Annoyingly, TriggerPatch may add patches, which may cause
// the patch table to move, which may, in turn, invalidate
// the patch (and patchNext) pointers. Store indeces, instead.
iEvent = g_patches->GetItemIndex( (HASHENTRY *)patch );
if (patchNext != NULL)
{
iEventNext = g_patches->GetItemIndex((HASHENTRY *)patchNext);
}
if (MatchPatch(thread, context, patch))
{
LOG((LF_CORDB, LL_INFO10000, "DC::SFT: patch matched\n"));
AddRef(patch);
// We are hitting a patch at a virtual trace call target, so let's trigger trace call here.
if (patch->trace.GetTraceType() == TRACE_ENTRY_STUB)
{
patch->controller->TriggerTraceCall(thread, dac_cast<PTR_CBYTE>(::GetIP(context)));
tpr = TPR_IGNORE;
}
else
{
// Mark if we're at an unsafe place.
AtSafePlaceHolder unsafePlaceHolder(thread);
tpr = patch->controller->TriggerPatch(patch,
thread,
TY_NORMAL);
}
// Any patch may potentially send an event.
// (Whereas some single-steps are "internal-only" and can
// never send an event- such as a single step over an exception that
// lands us in la-la land.)
used = DPOSS_USED_WITH_EVENT;
if (tpr == TPR_TRIGGER ||
tpr == TPR_TRIGGER_ONLY_THIS ||
tpr == TPR_TRIGGER_ONLY_THIS_AND_LOOP)
{
// Make sure we've still got a valid pointer.
patch = (DebuggerControllerPatch *)
DebuggerController::g_patches->GetEntryPtr( iEvent );
pDcq->dcqEnqueue(patch->controller, TRUE); // <REVISIT_TODO>@todo Return value</REVISIT_TODO>
}
// Make sure we've got a valid pointer in case TriggerPatch
// returned false but still caused the table to move.
patch = (DebuggerControllerPatch *)
g_patches->GetEntryPtr( iEvent );
// A patch can be deleted as a result of it's being triggered.
// The actual deletion of the patch is delayed until after the
// the end of the trigger.
// Moreover, "patchNext" could have been deleted as a result of DisableAll()
// being called in TriggerPatch(). Thus, we should update our patchNext
// pointer now. We were just lucky before, because the now-deprecated
// "deleted" flag didn't get set when we iterate the patches in DisableAll().
patchNext = g_patches->GetNextPatch(patch);
if (patchNext != NULL)
iEventNext = g_patches->GetItemIndex((HASHENTRY *)patchNext);
// Note that Release() actually removes the patch if its ref count
// reaches 0 after the release.
Release(patch);
}
if (tpr == TPR_IGNORE_AND_STOP ||
tpr == TPR_TRIGGER_ONLY_THIS ||
tpr == TPR_TRIGGER_ONLY_THIS_AND_LOOP)
{
#ifdef _DEBUG
if (tpr == TPR_TRIGGER_ONLY_THIS ||
tpr == TPR_TRIGGER_ONLY_THIS_AND_LOOP)
_ASSERTE(pDcq->dcqGetCount() == 1);
#endif //_DEBUG
fDone = TRUE;
}
else if (patchNext != NULL)
{
patch = (DebuggerControllerPatch *)
g_patches->GetEntryPtr(iEventNext);
}
else
{
patch = NULL;
}
}
if (stWhat & ST_SINGLE_STEP &&
tpr != TPR_TRIGGER_ONLY_THIS)
{
LOG((LF_CORDB, LL_INFO10000, "DC::SFT: Trigger controllers with single step\n"));
//
// Now, go ahead & trigger all controllers with
// single step events
//
DebuggerController *p;
p = g_controllers;
while (p != NULL)
{
DebuggerController *pNext = p->m_next;
if (p->m_thread == thread && p->m_singleStep)
{
if (used == DPOSS_DONT_CARE)
{
// Debugger does care for this exception.
used = DPOSS_USED_WITH_NO_EVENT;
}
if (p->TriggerSingleStep(thread, (const BYTE *)address))
{
// by now, we should already know that we care for this exception.
_ASSERTE(IsInUsedAction(used) == true);
// now we are sure that we will send event to the RS
used = DPOSS_USED_WITH_EVENT;
pDcq->dcqEnqueue(p, FALSE); // <REVISIT_TODO>@todo Return value</REVISIT_TODO>
}
}
p = pNext;
}
UnapplyTraceFlag(thread);
//
// See if we have any steppers still active for this thread, if so
// re-apply the trace flag.
//
p = g_controllers;
while (p != NULL)
{
if (p->m_thread == thread && p->m_singleStep)
{
ApplyTraceFlag(thread);
break;
}
p = p->m_next;
}
}
// Significant speed increase from single dereference, I bet :)
(*pTpr) = tpr;
LOG((LF_CORDB, LL_INFO10000, "DC::SFT returning 0x%x as used\n",used));
return used;
}
#ifdef EnC_SUPPORTED
DebuggerControllerPatch *DebuggerController::IsXXXPatched(const BYTE *PC,
DEBUGGER_CONTROLLER_TYPE dct)
{
_ASSERTE(g_patches != NULL);
DebuggerControllerPatch *patch = g_patches->GetPatch((CORDB_ADDRESS_TYPE *)PC);
while(patch != NULL &&
(int)patch->controller->GetDCType() <= (int)dct)
{
if (patch->IsNativePatch() &&
patch->controller->GetDCType()==dct)
{
return patch;
}
patch = g_patches->GetNextPatch(patch);
}
return NULL;
}
// This function will check for an EnC patch at the given address and return
// it if one is there, otherwise it will return NULL.
DebuggerControllerPatch *DebuggerController::GetEnCPatch(const BYTE *address)
{
_ASSERTE(address);
if( g_pEEInterface->IsManagedNativeCode(address) )
{
DebuggerJitInfo *dji = g_pDebugger->GetJitInfoFromAddr((TADDR) address);
if (dji == NULL)
return NULL;
// we can have two types of patches - one in code where the IL has been updated to trigger
// the switch and the other in the code we've switched to in order to trigger FunctionRemapComplete
// callback. If version == default then can't be the latter, but otherwise if haven't handled the
// remap for this function yet is certainly the latter.
if (! dji->m_encBreakpointsApplied &&
(dji->m_encVersion == CorDB_DEFAULT_ENC_FUNCTION_VERSION))
{
return NULL;
}
}
return IsXXXPatched(address, DEBUGGER_CONTROLLER_ENC);
}
#endif //EnC_SUPPORTED
// DebuggerController::DispatchPatchOrSingleStep - Ask any patches that are active at a given
// address if they want to do anything about the exception that's occurred there. How: For the given
// address, go through the list of patches & see if any of them are interested (by invoking their
// DebuggerController's TriggerPatch). Put any DCs that are interested into a queue and then calls
// SendEvent on each.
// Note that control will not return from this function in the case of EnC remap
DPOSS_ACTION DebuggerController::DispatchPatchOrSingleStep(Thread *thread, CONTEXT *context, CORDB_ADDRESS_TYPE *address, SCAN_TRIGGER which)
{
CONTRACT(DPOSS_ACTION)
{
// @todo - should this throw or not?
NOTHROW;
DISABLED(GC_TRIGGERS); // Only GC triggers if we send an event. See Comment in DispatchNativeException
PRECONDITION(!ThisIsHelperThreadWorker());
PRECONDITION(CheckPointer(thread));
PRECONDITION(CheckPointer(context));
PRECONDITION(CheckPointer(address));
PRECONDITION(!HasLock());
POSTCONDITION(!HasLock()); // make sure we're not leaking the controller lock
}
CONTRACT_END;
CONTRACT_VIOLATION(ThrowsViolation);
LOG((LF_CORDB|LF_ENC,LL_INFO1000,"DC:DPOSS at 0x%x trigger:0x%x\n", address, which));
// We should only have an exception if some managed thread was running.
// Thus we should never be here when we're stopped.
// @todo - this assert fires! Is that an issue, or is it invalid?
//_ASSERTE(!g_pDebugger->IsStopped());
DPOSS_ACTION used = DPOSS_DONT_CARE;
DebuggerControllerQueue dcq;
if (!g_patchTableValid)
{
LOG((LF_CORDB|LF_ENC, LL_INFO1000, "DC::DPOSS returning, no patch table.\n"));
RETURN (used);
}
_ASSERTE(g_patches != NULL);
CrstHolderWithState lockController(&g_criticalSection);
TADDR originalAddress = 0;
#ifdef EnC_SUPPORTED
DebuggerControllerPatch *dcpEnCOriginal = NULL;
// If this sequence point has an EnC patch, we want to process it ahead of any others. If the
// debugger wants to remap the function at this point, then we'll call ResumeInUpdatedFunction and
// not return, otherwise we will just continue with regular patch-handling logic
dcpEnCOriginal = GetEnCPatch(dac_cast<PTR_CBYTE>(GetIP(context)));
if (dcpEnCOriginal)
{
LOG((LF_CORDB|LF_ENC,LL_INFO10000, "DC::DPOSS EnC short-circuit\n"));
TP_RESULT tpres =
dcpEnCOriginal->controller->TriggerPatch(dcpEnCOriginal,
thread,
TY_SHORT_CIRCUIT);
// We will only come back here on a RemapOppporunity that wasn't taken, or on a RemapComplete.
// If we processed a RemapComplete (which returns TPR_IGNORE_AND_STOP), then don't want to handle
// additional breakpoints on the current line because we've already effectively executed to that point
// and would have hit them already. If they are new, we also don't want to hit them because eg. if are
// sitting on line 10 and add a breakpoint at line 10 and step,
// don't expect to stop at line 10, expect to go to line 11.
//
// Special case is if an EnC remap breakpoint exists in the function. This could only happen if the function was
// updated between the RemapOpportunity and the RemapComplete. In that case we want to not skip the patches
// and fall through to handle the remap breakpoint.
if (tpres == TPR_IGNORE_AND_STOP)
{
// It was a RemapComplete, so fall through. Set dcpEnCOriginal to NULL to indicate that any
// EnC patch still there should be treated as a new patch. Any RemapComplete patch will have been
// already removed by patch processing.
dcpEnCOriginal = NULL;
LOG((LF_CORDB|LF_ENC,LL_INFO10000, "DC::DPOSS done EnC short-circuit, exiting\n"));
used = DPOSS_USED_WITH_EVENT; // indicate that we handled a patch
goto Exit;
}
_ASSERTE(tpres==TPR_IGNORE);
LOG((LF_CORDB|LF_ENC,LL_INFO10000, "DC::DPOSS done EnC short-circuit, ignoring\n"));
// if we got here, then the EnC remap opportunity was not taken, so just continue on.
}
#endif // EnC_SUPPORTED
TP_RESULT tpr;
used = ScanForTriggers((CORDB_ADDRESS_TYPE *)address, thread, context, &dcq, which, &tpr);
LOG((LF_CORDB|LF_ENC, LL_EVERYTHING, "DC::DPOSS ScanForTriggers called and returned.\n"));
// If we setip, then that will change the address in the context.
// Remeber the old address so that we can compare it to the context's ip and see if it changed.
// If it did change, then don't dispatch our current event.
originalAddress = (TADDR) address;
#ifdef _DEBUG
// If we do a SetIP after this point, the value of address will be garbage. Set it to a distictive pattern now, so
// we don't accidentally use what will (98% of the time) appear to be a valid value.
address = (CORDB_ADDRESS_TYPE *)(UINT_PTR)0xAABBCCFF;
#endif //_DEBUG
if (dcq.dcqGetCount()> 0)
{
lockController.Release();
// Mark if we're at an unsafe place.
bool atSafePlace = g_pDebugger->IsThreadAtSafePlace(thread);
if (!atSafePlace)
g_pDebugger->IncThreadsAtUnsafePlaces();
DWORD dwEvent = 0xFFFFFFFF;
DWORD dwNumberEvents = 0;
BOOL reabort = FALSE;
SENDIPCEVENT_BEGIN(g_pDebugger, thread);
// Now that we've resumed from blocking, check if somebody did a SetIp on us.
bool fIpChanged = (originalAddress != GetIP(context));
// Send the events outside of the controller lock
bool anyEventsSent = false;
dwNumberEvents = dcq.dcqGetCount();
dwEvent = 0;
while (dwEvent < dwNumberEvents)
{
DebuggerController *event = dcq.dcqGetElement(dwEvent);
if (!event->m_deleted)
{
#ifdef DEBUGGING_SUPPORTED
if (thread->GetDomain()->IsDebuggerAttached())
{
if (event->SendEvent(thread, fIpChanged))
{
anyEventsSent = true;
}
}
#endif //DEBUGGING_SUPPORTED
}
dwEvent++;
}
// Trap all threads if necessary, but only if we actually sent a event up (i.e., all the queued events weren't
// deleted before we got a chance to get the EventSending lock.)
if (anyEventsSent)
{
LOG((LF_CORDB|LF_ENC, LL_EVERYTHING, "DC::DPOSS We sent an event\n"));
g_pDebugger->SyncAllThreads(SENDIPCEVENT_PtrDbgLockHolder);
LOG((LF_CORDB,LL_INFO1000, "SAT called!\n"));
}
// If we need to to a re-abort (see below), then save the current IP in the thread's context before we block and
// possibly let another func eval get setup.
reabort = thread->m_StateNC & Thread::TSNC_DebuggerReAbort;
SENDIPCEVENT_END;
if (!atSafePlace)
g_pDebugger->DecThreadsAtUnsafePlaces();
lockController.Acquire();
// Dequeue the events while we have the controller lock.
dwEvent = 0;
while (dwEvent < dwNumberEvents)
{
dcq.dcqDequeue();
dwEvent++;
}
// If a func eval completed with a ThreadAbortException, go ahead and setup the thread to re-abort itself now
// that we're continuing the thread. Note: we make sure that the thread's IP hasn't changed between now and when
// we blocked above. While blocked above, the debugger has a chance to setup another func eval on this
// thread. If that happens, we don't want to setup the reabort just yet.
if (reabort)
{
if ((UINT_PTR)GetEEFuncEntryPoint(::FuncEvalHijack) != (UINT_PTR)GetIP(context))
{
HRESULT hr;
hr = g_pDebugger->FuncEvalSetupReAbort(thread, Thread::TAR_Thread);
_ASSERTE(SUCCEEDED(hr));
}
}
}
#if defined EnC_SUPPORTED
Exit:
#endif
// Note: if the thread filter context is NULL, then SetIP would have failed & thus we should do the
// patch skip thing.
// @todo - do we need to get the context again here?
CONTEXT *pCtx = GetManagedLiveCtx(thread);
#ifdef EnC_SUPPORTED
DebuggerControllerPatch *dcpEnCCurrent = GetEnCPatch(dac_cast<PTR_CBYTE>((GetIP(context))));
// we have a new patch if the original was null and the current is non-null. Otherwise we have an old
// patch. We want to skip old patches, but handle new patches.
if (dcpEnCOriginal == NULL && dcpEnCCurrent != NULL)
{
LOG((LF_CORDB|LF_ENC,LL_INFO10000, "DC::DPOSS EnC post-processing\n"));
dcpEnCCurrent->controller->TriggerPatch( dcpEnCCurrent,
thread,
TY_SHORT_CIRCUIT);
used = DPOSS_USED_WITH_EVENT; // indicate that we handled a patch
}
#endif
ActivatePatchSkip(thread, dac_cast<PTR_CBYTE>(GetIP(pCtx)), FALSE);
lockController.Release();
// We pulse the GC mode here too cooperate w/ a thread trying to suspend the runtime. If we didn't pulse
// the GC, the odds of catching this thread in interuptable code may be very small (since this filter
// could be very large compared to the managed code this thread is running).
// Only do this if the exception was actually for the debugger. (We don't want to toggle the GC mode on every
// random exception). We can't do this while holding any debugger locks.
if (used == DPOSS_USED_WITH_EVENT)
{
bool atSafePlace = g_pDebugger->IsThreadAtSafePlace(thread);
if (!atSafePlace)
{
g_pDebugger->IncThreadsAtUnsafePlaces();
}
// Always pulse the GC mode. This will allow an async break to complete even if we have a patch
// at an unsafe place.
// If we are at an unsafe place, then we can't do a GC.
thread->PulseGCMode();
if (!atSafePlace)
{
g_pDebugger->DecThreadsAtUnsafePlaces();
}
}
RETURN used;
}
bool DebuggerController::IsSingleStepEnabled()
{
LIMITED_METHOD_CONTRACT;
return m_singleStep;
}
void DebuggerController::EnableSingleStep()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
#ifdef _DEBUG
// Some controllers don't need to set the SS to do their job, and if they are setting it, it's likely an issue.
// So we assert here to catch them red-handed. This assert can always be updated to accomodate changes
// in a controller's behavior.
switch(GetDCType())
{
case DEBUGGER_CONTROLLER_THREAD_STARTER:
case DEBUGGER_CONTROLLER_BREAKPOINT:
case DEBUGGER_CONTROLLER_USER_BREAKPOINT:
case DEBUGGER_CONTROLLER_FUNC_EVAL_COMPLETE:
CONSISTENCY_CHECK_MSGF(false, ("Controller pThis=%p shouldn't be setting ss flag.", this));
break;
default: // MingW compilers require all enum cases to be handled in switch statement.
break;
}
#endif
EnableSingleStep(m_thread);
m_singleStep = true;
}
#ifdef EnC_SUPPORTED
// Note that this doesn't tell us if Single Stepping is currently enabled
// at the hardware level (ie, for x86, if (context->EFlags & 0x100), but
// rather, if we WANT single stepping enabled (pThread->m_State &Thread::TS_DebuggerIsStepping)
// This gets called from exactly one place - ActivatePatchSkipForEnC
BOOL DebuggerController::IsSingleStepEnabled(Thread *pThread)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
// This should be an atomic operation, do we
// don't need to lock it.
if(pThread->m_StateNC & Thread::TSNC_DebuggerIsStepping)
{
_ASSERTE(pThread->m_StateNC & Thread::TSNC_DebuggerIsStepping);
return TRUE;
}
else
return FALSE;
}
#endif //EnC_SUPPORTED
void DebuggerController::EnableSingleStep(Thread *pThread)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
LOG((LF_CORDB,LL_INFO1000, "DC::EnableSingleStep\n"));
_ASSERTE(pThread != NULL);
ControllerLockHolder lockController;
ApplyTraceFlag(pThread);
}
// Disable Single stepping for this controller.
// If none of the controllers on this thread want single-stepping, then also
// ensure that it's disabled on the hardware level.
void DebuggerController::DisableSingleStep()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(m_thread != NULL);
LOG((LF_CORDB,LL_INFO1000, "DC::DisableSingleStep\n"));
ControllerLockHolder lockController;
{
DebuggerController *p = g_controllers;
m_singleStep = false;
while (p != NULL)
{
if (p->m_thread == m_thread
&& p->m_singleStep)
break;
p = p->m_next;
}
if (p == NULL)
{
UnapplyTraceFlag(m_thread);
}
}
}
//
// ApplyTraceFlag sets the trace flag (i.e., turns on single-stepping)
// for a thread.
//
void DebuggerController::ApplyTraceFlag(Thread *thread)
{
LOG((LF_CORDB,LL_INFO1000, "DC::ApplyTraceFlag thread:0x%x [0x%0x]\n", thread, Debugger::GetThreadIdHelper(thread)));
CONTEXT *context;
if(thread->GetInteropDebuggingHijacked())
{
context = GetManagedLiveCtx(thread);
}
else
{
context = GetManagedStoppedCtx(thread);
}
CONSISTENCY_CHECK_MSGF(context != NULL, ("Can't apply ss flag to thread 0x%p b/c it's not in a safe place.\n", thread));
PREFIX_ASSUME(context != NULL);
g_pEEInterface->MarkThreadForDebugStepping(thread, true);
LOG((LF_CORDB,LL_INFO1000, "DC::ApplyTraceFlag marked thread for debug stepping\n"));
SetSSFlag(reinterpret_cast<DT_CONTEXT *>(context) ARM_ARG(thread));
LOG((LF_CORDB,LL_INFO1000, "DC::ApplyTraceFlag Leaving, baby!\n"));
}
//
// UnapplyTraceFlag sets the trace flag for a thread.
// Removes the hardware trace flag on this thread.
//
void DebuggerController::UnapplyTraceFlag(Thread *thread)
{
LOG((LF_CORDB,LL_INFO1000, "DC::UnapplyTraceFlag thread:0x%x\n", thread));
// Either this is the helper thread, or we're manipulating our own context.
_ASSERTE(
ThisIsHelperThreadWorker() ||
(thread == ::GetThread())
);
CONTEXT *context = GetManagedStoppedCtx(thread);
// If there's no context available, then the thread shouldn't have the single-step flag
// enabled and there's nothing for us to do.
if (context == NULL)
{
// In theory, I wouldn't expect us to ever get here.
// Even if we are here, our single-step flag should already be deactivated,
// so there should be nothing to do. However, we still assert b/c we want to know how
// we'd actually hit this.
// @todo - is there a path if TriggerUnwind() calls DisableAll(). But why would
CONSISTENCY_CHECK_MSGF(false, ("How did we get here?. thread=%p\n", thread));
LOG((LF_CORDB,LL_INFO1000, "DC::UnapplyTraceFlag couldn't get context.\n"));
return;
}
// Always need to unmark for stepping
g_pEEInterface->MarkThreadForDebugStepping(thread, false);
UnsetSSFlag(reinterpret_cast<DT_CONTEXT *>(context) ARM_ARG(thread));
}
void DebuggerController::EnableExceptionHook()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(m_thread != NULL);
ControllerLockHolder lockController;
m_exceptionHook = true;
}
void DebuggerController::DisableExceptionHook()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(m_thread != NULL);
ControllerLockHolder lockController;
m_exceptionHook = false;
}
// void DebuggerController::DispatchExceptionHook() Called before
// the switch statement in DispatchNativeException (therefore
// when any exception occurs), this allows patches to do something before the
// regular DispatchX methods.
// How: Iterate through list of controllers. If m_exceptionHook
// is set & m_thread is either thread or NULL, then invoke TriggerExceptionHook()
BOOL DebuggerController::DispatchExceptionHook(Thread *thread,
CONTEXT *context,
EXCEPTION_RECORD *pException)
{
// ExceptionHook has restrictive contract b/c it could come from anywhere.
// This can only modify controller's internal state. Can't send managed debug events.
CONTRACTL
{
SO_NOT_MAINLINE;
GC_NOTRIGGER;
NOTHROW;
MODE_ANY;
// Filter context not set yet b/c we can only set it in COOP, and this may be in preemptive.
PRECONDITION(thread == ::GetThread());
PRECONDITION((g_pEEInterface->GetThreadFilterContext(thread) == NULL));
PRECONDITION(CheckPointer(pException));
}
CONTRACTL_END;
LOG((LF_CORDB, LL_INFO1000, "DC:: DispatchExceptionHook\n"));
if (!g_patchTableValid)
{
LOG((LF_CORDB, LL_INFO1000, "DC::DEH returning, no patch table.\n"));
return (TRUE);
}
_ASSERTE(g_patches != NULL);
ControllerLockHolder lockController;
TP_RESULT tpr = TPR_IGNORE;
DebuggerController *p;
p = g_controllers;
while (p != NULL)
{
DebuggerController *pNext = p->m_next;
if (p->m_exceptionHook
&& (p->m_thread == NULL || p->m_thread == thread) &&
tpr != TPR_IGNORE_AND_STOP)
{
LOG((LF_CORDB, LL_INFO1000, "DC::DEH calling TEH...\n"));
tpr = p->TriggerExceptionHook(thread, context , pException);
LOG((LF_CORDB, LL_INFO1000, "DC::DEH ... returned.\n"));
if (tpr == TPR_IGNORE_AND_STOP)
{
LOG((LF_CORDB, LL_INFO1000, "DC:: DEH: leaving early!\n"));
break;
}
}
p = pNext;
}
LOG((LF_CORDB, LL_INFO1000, "DC:: DEH: returning 0x%x!\n", tpr));
return (tpr != TPR_IGNORE_AND_STOP);
}
//
// EnableUnwind enables an unwind event to be called when the stack is unwound
// (via an exception) to or past the given pointer.
//
void DebuggerController::EnableUnwind(FramePointer fp)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
ASSERT(m_thread != NULL);
LOG((LF_CORDB,LL_EVERYTHING,"DC:EU EnableUnwind at 0x%x\n", fp.GetSPValue()));
ControllerLockHolder lockController;
m_unwindFP = fp;
}
FramePointer DebuggerController::GetUnwind()
{
LIMITED_METHOD_CONTRACT;
return m_unwindFP;
}
//
// DisableUnwind disables the unwind event for the controller.
//
void DebuggerController::DisableUnwind()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
CAN_TAKE_LOCK;
}
CONTRACTL_END;
ASSERT(m_thread != NULL);
LOG((LF_CORDB,LL_INFO1000, "DC::DU\n"));
ControllerLockHolder lockController;
m_unwindFP = LEAF_MOST_FRAME;
}
//
// DispatchUnwind is called when an unwind happens.
// the event to the appropriate controllers.
// - handlerFP is the frame pointer that the handler will be invoked at.
// - DJI is EnC-aware method that the handler is in.
// - newOffset is the
//
bool DebuggerController::DispatchUnwind(Thread *thread,
MethodDesc *fd, DebuggerJitInfo * pDJI,
SIZE_T newOffset,
FramePointer handlerFP,
CorDebugStepReason unwindReason)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER; // don't send IPC events
MODE_COOPERATIVE; // TriggerUnwind always is coop
PRECONDITION(!IsDbgHelperSpecialThread());
}
CONTRACTL_END;
CONTRACT_VIOLATION(ThrowsViolation); // trigger unwind throws
_ASSERTE(unwindReason == STEP_EXCEPTION_FILTER || unwindReason == STEP_EXCEPTION_HANDLER);
bool used = false;
LOG((LF_CORDB, LL_INFO10000, "DC: Dispatch Unwind\n"));
ControllerLockHolder lockController;
{
DebuggerController *p;
p = g_controllers;
while (p != NULL)
{
DebuggerController *pNext = p->m_next;
if (p->m_thread == thread && p->m_unwindFP != LEAF_MOST_FRAME)
{
LOG((LF_CORDB, LL_INFO10000, "Dispatch Unwind: Found candidate\n"));
// Assumptions here:
// Function with handlers are -ALWAYS- EBP-frame based (JIT assumption)
//
// newFrame is the EBP for the handler
// p->m_unwindFP points to the stack slot with the return address of the function.
//
// For the interesting case: stepover, we want to know if the handler is in the same function
// as the stepper, if its above it (caller) o under it (callee) in order to know if we want
// to patch the handler or not.
//
// 3 cases:
//
// a) Handler is in a function under the function where the step happened. It therefore is
// a stepover. We don't want to patch this handler. The handler will have an EBP frame.
// So it will be at least be 2 DWORDs away from the m_unwindFP of the controller (
// 1 DWORD from the pushed return address and 1 DWORD for the push EBP).
//
// b) Handler is in the same function as the stepper. We want to patch the handler. In this
// case handlerFP will be the same as p->m_unwindFP-sizeof(void*). Why? p->m_unwindFP
// stores a pointer to the return address of the function. As a function with a handler
// is always EBP frame based it will have the following code in the prolog:
//
// push ebp <- ( sub esp, 4 ; mov [esp], ebp )
// mov esp, ebp
//
// Therefore EBP will be equal to &CallerReturnAddress-4.
//
// c) Handler is above the function where the stepper is. We want to patch the handler. handlerFP
// will be always greater than the pointer to the return address of the function where the
// stepper is.
//
//
//
if (IsEqualOrCloserToRoot(handlerFP, p->m_unwindFP))
{
used = true;
//
// Assume that this isn't going to block us at all --
// other threads may be waiting to patch or unpatch something,
// or to dispatch.
//
LOG((LF_CORDB, LL_INFO10000,
"Unwind trigger at offset 0x%p; handlerFP: 0x%p unwindReason: 0x%x.\n",
newOffset, handlerFP.GetSPValue(), unwindReason));
p->TriggerUnwind(thread,
fd, pDJI,
newOffset,
handlerFP,
unwindReason);
}
else
{
LOG((LF_CORDB, LL_INFO10000,
"Unwind trigger at offset 0x%p; handlerFP: 0x%p unwindReason: 0x%x.\n",
newOffset, handlerFP.GetSPValue(), unwindReason));
}
}
p = pNext;
}
}
return used;
}
//
// EnableTraceCall enables a call event on the controller
// maxFrame is the leaf-most frame that we want notifications for.
// For step-in stuff, this will always be LEAF_MOST_FRAME.
// for step-out, this will be the current frame because we don't
// care if the current frame calls back into managed code when we're
// only interested in our parent frames.
//
void DebuggerController::EnableTraceCall(FramePointer maxFrame)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
ASSERT(m_thread != NULL);
LOG((LF_CORDB,LL_INFO1000, "DC::ETC maxFrame=0x%x, thread=0x%x\n",
maxFrame.GetSPValue(), Debugger::GetThreadIdHelper(m_thread)));
// JMC stepper should never enabled this. (They should enable ME instead).
_ASSERTE((DEBUGGER_CONTROLLER_JMC_STEPPER != this->GetDCType()) || !"JMC stepper shouldn't enable trace-call");
ControllerLockHolder lockController;
{
if (!m_traceCall)
{
m_traceCall = true;
g_pEEInterface->EnableTraceCall(m_thread);
}
if (IsCloserToLeaf(maxFrame, m_traceCallFP))
m_traceCallFP = maxFrame;
}
}
struct PatchTargetVisitorData
{
DebuggerController* controller;
FramePointer maxFrame;
};
VOID DebuggerController::PatchTargetVisitor(TADDR pVirtualTraceCallTarget, VOID* pUserData)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
DebuggerController* controller = ((PatchTargetVisitorData*) pUserData)->controller;
FramePointer maxFrame = ((PatchTargetVisitorData*) pUserData)->maxFrame;
EX_TRY
{
CONTRACT_VIOLATION(GCViolation); // PatchTrace throws, which implies GC-triggers
TraceDestination trace;
trace.InitForUnmanagedStub(pVirtualTraceCallTarget);
controller->PatchTrace(&trace, maxFrame, true);
}
EX_CATCH
{
// not much we can do here
}
EX_END_CATCH(SwallowAllExceptions)
}
//
// DisableTraceCall disables call events on the controller
//
void DebuggerController::DisableTraceCall()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
ASSERT(m_thread != NULL);
ControllerLockHolder lockController;
{
if (m_traceCall)
{
LOG((LF_CORDB,LL_INFO1000, "DC::DTC thread=0x%x\n",
Debugger::GetThreadIdHelper(m_thread)));
g_pEEInterface->DisableTraceCall(m_thread);
m_traceCall = false;
m_traceCallFP = ROOT_MOST_FRAME;
}
}
}
// Get a FramePointer for the leafmost frame on this thread's stacktrace.
// It's tempting to create this off the head of the Frame chain, but that may
// include internal EE Frames (like GCRoot frames) which a FrameInfo-stackwalk may skip over.
// Thus using the Frame chain would err on the side of returning a FramePointer that
// closer to the leaf.
FramePointer GetCurrentFramePointerFromStackTraceForTraceCall(Thread * thread)
{
_ASSERTE(thread != NULL);
// Ensure this is really the same as CSI.
ControllerStackInfo info;
// It's possible this stackwalk may be done at an unsafe time.
// this method may trigger a GC, for example, in
// FramedMethodFrame::AskStubForUnmanagedCallSite
// which will trash the incoming argument array
// which is not gc-protected.
// We could probably imagine a more specialized stackwalk that
// avoids these calls and is thus GC_NOTRIGGER.
CONTRACT_VIOLATION(GCViolation);
// This is being run live, so there's no filter available.
CONTEXT *context;
context = g_pEEInterface->GetThreadFilterContext(thread);
_ASSERTE(context == NULL);
_ASSERTE(!ISREDIRECTEDTHREAD(thread));
// This is actually safe because we're coming from a TraceCall, which
// means we're not in the middle of a stub. We don't have some partially
// constructed frame, so we can safely traverse the stack.
// However, we may still have a problem w/ the GC-violation.
StackTraceTicket ticket(StackTraceTicket::SPECIAL_CASE_TICKET);
info.GetStackInfo(ticket, thread, LEAF_MOST_FRAME, NULL);
FramePointer fp = info.m_activeFrame.fp;
return fp;
}
//
// DispatchTraceCall is called when a call is traced in the EE
// It dispatches the event to the appropriate controllers.
//
bool DebuggerController::DispatchTraceCall(Thread *thread,
const BYTE *ip)
{
CONTRACTL
{
GC_NOTRIGGER;
THROWS;
}
CONTRACTL_END;
bool used = false;
LOG((LF_CORDB, LL_INFO10000,
"DC::DTC: TraceCall at 0x%x\n", ip));
ControllerLockHolder lockController;
{
DebuggerController *p;
p = g_controllers;
while (p != NULL)
{
DebuggerController *pNext = p->m_next;
if (p->m_thread == thread && p->m_traceCall)
{
bool trigger;
if (p->m_traceCallFP == LEAF_MOST_FRAME)
trigger = true;
else
{
// We know we don't have a filter context, so get a frame pointer from our frame chain.
FramePointer fpToCheck = GetCurrentFramePointerFromStackTraceForTraceCall(thread);
// <REVISIT_TODO>
//
// Currently, we never ever put a patch in an IL stub, and as such, if the IL stub
// throws an exception after returning from unmanaged code, we would not trigger
// a trace call when we call the constructor of the exception. The following is
// kind of a workaround to make that working. If we ever make the change to stop in
// IL stubs (for example, if we start to share security IL stub), then this can be
// removed.
//
// </REVISIT_TODO>
// It's possible this stackwalk may be done at an unsafe time.
// this method may trigger a GC, for example, in
// FramedMethodFrame::AskStubForUnmanagedCallSite
// which will trash the incoming argument array
// which is not gc-protected.
ControllerStackInfo info;
{
CONTRACT_VIOLATION(GCViolation);
#ifdef _DEBUG
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(thread);
#endif // _DEBUG
_ASSERTE(context == NULL);
_ASSERTE(!ISREDIRECTEDTHREAD(thread));
// See explanation in GetCurrentFramePointerFromStackTraceForTraceCall.
StackTraceTicket ticket(StackTraceTicket::SPECIAL_CASE_TICKET);
info.GetStackInfo(ticket, thread, LEAF_MOST_FRAME, NULL);
}
if (info.m_activeFrame.chainReason == CHAIN_ENTER_UNMANAGED)
{
_ASSERTE(info.HasReturnFrame());
// This check makes sure that we don't do this logic for inlined frames.
if (info.m_returnFrame.md->IsILStub())
{
// Make sure that the frame pointer of the active frame is actually
// the address of an exit frame.
_ASSERTE( (static_cast<Frame*>(info.m_activeFrame.fp.GetSPValue()))->GetFrameType()
== Frame::TYPE_EXIT );
_ASSERTE(!info.m_returnFrame.HasChainMarker());
fpToCheck = info.m_returnFrame.fp;
}
}
// @todo - This comparison seems somewhat nonsensical. We don't have a filter context
// in place, so what frame pointer is fpToCheck actually for?
trigger = IsEqualOrCloserToRoot(fpToCheck, p->m_traceCallFP);
}
if (trigger)
{
used = true;
// This can only update controller's state, can't actually send IPC events.
p->TriggerTraceCall(thread, ip);
}
}
p = pNext;
}
}
return used;
}
bool DebuggerController::IsMethodEnterEnabled()
{
LIMITED_METHOD_CONTRACT;
return m_fEnableMethodEnter;
}
// Notify dispatching logic that this controller wants to get TriggerMethodEnter
// We keep a count of total controllers waiting for MethodEnter (in g_cTotalMethodEnter).
// That way we know if any controllers want MethodEnter callbacks. If none do,
// then we can set the JMC probe flag to false for all modules.
void DebuggerController::EnableMethodEnter()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
ControllerLockHolder chController;
Debugger::DebuggerDataLockHolder chInfo(g_pDebugger);
// Both JMC + Traditional steppers may use MethodEnter.
// For JMC, it's a core part of functionality. For Traditional steppers, we use it as a backstop
// in case the stub-managers fail.
_ASSERTE(g_cTotalMethodEnter >= 0);
if (!m_fEnableMethodEnter)
{
LOG((LF_CORDB, LL_INFO1000000, "DC::EnableME, this=%p, previously disabled\n", this));
m_fEnableMethodEnter = true;
g_cTotalMethodEnter++;
}
else
{
LOG((LF_CORDB, LL_INFO1000000, "DC::EnableME, this=%p, already set\n", this));
}
g_pDebugger->UpdateAllModuleJMCFlag(g_cTotalMethodEnter != 0); // Needs JitInfo lock
}
// Notify dispatching logic that this controller doesn't want to get
// TriggerMethodEnter
void DebuggerController::DisableMethodEnter()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
ControllerLockHolder chController;
Debugger::DebuggerDataLockHolder chInfo(g_pDebugger);
if (m_fEnableMethodEnter)
{
LOG((LF_CORDB, LL_INFO1000000, "DC::DisableME, this=%p, previously set\n", this));
m_fEnableMethodEnter = false;
g_cTotalMethodEnter--;
_ASSERTE(g_cTotalMethodEnter >= 0);
}
else
{
LOG((LF_CORDB, LL_INFO1000000, "DC::DisableME, this=%p, already disabled\n", this));
}
g_pDebugger->UpdateAllModuleJMCFlag(g_cTotalMethodEnter != 0); // Needs JitInfo lock
}
// Loop through controllers and dispatch TriggerMethodEnter
void DebuggerController::DispatchMethodEnter(void * pIP, FramePointer fp)
{
_ASSERTE(pIP != NULL);
Thread * pThread = g_pEEInterface->GetThread();
_ASSERTE(pThread != NULL);
// Lookup the DJI for this method & ip.
// Since we create DJIs when we jit the code, and this code has been jitted
// (that's where the probe's coming from!), we will have a DJI.
DebuggerJitInfo * dji = g_pDebugger->GetJitInfoFromAddr((TADDR) pIP);
// This includes the case where we have a LightWeight codegen method.
if (dji == NULL)
{
return;
}
LOG((LF_CORDB, LL_INFO100000, "DC::DispatchMethodEnter for '%s::%s'\n",
dji->m_fd->m_pszDebugClassName,
dji->m_fd->m_pszDebugMethodName));
ControllerLockHolder lockController;
// For debug check, keep a count to make sure that g_cTotalMethodEnter
// is actually the number of controllers w/ MethodEnter enabled.
int count = 0;
DebuggerController *p = g_controllers;
while (p != NULL)
{
if (p->m_fEnableMethodEnter)
{
if ((p->GetThread() == NULL) || (p->GetThread() == pThread))
{
++count;
p->TriggerMethodEnter(pThread, dji, (const BYTE *) pIP, fp);
}
}
p = p->m_next;
}
_ASSERTE(g_cTotalMethodEnter == count);
}
//
// AddProtection adds page protection to (at least) the given range of
// addresses
//
void DebuggerController::AddProtection(const BYTE *start, const BYTE *end,
bool readable)
{
// !!!
_ASSERTE(!"Not implemented yet");
}
//
// RemoveProtection removes page protection from the given
// addresses. The parameters should match an earlier call to
// AddProtection
//
void DebuggerController::RemoveProtection(const BYTE *start, const BYTE *end,
bool readable)
{
// !!!
_ASSERTE(!"Not implemented yet");
}
// Default implementations for FuncEvalEnter & Exit notifications.
void DebuggerController::TriggerFuncEvalEnter(Thread * thread)
{
LOG((LF_CORDB, LL_INFO100000, "DC::TFEEnter, thead=%p, this=%p\n", thread, this));
}
void DebuggerController::TriggerFuncEvalExit(Thread * thread)
{
LOG((LF_CORDB, LL_INFO100000, "DC::TFEExit, thead=%p, this=%p\n", thread, this));
}
// bool DebuggerController::TriggerPatch() What: Tells the
// static DC whether this patch should be activated now.
// Returns true if it should be, false otherwise.
// How: Base class implementation returns false. Others may
// return true.
TP_RESULT DebuggerController::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
LOG((LF_CORDB, LL_INFO10000, "DC::TP: in default TriggerPatch\n"));
return TPR_IGNORE;
}
bool DebuggerController::TriggerSingleStep(Thread *thread,
const BYTE *ip)
{
LOG((LF_CORDB, LL_INFO10000, "DC::TP: in default TriggerSingleStep\n"));
return false;
}
void DebuggerController::TriggerUnwind(Thread *thread,
MethodDesc *fd, DebuggerJitInfo * pDJI, SIZE_T offset,
FramePointer fp,
CorDebugStepReason unwindReason)
{
LOG((LF_CORDB, LL_INFO10000, "DC::TP: in default TriggerUnwind\n"));
}
void DebuggerController::TriggerTraceCall(Thread *thread,
const BYTE *ip)
{
LOG((LF_CORDB, LL_INFO10000, "DC::TP: in default TriggerTraceCall\n"));
}
TP_RESULT DebuggerController::TriggerExceptionHook(Thread *thread, CONTEXT * pContext,
EXCEPTION_RECORD *exception)
{
LOG((LF_CORDB, LL_INFO10000, "DC::TP: in default TriggerExceptionHook\n"));
return TPR_IGNORE;
}
void DebuggerController::TriggerMethodEnter(Thread * thread,
DebuggerJitInfo * dji,
const BYTE * ip,
FramePointer fp)
{
LOG((LF_CORDB, LL_INFO10000, "DC::TME in default impl. dji=%p, addr=%p, fp=%p\n",
dji, ip, fp.GetSPValue()));
}
bool DebuggerController::SendEvent(Thread *thread, bool fIpChanged)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
SENDEVENT_CONTRACT_ITEMS;
}
CONTRACTL_END;
LOG((LF_CORDB, LL_INFO10000, "DC::TP: in default SendEvent\n"));
// If any derived class trigger SendEvent, it should also implement SendEvent.
_ASSERTE(false || !"Base DebuggerController sending an event?");
return false;
}
// Dispacth Func-Eval Enter & Exit notifications.
void DebuggerController::DispatchFuncEvalEnter(Thread * thread)
{
LOG((LF_CORDB, LL_INFO100000, "DC::DispatchFuncEvalEnter for thread 0x%p\n", thread));
ControllerLockHolder lockController;
DebuggerController *p = g_controllers;
while (p != NULL)
{
if ((p->GetThread() == NULL) || (p->GetThread() == thread))
{
p->TriggerFuncEvalEnter(thread);
}
p = p->m_next;
}
}
void DebuggerController::DispatchFuncEvalExit(Thread * thread)
{
LOG((LF_CORDB, LL_INFO100000, "DC::DispatchFuncEvalExit for thread 0x%p\n", thread));
ControllerLockHolder lockController;
DebuggerController *p = g_controllers;
while (p != NULL)
{
if ((p->GetThread() == NULL) || (p->GetThread() == thread))
{
p->TriggerFuncEvalExit(thread);
}
p = p->m_next;
}
}
#ifdef _DEBUG
// See comment in DispatchNativeException
void ThisFunctionMayHaveTriggerAGC()
{
CONTRACTL
{
SO_NOT_MAINLINE;
GC_TRIGGERS;
NOTHROW;
}
CONTRACTL_END;
}
#endif
// bool DebuggerController::DispatchNativeException() Figures out
// if any debugger controllers will handle the exception.
// DispatchNativeException should be called by the EE when a native exception
// occurs. If it returns true, the exception was generated by a Controller and
// should be ignored.
// How: Calls DispatchExceptionHook to see if anything is
// interested in ExceptionHook, then does a switch on dwCode:
// EXCEPTION_BREAKPOINT means invoke DispatchPatchOrSingleStep(ST_PATCH).
// EXCEPTION_SINGLE_STEP means DispatchPatchOrSingleStep(ST_SINGLE_STEP).
// EXCEPTION_ACCESS_VIOLATION means invoke DispatchAccessViolation.
// Returns true if the exception was actually meant for the debugger,
// returns false otherwise.
bool DebuggerController::DispatchNativeException(EXCEPTION_RECORD *pException,
CONTEXT *pContext,
DWORD dwCode,
Thread *pCurThread)
{
CONTRACTL
{
SO_INTOLERANT;
NOTHROW;
// If this exception is for the debugger, then we may trigger a GC.
// But we'll be called on _any_ exception, including ones in a GC-no-triggers region.
// Our current contract system doesn't let us specify such conditions on GC_TRIGGERS.
// So we disable it now, and if we find out the exception is meant for the debugger,
// we'll call ThisFunctionMayHaveTriggerAGC() to ping that we're really a GC_TRIGGERS.
DISABLED(GC_TRIGGERS); // Only GC triggers if we send an event,
PRECONDITION(!IsDbgHelperSpecialThread());
// If we're called from preemptive mode, than our caller has protected the stack.
// If we're in cooperative mode, then we need to protect the stack before toggling GC modes
// (by setting the filter-context)
MODE_ANY;
PRECONDITION(CheckPointer(pException));
PRECONDITION(CheckPointer(pContext));
PRECONDITION(CheckPointer(pCurThread));
}
CONTRACTL_END;
LOG((LF_CORDB, LL_EVERYTHING, "DispatchNativeException was called\n"));
LOG((LF_CORDB, LL_INFO10000, "Native exception at 0x%p, code=0x%8x, context=0x%p, er=0x%p\n",
pException->ExceptionAddress, dwCode, pContext, pException));
bool fDebuggers;
BOOL fDispatch;
DPOSS_ACTION result = DPOSS_DONT_CARE;
// We have a potentially ugly locking problem here. This notification is called on any exception,
// but we have no idea what our locking context is at the time. Thus we may hold locks smaller
// than the controller lock.
// The debugger logic really only cares about exceptions directly in managed code (eg, hardware exceptions)
// or in patch-skippers (since that's a copy of managed code running in a look-aside buffer).
// That should exclude all C++ exceptions, which are the common case if Runtime code throws an internal ex.
// So we ignore those to avoid the lock violation.
if (pException->ExceptionCode == EXCEPTION_MSVC)
{
LOG((LF_CORDB, LL_INFO1000, "Debugger skipping for C++ exception.\n"));
return FALSE;
}
// The debugger really only cares about exceptions in managed code. Any exception that occurs
// while the thread is redirected (such as EXCEPTION_HIJACK) is not of interest to the debugger.
// Allowing this would be problematic because when an exception occurs while the thread is
// redirected, we don't know which context (saved redirection context or filter context)
// we should be operating on (see code:GetManagedStoppedCtx).
if( ISREDIRECTEDTHREAD(pCurThread) )
{
LOG((LF_CORDB, LL_INFO1000, "Debugger ignoring exception 0x%x on redirected thread.\n", dwCode));
// We shouldn't be seeing debugging exceptions on a redirected thread. While a thread is
// redirected we only call a few internal things (see code:Thread.RedirectedHandledJITCase),
// and may call into the host. We can't call normal managed code or anything we'd want to debug.
_ASSERTE(dwCode != EXCEPTION_BREAKPOINT);
_ASSERTE(dwCode != EXCEPTION_SINGLE_STEP);
return FALSE;
}
// It's possible we're here without a debugger (since we have to call the
// patch skippers). The Debugger may detach anytime,
// so remember the attach state now.
#ifdef _DEBUG
bool fWasAttached = false;
#ifdef DEBUGGING_SUPPORTED
fWasAttached = (CORDebuggerAttached() != 0);
#endif //DEBUGGING_SUPPORTED
#endif //_DEBUG
{
// If we're in cooperative mode, it's unsafe to do a GC until we've put a filter context in place.
GCX_NOTRIGGER();
// If we know the debugger doesn't care about this exception, bail now.
// Usually this is just if there's a debugger attached.
// However, if a debugger detached but left outstanding controllers (like patch-skippers),
// we still may care.
// The only way a controller would get created outside of the helper thread is from
// a patch skipper, so we always handle breakpoints.
if (!CORDebuggerAttached() && (g_controllers == NULL) && (dwCode != EXCEPTION_BREAKPOINT))
{
return false;
}
FireEtwDebugExceptionProcessingStart();
// We should never be here if the debugger was never involved.
CONTEXT * pOldContext;
pOldContext = pCurThread->GetFilterContext();
// In most cases it is an error to nest, however in the patch-skipping logic we must
// copy an unknown amount of code into another buffer and it occasionally triggers
// an AV. This heuristic should filter that case out. See DDB 198093.
// Ensure we perform this exception nesting filtering even before the call to
// DebuggerController::DispatchExceptionHook, otherwise the nesting will continue when
// a contract check is triggered in DispatchExceptionHook and another BP exception is
// raised. See Dev11 66058.
if ((pOldContext != NULL) && pCurThread->AVInRuntimeImplOkay() &&
pException->ExceptionCode == STATUS_ACCESS_VIOLATION)
{
STRESS_LOG1(LF_CORDB, LL_INFO100, "DC::DNE Nested Access Violation at 0x%p is being ignored\n",
pException->ExceptionAddress);
return false;
}
// Otherwise it is an error to nest at all
_ASSERTE(pOldContext == NULL);
fDispatch = DebuggerController::DispatchExceptionHook(pCurThread,
pContext,
pException);
{
// Must be in cooperative mode to set the filter context. We know there are times we'll be in preemptive mode,
// (such as M2U handoff, or potentially patches in the middle of a stub, or various random exceptions)
// @todo - We need to worry about GC-protecting our stack. If we're in preemptive mode, the caller did it for us.
// If we're in cooperative, then we need to set the FilterContext *before* we toggle GC mode (since
// the FC protects the stack).
// If we're in preemptive, then we need to set the FilterContext *after* we toggle ourselves to Cooperative.
// Also note it may not be possible to toggle GC mode at these times (such as in the middle of the stub).
//
// Part of the problem is that the Filter Context is serving 2 purposes here:
// - GC protect the stack. (essential if we're in coop mode).
// - provide info to controllers (such as current IP, and a place to set the Single-Step flag).
//
// This contract violation is mitigated in that we must have had the debugger involved to get to this point.
CONTRACT_VIOLATION(ModeViolation);
g_pEEInterface->SetThreadFilterContext(pCurThread, pContext);
}
// Now that we've set the filter context, we can let the GCX_NOTRIGGER expire.
// It's still possible that we may be called from a No-trigger region.
}
if (fDispatch)
{
// Disable SingleStep for all controllers on this thread. This requires the filter context set.
// This is what would disable the ss-flag when single-stepping over an AV.
if (g_patchTableValid && (dwCode != EXCEPTION_SINGLE_STEP))
{
LOG((LF_CORDB, LL_INFO1000, "DC::DNE non-single-step exception; check if any controller has ss turned on\n"));
ControllerLockHolder lockController;
for (DebuggerController* p = g_controllers; p != NULL; p = p->m_next)
{
if (p->m_singleStep && (p->m_thread == pCurThread))
{
LOG((LF_CORDB, LL_INFO1000, "DC::DNE turn off ss for controller 0x%p\n", p));
p->DisableSingleStep();
}
}
// implicit controller lock release
}
CORDB_ADDRESS_TYPE * ip = dac_cast<PTR_CORDB_ADDRESS_TYPE>(GetIP(pContext));
switch (dwCode)
{
case EXCEPTION_BREAKPOINT:
// EIP should be properly set up at this point.
result = DebuggerController::DispatchPatchOrSingleStep(pCurThread,
pContext,
ip,
ST_PATCH);
LOG((LF_CORDB, LL_EVERYTHING, "DC::DNE DispatchPatch call returned\n"));
// If we detached, we should remove all our breakpoints. So if we try
// to handle this breakpoint, make sure that we're attached.
if (IsInUsedAction(result) == true)
{
_ASSERTE(fWasAttached);
}
break;
case EXCEPTION_SINGLE_STEP:
LOG((LF_CORDB, LL_EVERYTHING, "DC::DNE SINGLE_STEP Exception\n"));
result = DebuggerController::DispatchPatchOrSingleStep(pCurThread,
pContext,
ip,
(SCAN_TRIGGER)(ST_PATCH|ST_SINGLE_STEP));
// We pass patch | single step since single steps actually
// do both (eg, you SS onto a breakpoint).
break;
default:
break;
} // end switch
}
#ifdef _DEBUG
else
{
LOG((LF_CORDB, LL_INFO1000, "DC:: DNE step-around fDispatch:0x%x!\n", fDispatch));
}
#endif //_DEBUG
fDebuggers = (fDispatch?(IsInUsedAction(result)?true:false):true);
LOG((LF_CORDB, LL_INFO10000, "DC::DNE, returning 0x%x.\n", fDebuggers));
#ifdef _DEBUG
if (fDebuggers && (result == DPOSS_USED_WITH_EVENT))
{
// If the exception belongs to the debugger, then we may have sent an event,
// and thus we may have triggered a GC.
ThisFunctionMayHaveTriggerAGC();
}
#endif
// Must restore the filter context. After the filter context is gone, we're
// unprotected again and unsafe for a GC.
{
CONTRACT_VIOLATION(ModeViolation);
g_pEEInterface->SetThreadFilterContext(pCurThread, NULL);
}
#ifdef _TARGET_ARM_
if (pCurThread->IsSingleStepEnabled())
pCurThread->ApplySingleStep(pContext);
#endif
FireEtwDebugExceptionProcessingEnd();
return fDebuggers;
}
// * -------------------------------------------------------------------------
// * DebuggerPatchSkip routines
// * -------------------------------------------------------------------------
DebuggerPatchSkip::DebuggerPatchSkip(Thread *thread,
DebuggerControllerPatch *patch,
AppDomain *pAppDomain)
: DebuggerController(thread, pAppDomain),
m_address(patch->address)
{
LOG((LF_CORDB, LL_INFO10000,
"DPS::DPS: Patch skip 0x%p\n", patch->address));
// On ARM the single-step emulation already utilizes a per-thread execution buffer similar to the scheme
// below. As a result we can skip most of the instruction parsing logic that's instead internalized into
// the single-step emulation itself.
#ifndef _TARGET_ARM_
// NOTE: in order to correctly single-step RIP-relative writes on multiple threads we need to set up
// a shared buffer with the instruction and a buffer for the RIP-relative value so that all threads
// are working on the same copy. as the single-steps complete the modified data in the buffer is
// copied back to the real address to ensure proper execution of the program.
//
// Create the shared instruction block. this will also create the shared RIP-relative buffer
//
m_pSharedPatchBypassBuffer = patch->GetOrCreateSharedPatchBypassBuffer();
BYTE* patchBypass = m_pSharedPatchBypassBuffer->PatchBypass;
// Copy the instruction block over to the patch skip
// WARNING: there used to be an issue here because CopyInstructionBlock copied the breakpoint from the
// jitted code stream into the patch buffer. Further below CORDbgSetInstruction would correct the
// first instruction. This buffer is shared by all threads so if another thread executed the buffer
// between this thread's execution of CopyInstructionBlock and CORDbgSetInstruction the wrong
// code would be executed. The bug has been fixed by changing CopyInstructionBlock to only copy
// the code bytes after the breakpoint.
// You might be tempted to stop copying the code at all, however that wouldn't work well with rejit.
// If we skip a breakpoint that is sitting at the beginning of a method, then the profiler rejits that
// method causing a jump-stamp to be placed, then we skip the breakpoint again, we need to make sure
// the 2nd skip executes the new jump-stamp code and not the original method prologue code. Copying
// the code every time ensures that we have the most up-to-date version of the code in the buffer.
_ASSERTE( patch->IsBound() );
CopyInstructionBlock(patchBypass, (const BYTE *)patch->address);
// Technically, we could create a patch skipper for an inactive patch, but we rely on the opcode being
// set here.
_ASSERTE( patch->IsActivated() );
CORDbgSetInstruction((CORDB_ADDRESS_TYPE *)patchBypass, patch->opcode);
LOG((LF_CORDB, LL_EVERYTHING, "SetInstruction was called\n"));
//
// Look at instruction to get some attributes
//
NativeWalker::DecodeInstructionForPatchSkip(patchBypass, &(m_instrAttrib));
#if defined(_TARGET_AMD64_)
// The code below handles RIP-relative addressing on AMD64. the original implementation made the assumption that
// we are only using RIP-relative addressing to access read-only data (see VSW 246145 for more information). this
// has since been expanded to handle RIP-relative writes as well.
if (m_instrAttrib.m_dwOffsetToDisp != 0)
{
_ASSERTE(m_instrAttrib.m_cbInstr != 0);
//
// Populate the RIP-relative buffer with the current value if needed
//
BYTE* bufferBypass = m_pSharedPatchBypassBuffer->BypassBuffer;
// Overwrite the *signed* displacement.
int dwOldDisp = *(int*)(&patchBypass[m_instrAttrib.m_dwOffsetToDisp]);
int dwNewDisp = offsetof(SharedPatchBypassBuffer, BypassBuffer) -
(offsetof(SharedPatchBypassBuffer, PatchBypass) + m_instrAttrib.m_cbInstr);
*(int*)(&patchBypass[m_instrAttrib.m_dwOffsetToDisp]) = dwNewDisp;
// This could be an LEA, which we'll just have to change into a MOV
// and copy the original address
if (((patchBypass[0] == 0x4C) || (patchBypass[0] == 0x48)) && (patchBypass[1] == 0x8d))
{
patchBypass[1] = 0x8b; // MOV reg, mem
_ASSERTE((int)sizeof(void*) <= SharedPatchBypassBuffer::cbBufferBypass);
*(void**)bufferBypass = (void*)(patch->address + m_instrAttrib.m_cbInstr + dwOldDisp);
}
else
{
// Copy the data into our buffer.
memcpy(bufferBypass, patch->address + m_instrAttrib.m_cbInstr + dwOldDisp, SharedPatchBypassBuffer::cbBufferBypass);
if (m_instrAttrib.m_fIsWrite)
{
// save the actual destination address and size so when we TriggerSingleStep() we can update the value
m_pSharedPatchBypassBuffer->RipTargetFixup = (UINT_PTR)(patch->address + m_instrAttrib.m_cbInstr + dwOldDisp);
m_pSharedPatchBypassBuffer->RipTargetFixupSize = m_instrAttrib.m_cOperandSize;
}
}
}
#endif // _TARGET_AMD64_
#endif // !_TARGET_ARM_
// Signals our thread that the debugger will be manipulating the context
// during the patch skip operation. This effectively prevents other threads
// from suspending us until we have completed skiping the patch and restored
// a good context (See DDB 188816)
thread->BeginDebuggerPatchSkip(this);
//
// Set IP of context to point to patch bypass buffer
//
T_CONTEXT *context = g_pEEInterface->GetThreadFilterContext(thread);
_ASSERTE(!ISREDIRECTEDTHREAD(thread));
CONTEXT c;
if (context == NULL)
{
// We can't play with our own context!
#if _DEBUG
if (g_pEEInterface->GetThread())
{
// current thread is mamaged thread
_ASSERTE(Debugger::GetThreadIdHelper(thread) != Debugger::GetThreadIdHelper(g_pEEInterface->GetThread()));
}
#endif // _DEBUG
c.ContextFlags = CONTEXT_CONTROL;
thread->GetThreadContext(&c);
context =(T_CONTEXT *) &c;
ARM_ONLY(_ASSERTE(!"We should always have a filter context in DebuggerPatchSkip."));
}
#ifdef _TARGET_ARM_
// Since we emulate all single-stepping on ARM using an instruction buffer and a breakpoint all we have to
// do here is initiate a normal single-step except that we pass the instruction to be stepped explicitly
// (calling EnableSingleStep() would infer this by looking at the PC in the context, which would pick up
// the patch we're trying to skip).
//
// Ideally we'd refactor the EnableSingleStep to support this alternative calling sequence but since this
// involves three levels of methods and is only applicable to ARM we've chosen to replicate the relevant
// implementation here instead.
{
ControllerLockHolder lockController;
g_pEEInterface->MarkThreadForDebugStepping(thread, true);
WORD opcode2 = 0;
if (Is32BitInstruction(patch->opcode))
{
opcode2 = CORDbgGetInstruction((CORDB_ADDRESS_TYPE *)(((DWORD)patch->address) + 2));
}
thread->BypassWithSingleStep((DWORD)patch->address, patch->opcode, opcode2);
m_singleStep = true;
}
#else // _TARGET_ARM_
#ifdef _TARGET_ARM64_
patchBypass = NativeWalker::SetupOrSimulateInstructionForPatchSkip(context, m_pSharedPatchBypassBuffer, (const BYTE *)patch->address, patch->opcode);
#endif //_TARGET_ARM64_
//set eip to point to buffer...
SetIP(context, (PCODE)patchBypass);
if (context ==(T_CONTEXT*) &c)
thread->SetThreadContext(&c);
LOG((LF_CORDB, LL_INFO10000, "DPS::DPS Bypass at 0x%p for opcode %p \n", patchBypass, patch->opcode));
//
// Turn on single step (if the platform supports it) so we can
// fix up state after the instruction is executed.
// Also turn on exception hook so we can adjust IP in exceptions
//
EnableSingleStep();
#endif // _TARGET_ARM_
EnableExceptionHook();
}
DebuggerPatchSkip::~DebuggerPatchSkip()
{
#ifndef _TARGET_ARM_
_ASSERTE(m_pSharedPatchBypassBuffer);
m_pSharedPatchBypassBuffer->Release();
#endif
}
void DebuggerPatchSkip::DebuggerDetachClean()
{
// Since for ARM SharedPatchBypassBuffer isn't existed, we don't have to anything here.
#ifndef _TARGET_ARM_
// Fix for Bug 1176448
// When a debugger is detaching from the debuggee, we need to move the IP if it is pointing
// somewhere in PatchBypassBuffer.All managed threads are suspended during detach, so changing
// the context without notifications is safe.
// Notice:
// THIS FIX IS INCOMPLETE!It attempts to update the IP in the cases we can easily detect.However,
// if a thread is in pre - emptive mode, and its filter context has been propagated to a VEH
// context, then the filter context we get will be NULL and this fix will not work.Our belief is
// that this scenario is rare enough that it doesnt justify the cost and risk associated with a
// complete fix, in which we would have to either :
// 1. Change the reference counting for DebuggerController and then change the exception handling
// logic in the debuggee so that we can handle the debugger event after detach.
// 2. Create a "stack walking" implementation for native code and use it to get the current IP and
// set the IP to the right place.
Thread *thread = GetThread();
if (thread != NULL)
{
BYTE *patchBypass = m_pSharedPatchBypassBuffer->PatchBypass;
CONTEXT *context = thread->GetFilterContext();
if (patchBypass != NULL &&
context != NULL &&
(size_t)GetIP(context) >= (size_t)patchBypass &&
(size_t)GetIP(context) <= (size_t)(patchBypass + MAX_INSTRUCTION_LENGTH + 1))
{
SetIP(context, (PCODE)((BYTE *)GetIP(context) - (patchBypass - (BYTE *)m_address)));
}
}
#endif
}
//
// We have to have a whole seperate function for this because you
// can't use __try in a function that requires object unwinding...
//
LONG FilterAccessViolation2(LPEXCEPTION_POINTERS ep, PVOID pv)
{
LIMITED_METHOD_CONTRACT;
return (ep->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION)
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
}
// This helper is required because the AVInRuntimeImplOkayHolder can not
// be directly placed inside the scope of a PAL_TRY
void _CopyInstructionBlockHelper(BYTE* to, const BYTE* from)
{
AVInRuntimeImplOkayHolder AVOkay;
// This function only copies the portion of the instruction that follows the
// breakpoint opcode, not the breakpoint itself
to += CORDbg_BREAK_INSTRUCTION_SIZE;
from += CORDbg_BREAK_INSTRUCTION_SIZE;
// If an AV occurs because we walked off a valid page then we need
// to be certain that all bytes on the previous page were copied.
// We are certain that we copied enough bytes to contain the instruction
// because it must have fit within the valid page.
for (int i = 0; i < MAX_INSTRUCTION_LENGTH - CORDbg_BREAK_INSTRUCTION_SIZE; i++)
{
*to++ = *from++;
}
}
// WARNING: this function skips copying the first CORDbg_BREAK_INSTRUCTION_SIZE bytes by design
// See the comment at the callsite in DebuggerPatchSkip::DebuggerPatchSkip for more details on
// this
void DebuggerPatchSkip::CopyInstructionBlock(BYTE *to, const BYTE* from)
{
// We wrap the memcpy in an exception handler to handle the
// extremely rare case where we're copying an instruction off the
// end of a method that is also at the end of a page, and the next
// page is unmapped.
struct Param
{
BYTE *to;
const BYTE* from;
} param;
param.to = to;
param.from = from;
PAL_TRY(Param *, pParam, ¶m)
{
_CopyInstructionBlockHelper(pParam->to, pParam->from);
}
PAL_EXCEPT_FILTER(FilterAccessViolation2)
{
// The whole point is that if we copy up the the AV, then
// that's enough to execute, otherwise we would not have been
// able to execute the code anyway. So we just ignore the
// exception.
LOG((LF_CORDB, LL_INFO10000,
"DPS::DPS: AV copying instruction block ignored.\n"));
}
PAL_ENDTRY
// We just created a new buffer of code, but the CPU caches code and may
// not be aware of our changes. This should force the CPU to dump any cached
// instructions it has in this region and load the new ones from memory
FlushInstructionCache(GetCurrentProcess(), to + CORDbg_BREAK_INSTRUCTION_SIZE,
MAX_INSTRUCTION_LENGTH - CORDbg_BREAK_INSTRUCTION_SIZE);
}
TP_RESULT DebuggerPatchSkip::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
ARM_ONLY(_ASSERTE(!"Should not have called DebuggerPatchSkip::TriggerPatch."));
LOG((LF_CORDB, LL_EVERYTHING, "DPS::TP called\n"));
#if defined(_DEBUG) && !defined(_TARGET_ARM_)
CONTEXT *context = GetManagedLiveCtx(thread);
LOG((LF_CORDB, LL_INFO1000, "DPS::TP: We've patched 0x%x (byPass:0x%x) "
"for a skip after an EnC update!\n", GetIP(context),
GetBypassAddress()));
_ASSERTE(g_patches != NULL);
// We shouldn't have mucked with EIP, yet.
_ASSERTE(dac_cast<PTR_CORDB_ADDRESS_TYPE>(GetIP(context)) == GetBypassAddress());
//We should be the _only_ patch here
MethodDesc *md2 = dac_cast<PTR_MethodDesc>(GetIP(context));
DebuggerControllerPatch *patchCheck = g_patches->GetPatch(g_pEEInterface->MethodDescGetModule(md2),md2->GetMemberDef());
_ASSERTE(patchCheck == patch);
_ASSERTE(patchCheck->controller == patch->controller);
patchCheck = g_patches->GetNextPatch(patchCheck);
_ASSERTE(patchCheck == NULL);
#endif // _DEBUG
DisableAll();
EnableExceptionHook();
EnableSingleStep(); //gets us back to where we want.
return TPR_IGNORE; // don't actually want to stop here....
}
TP_RESULT DebuggerPatchSkip::TriggerExceptionHook(Thread *thread, CONTEXT * context,
EXCEPTION_RECORD *exception)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
// Patch skippers only operate on patches set in managed code. But the infrastructure may have
// toggled the GC mode underneath us.
MODE_ANY;
PRECONDITION(GetThread() == thread);
PRECONDITION(thread != NULL);
PRECONDITION(CheckPointer(context));
}
CONTRACTL_END;
if (m_pAppDomain != NULL)
{
AppDomain *pAppDomainCur = thread->GetDomain();
if (pAppDomainCur != m_pAppDomain)
{
LOG((LF_CORDB,LL_INFO10000, "DPS::TEH: Appdomain mismatch - not skiiping!\n"));
return TPR_IGNORE;
}
}
LOG((LF_CORDB,LL_INFO10000, "DPS::TEH: doing the patch-skip thing\n"));
#if defined(_TARGET_ARM64_)
if (!IsSingleStep(exception->ExceptionCode))
{
LOG((LF_CORDB, LL_INFO10000, "Exception in patched Bypass instruction .\n"));
return (TPR_IGNORE_AND_STOP);
}
_ASSERTE(m_pSharedPatchBypassBuffer);
BYTE* patchBypass = m_pSharedPatchBypassBuffer->PatchBypass;
PCODE targetIp;
if (m_pSharedPatchBypassBuffer->RipTargetFixup)
{
targetIp = m_pSharedPatchBypassBuffer->RipTargetFixup;
}
else
{
targetIp = (PCODE)((BYTE *)GetIP(context) - (patchBypass - (BYTE *)m_address));
}
SetIP(context, targetIp);
LOG((LF_CORDB, LL_ALWAYS, "Redirecting after Patch to 0x%p\n", GetIP(context)));
#elif defined (_TARGET_ARM_)
//Do nothing
#else
_ASSERTE(m_pSharedPatchBypassBuffer);
BYTE* patchBypass = m_pSharedPatchBypassBuffer->PatchBypass;
if (m_instrAttrib.m_fIsCall && IsSingleStep(exception->ExceptionCode))
{
// Fixup return address on stack
#if defined(_TARGET_X86_) || defined(_TARGET_AMD64_)
SIZE_T *sp = (SIZE_T *) GetSP(context);
LOG((LF_CORDB, LL_INFO10000,
"Bypass call return address redirected from 0x%p\n", *sp));
*sp -= patchBypass - (BYTE*)m_address;
LOG((LF_CORDB, LL_INFO10000, "to 0x%p\n", *sp));
#else
PORTABILITY_ASSERT("DebuggerPatchSkip::TriggerExceptionHook -- return address fixup NYI");
#endif
}
if (!m_instrAttrib.m_fIsAbsBranch || !IsSingleStep(exception->ExceptionCode))
{
// Fixup IP
LOG((LF_CORDB, LL_INFO10000, "Bypass instruction redirected from 0x%p\n", GetIP(context)));
if (IsSingleStep(exception->ExceptionCode))
{
#ifndef FEATURE_PAL
// Check if the current IP is anywhere near the exception dispatcher logic.
// If it is, ignore the exception, as the real exception is coming next.
static FARPROC pExcepDispProc = NULL;
if (!pExcepDispProc)
{
HMODULE hNtDll = WszGetModuleHandle(W("ntdll.dll"));
if (hNtDll != NULL)
{
pExcepDispProc = GetProcAddress(hNtDll, "KiUserExceptionDispatcher");
if (!pExcepDispProc)
pExcepDispProc = (FARPROC)(size_t)(-1);
}
else
pExcepDispProc = (FARPROC)(size_t)(-1);
}
_ASSERTE(pExcepDispProc != NULL);
if ((size_t)pExcepDispProc != (size_t)(-1))
{
LPVOID pExcepDispEntryPoint = pExcepDispProc;
if ((size_t)GetIP(context) > (size_t)pExcepDispEntryPoint &&
(size_t)GetIP(context) <= ((size_t)pExcepDispEntryPoint + MAX_INSTRUCTION_LENGTH * 2 + 1))
{
LOG((LF_CORDB, LL_INFO10000,
"Bypass instruction not redirected. Landed in exception dispatcher.\n"));
return (TPR_IGNORE_AND_STOP);
}
}
#endif // FEATURE_PAL
// If the IP is close to the skip patch start, or if we were skipping over a call, then assume the IP needs
// adjusting.
if (m_instrAttrib.m_fIsCall ||
((size_t)GetIP(context) > (size_t)patchBypass &&
(size_t)GetIP(context) <= (size_t)(patchBypass + MAX_INSTRUCTION_LENGTH + 1)))
{
LOG((LF_CORDB, LL_INFO10000, "Bypass instruction redirected because still in skip area.\n"));
LOG((LF_CORDB, LL_INFO10000, "m_fIsCall = %d, patchBypass = 0x%x, m_address = 0x%x\n",
m_instrAttrib.m_fIsCall, patchBypass, m_address));
SetIP(context, (PCODE)((BYTE *)GetIP(context) - (patchBypass - (BYTE *)m_address)));
}
else
{
// Otherwise, need to see if the IP is something we recognize (either managed code
// or stub code) - if not, we ignore the exception
PCODE newIP = GetIP(context);
newIP -= PCODE(patchBypass - (BYTE *)m_address);
TraceDestination trace;
if (g_pEEInterface->IsManagedNativeCode(dac_cast<PTR_CBYTE>(newIP)) ||
(g_pEEInterface->TraceStub(LPBYTE(newIP), &trace)))
{
LOG((LF_CORDB, LL_INFO10000, "Bypass instruction redirected because we landed in managed or stub code\n"));
SetIP(context, newIP);
}
// If we have no idea where things have gone, then we assume that the IP needs no adjusting (which
// could happen if the instruction we were trying to patch skip caused an AV). In this case we want
// to claim it as ours but ignore it and continue execution.
else
{
LOG((LF_CORDB, LL_INFO10000, "Bypass instruction not redirected because we're not in managed or stub code.\n"));
return (TPR_IGNORE_AND_STOP);
}
}
}
else
{
LOG((LF_CORDB, LL_INFO10000, "Bypass instruction redirected because it wasn't a single step exception.\n"));
SetIP(context, (PCODE)((BYTE *)GetIP(context) - (patchBypass - (BYTE *)m_address)));
}
LOG((LF_CORDB, LL_ALWAYS, "to 0x%x\n", GetIP(context)));
}
#endif
// Signals our thread that the debugger is done manipulating the context
// during the patch skip operation. This effectively prevented other threads
// from suspending us until we completed skiping the patch and restored
// a good context (See DDB 188816)
m_thread->EndDebuggerPatchSkip();
// Don't delete the controller yet if this is a single step exception, as the code will still want to dispatch to
// our single step method, and if it doesn't find something to dispatch to we won't continue from the exception.
//
// (This is kind of broken behavior but is easily worked around here
// by this test)
if (!IsSingleStep(exception->ExceptionCode))
{
Delete();
}
DisableExceptionHook();
return TPR_TRIGGER;
}
bool DebuggerPatchSkip::TriggerSingleStep(Thread *thread, const BYTE *ip)
{
LOG((LF_CORDB,LL_INFO10000, "DPS::TSS: basically a no-op\n"));
if (m_pAppDomain != NULL)
{
AppDomain *pAppDomainCur = thread->GetDomain();
if (pAppDomainCur != m_pAppDomain)
{
LOG((LF_CORDB,LL_INFO10000, "DPS::TSS: Appdomain mismatch - "
"not SingSteping!!\n"));
return false;
}
}
#if defined(_TARGET_AMD64_)
// Dev11 91932: for RIP-relative writes we need to copy the value that was written in our buffer to the actual address
_ASSERTE(m_pSharedPatchBypassBuffer);
if (m_pSharedPatchBypassBuffer->RipTargetFixup)
{
_ASSERTE(m_pSharedPatchBypassBuffer->RipTargetFixupSize);
BYTE* bufferBypass = m_pSharedPatchBypassBuffer->BypassBuffer;
BYTE fixupSize = m_pSharedPatchBypassBuffer->RipTargetFixupSize;
UINT_PTR targetFixup = m_pSharedPatchBypassBuffer->RipTargetFixup;
switch (fixupSize)
{
case 1:
*(reinterpret_cast<BYTE*>(targetFixup)) = *(reinterpret_cast<BYTE*>(bufferBypass));
break;
case 2:
*(reinterpret_cast<WORD*>(targetFixup)) = *(reinterpret_cast<WORD*>(bufferBypass));
break;
case 4:
*(reinterpret_cast<DWORD*>(targetFixup)) = *(reinterpret_cast<DWORD*>(bufferBypass));
break;
case 8:
*(reinterpret_cast<ULONGLONG*>(targetFixup)) = *(reinterpret_cast<ULONGLONG*>(bufferBypass));
break;
case 16:
memcpy(reinterpret_cast<void*>(targetFixup), bufferBypass, 16);
break;
default:
_ASSERTE(!"bad operand size");
}
}
#endif
LOG((LF_CORDB,LL_INFO10000, "DPS::TSS: triggered, about to delete\n"));
TRACE_FREE(this);
Delete();
return false;
}
// * -------------------------------------------------------------------------
// * DebuggerBreakpoint routines
// * -------------------------------------------------------------------------
// DebuggerBreakpoint::DebuggerBreakpoint() The constructor
// invokes AddBindAndActivatePatch to set the breakpoint
DebuggerBreakpoint::DebuggerBreakpoint(Module *module,
mdMethodDef md,
AppDomain *pAppDomain,
SIZE_T offset,
bool native,
SIZE_T ilEnCVersion, // must give the EnC version for non-native bps
MethodDesc *nativeMethodDesc, // use only when m_native
DebuggerJitInfo *nativeJITInfo, // optional when m_native, null otherwise
BOOL *pSucceed
)
: DebuggerController(NULL, pAppDomain)
{
_ASSERTE(pSucceed != NULL);
_ASSERTE(native == (nativeMethodDesc != NULL));
_ASSERTE(native || nativeJITInfo == NULL);
_ASSERTE(!nativeJITInfo || nativeJITInfo->m_jitComplete); // this is sent by the left-side, and it couldn't have got the code if the JIT wasn't complete
if (native)
{
(*pSucceed) = AddBindAndActivateNativeManagedPatch(nativeMethodDesc, nativeJITInfo, offset, LEAF_MOST_FRAME, pAppDomain);
return;
}
else
{
(*pSucceed) = AddILPatch(pAppDomain, module, md, ilEnCVersion, offset);
}
}
// TP_RESULT DebuggerBreakpoint::TriggerPatch()
// What: This patch will always be activated.
// How: return true.
TP_RESULT DebuggerBreakpoint::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
LOG((LF_CORDB, LL_INFO10000, "DB::TP\n"));
return TPR_TRIGGER;
}
// void DebuggerBreakpoint::SendEvent() What: Inform
// the right side that the breakpoint was reached.
// How: g_pDebugger->SendBreakpoint()
bool DebuggerBreakpoint::SendEvent(Thread *thread, bool fIpChanged)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
SENDEVENT_CONTRACT_ITEMS;
}
CONTRACTL_END;
LOG((LF_CORDB, LL_INFO10000, "DB::SE: in DebuggerBreakpoint's SendEvent\n"));
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(thread);
// If we got interupted by SetIp, we just don't send the IPC event. Our triggers are still
// active so no harm done.
if (!fIpChanged)
{
g_pDebugger->SendBreakpoint(thread, context, this);
return true;
}
// Controller is still alive, will fire if we hit the breakpoint again.
return false;
}
//* -------------------------------------------------------------------------
// * DebuggerStepper routines
// * -------------------------------------------------------------------------
DebuggerStepper::DebuggerStepper(Thread *thread,
CorDebugUnmappedStop rgfMappingStop,
CorDebugIntercept interceptStop,
AppDomain *appDomain)
: DebuggerController(thread, appDomain),
m_stepIn(false),
m_reason(STEP_NORMAL),
m_fpStepInto(LEAF_MOST_FRAME),
m_rgfInterceptStop(interceptStop),
m_rgfMappingStop(rgfMappingStop),
m_range(NULL),
m_rangeCount(0),
m_realRangeCount(0),
m_fp(LEAF_MOST_FRAME),
#if defined(WIN64EXCEPTIONS)
m_fpParentMethod(LEAF_MOST_FRAME),
#endif // WIN64EXCEPTIONS
m_fpException(LEAF_MOST_FRAME),
m_fdException(0),
m_cFuncEvalNesting(0)
{
#ifdef _DEBUG
m_fReadyToSend = false;
#endif
}
DebuggerStepper::~DebuggerStepper()
{
if (m_range != NULL)
{
TRACE_FREE(m_range);
DeleteInteropSafe(m_range);
}
}
// bool DebuggerStepper::ShouldContinueStep() Return true if
// the stepper should not stop at this address. The stepper should not
// stop here if: here is in the {prolog,epilog,etc};
// and the stepper is not interested in stopping here.
// We assume that this is being called in the frame which the stepper steps
// through. Unless, of course, we're returning from a call, in which
// case we want to stop in the epilog even if the user didn't say so,
// to prevent stepping out of multiple frames at once.
// <REVISIT_TODO>Possible optimization: GetJitInfo, then AddPatch @ end of prolog?</REVISIT_TODO>
bool DebuggerStepper::ShouldContinueStep( ControllerStackInfo *info,
SIZE_T nativeOffset)
{
LOG((LF_CORDB,LL_INFO10000, "DeSt::ShContSt: nativeOffset:0x%p \n", nativeOffset));
if (m_rgfMappingStop != STOP_ALL && (m_reason != STEP_EXIT) )
{
DebuggerJitInfo *ji = info->m_activeFrame.GetJitInfoFromFrame();
if ( ji != NULL )
{
LOG((LF_CORDB,LL_INFO10000,"DeSt::ShContSt: For code 0x%p, got "
"DJI 0x%p, from 0x%p to 0x%p\n",
(const BYTE*)GetControlPC(&(info->m_activeFrame.registers)),
ji, ji->m_addrOfCode, ji->m_addrOfCode+ji->m_sizeOfCode));
}
else
{
LOG((LF_CORDB,LL_INFO10000,"DeSt::ShCoSt: For code 0x%p, didn't "
"get DJI\n",(const BYTE*)GetControlPC(&(info->m_activeFrame.registers))));
return false; // Haven't a clue if we should continue, so
// don't
}
CorDebugMappingResult map = MAPPING_UNMAPPED_ADDRESS;
DWORD whichIDontCare;
ji->MapNativeOffsetToIL( nativeOffset, &map, &whichIDontCare);
unsigned int interestingMappings =
(map & ~(MAPPING_APPROXIMATE | MAPPING_EXACT));
LOG((LF_CORDB,LL_INFO10000,
"DeSt::ShContSt: interestingMappings:0x%x m_rgfMappingStop:%x\n",
interestingMappings,m_rgfMappingStop));
// If we're in a prolog,epilog, then we may want to skip
// over it or stop
if ( interestingMappings )
{
if ( interestingMappings & m_rgfMappingStop )
return false;
else
return true;
}
}
return false;
}
bool DebuggerStepper::IsRangeAppropriate(ControllerStackInfo *info)
{
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: info:0x%x \n", info));
if (m_range == NULL)
{
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: m_range == NULL, returning FALSE\n"));
return false;
}
FrameInfo *realFrame;
#if defined(WIN64EXCEPTIONS)
bool fActiveFrameIsFunclet = info->m_activeFrame.IsNonFilterFuncletFrame();
if (fActiveFrameIsFunclet)
{
realFrame = &(info->m_returnFrame);
}
else
#endif // WIN64EXCEPTIONS
{
realFrame = &(info->m_activeFrame);
}
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: info->m_activeFrame.fp:0x%x m_fp:0x%x\n", info->m_activeFrame.fp, m_fp));
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: m_fdException:0x%x realFrame->md:0x%x realFrame->fp:0x%x m_fpException:0x%x\n",
m_fdException, realFrame->md, realFrame->fp, m_fpException));
if ( (info->m_activeFrame.fp == m_fp) ||
( (m_fdException != NULL) && (realFrame->md == m_fdException) &&
IsEqualOrCloserToRoot(realFrame->fp, m_fpException) ) )
{
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: returning TRUE\n"));
return true;
}
#if defined(WIN64EXCEPTIONS)
// There are two scenarios which make this function more complicated on WIN64.
// 1) We initiate a step in the parent method or a funclet but end up stepping into another funclet closer to the leaf.
// a) start in the parent method
// b) start in a funclet
// 2) We initiate a step in a funclet but end up stepping out to the parent method or a funclet closer to the root.
// a) end up in the parent method
// b) end up in a funclet
// In both cases the range of the stepper should still be appropriate.
bool fValidParentMethodFP = (m_fpParentMethod != LEAF_MOST_FRAME);
if (fActiveFrameIsFunclet)
{
// Scenario 1a
if (m_fp == info->m_returnFrame.fp)
{
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: returning TRUE\n"));
return true;
}
// Scenario 1b & 2b have the same condition
else if (fValidParentMethodFP && (m_fpParentMethod == info->m_returnFrame.fp))
{
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: returning TRUE\n"));
return true;
}
}
else
{
// Scenario 2a
if (fValidParentMethodFP && (m_fpParentMethod == info->m_activeFrame.fp))
{
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: returning TRUE\n"));
return true;
}
}
#endif // WIN64EXCEPTIONS
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: returning FALSE\n"));
return false;
}
// bool DebuggerStepper::IsInRange() Given the native offset ip,
// returns true if ip falls within any of the native offset ranges specified
// by the array of COR_DEBUG_STEP_RANGEs.
// Returns true if ip falls within any of the ranges. Returns false
// if ip doesn't, or if there are no ranges (rangeCount==0). Note that a
// COR_DEBUG_STEP_RANGE with an endOffset of zero is interpreted as extending
// from startOffset to the end of the method.
// SIZE_T ip: Native offset, relative to the beginning of the method.
// COR_DEBUG_STEP_RANGE *range: An array of ranges, which are themselves
// native offsets, to compare against ip.
// SIZE_T rangeCount: Number of elements in range
bool DebuggerStepper::IsInRange(SIZE_T ip, COR_DEBUG_STEP_RANGE *range, SIZE_T rangeCount,
ControllerStackInfo *pInfo)
{
LOG((LF_CORDB,LL_INFO10000,"DS::IIR: off=0x%x\n", ip));
if (range == NULL)
{
LOG((LF_CORDB,LL_INFO10000,"DS::IIR: range == NULL -> not in range\n"));
return false;
}
if (pInfo && !IsRangeAppropriate(pInfo))
{
LOG((LF_CORDB,LL_INFO10000,"DS::IIR: no pInfo or range not appropriate -> not in range\n"));
return false;
}
COR_DEBUG_STEP_RANGE *r = range;
COR_DEBUG_STEP_RANGE *rEnd = r + rangeCount;
while (r < rEnd)
{
SIZE_T endOffset = r->endOffset ? r->endOffset : ~0;
LOG((LF_CORDB,LL_INFO100000,"DS::IIR: so=0x%x, eo=0x%x\n",
r->startOffset, endOffset));
if (ip >= r->startOffset && ip < endOffset)
{
LOG((LF_CORDB,LL_INFO1000,"DS::IIR:this:0x%x Found native offset "
"0x%x to be in the range"
"[0x%x, 0x%x), index 0x%x\n\n", this, ip, r->startOffset,
endOffset, ((r-range)/sizeof(COR_DEBUG_STEP_RANGE *)) ));
return true;
}
r++;
}
LOG((LF_CORDB,LL_INFO10000,"DS::IIR: not in range\n"));
return false;
}
// bool DebuggerStepper::DetectHandleInterceptors() Return true if
// the current execution takes place within an interceptor (that is, either
// the current frame, or the parent frame is a framed frame whose
// GetInterception method returns something other than INTERCEPTION_NONE),
// and this stepper doesn't want to stop in an interceptor, and we successfully
// set a breakpoint after the top-most interceptor in the stack.
bool DebuggerStepper::DetectHandleInterceptors(ControllerStackInfo *info)
{
LOG((LF_CORDB,LL_INFO10000,"DS::DHI: Start DetectHandleInterceptors\n"));
LOG((LF_CORDB,LL_INFO10000,"DS::DHI: active frame=0x%08x, has return frame=%d, return frame=0x%08x m_reason:%d\n",
info->m_activeFrame.frame, info->HasReturnFrame(), info->m_returnFrame.frame, m_reason));
// If this is a normal step, then we want to continue stepping, even if we
// are in an interceptor.
if (m_reason == STEP_NORMAL || m_reason == STEP_RETURN || m_reason == STEP_EXCEPTION_HANDLER)
{
LOG((LF_CORDB,LL_INFO1000,"DS::DHI: Returning false while stepping within function, finally!\n"));
return false;
}
bool fAttemptStepOut = false;
if (m_rgfInterceptStop != INTERCEPT_ALL) // we may have to skip out of one
{
if (info->m_activeFrame.frame != NULL &&
info->m_activeFrame.frame != FRAME_TOP &&
info->m_activeFrame.frame->GetInterception() != Frame::INTERCEPTION_NONE)
{
if (!((CorDebugIntercept)info->m_activeFrame.frame->GetInterception() & Frame::Interception(m_rgfInterceptStop)))
{
LOG((LF_CORDB,LL_INFO10000,"DS::DHI: Stepping out b/c of excluded frame type:0x%x\n",
info->m_returnFrame. frame->GetInterception()));
fAttemptStepOut = true;
}
else
{
LOG((LF_CORDB,LL_INFO10000,"DS::DHI: 0x%x set to STEP_INTERCEPT\n", this));
m_reason = STEP_INTERCEPT; //remember why we've stopped
}
}
if ((m_reason == STEP_EXCEPTION_FILTER) ||
(info->HasReturnFrame() &&
info->m_returnFrame.frame != NULL &&
info->m_returnFrame.frame != FRAME_TOP &&
info->m_returnFrame.frame->GetInterception() != Frame::INTERCEPTION_NONE))
{
if (m_reason == STEP_EXCEPTION_FILTER)
{
// Exceptions raised inside of the EE by COMPlusThrow, FCThrow, etc will not
// insert an ExceptionFrame, and hence info->m_returnFrame.frame->GetInterception()
// will not be accurate. Hence we use m_reason instead
if (!(Frame::INTERCEPTION_EXCEPTION & Frame::Interception(m_rgfInterceptStop)))
{
LOG((LF_CORDB,LL_INFO10000,"DS::DHI: Stepping out b/c of excluded INTERCEPTION_EXCEPTION\n"));
fAttemptStepOut = true;
}
}
else if (!(info->m_returnFrame.frame->GetInterception() & Frame::Interception(m_rgfInterceptStop)))
{
LOG((LF_CORDB,LL_INFO10000,"DS::DHI: Stepping out b/c of excluded return frame type:0x%x\n",
info->m_returnFrame.frame->GetInterception()));
fAttemptStepOut = true;
}
if (!fAttemptStepOut)
{
LOG((LF_CORDB,LL_INFO10000,"DS::DHI 0x%x set to STEP_INTERCEPT\n", this));
m_reason = STEP_INTERCEPT; //remember why we've stopped
}
}
else if (info->m_specialChainReason != CHAIN_NONE)
{
if(!(info->m_specialChainReason & CorDebugChainReason(m_rgfInterceptStop)) )
{
LOG((LF_CORDB,LL_INFO10000, "DS::DHI: (special) Stepping out b/c of excluded return frame type:0x%x\n",
info->m_specialChainReason));
fAttemptStepOut = true;
}
else
{
LOG((LF_CORDB,LL_INFO10000,"DS::DHI 0x%x set to STEP_INTERCEPT\n", this));
m_reason = STEP_INTERCEPT; //remember why we've stopped
}
}
else if (info->m_activeFrame.frame == NULL)
{
// Make sure we are not dealing with a chain here.
if (info->m_activeFrame.HasMethodFrame())
{
// Check whether we are executing in a class constructor.
_ASSERTE(info->m_activeFrame.md != NULL);
if (info->m_activeFrame.md->IsClassConstructor())
{
// We are in a class constructor. Check whether we want to stop in it.
if (!(CHAIN_CLASS_INIT & CorDebugChainReason(m_rgfInterceptStop)))
{
LOG((LF_CORDB, LL_INFO10000, "DS::DHI: Stepping out b/c of excluded cctor:0x%x\n",
CHAIN_CLASS_INIT));
fAttemptStepOut = true;
}
else
{
LOG((LF_CORDB, LL_INFO10000,"DS::DHI 0x%x set to STEP_INTERCEPT\n", this));
m_reason = STEP_INTERCEPT; //remember why we've stopped
}
}
}
}
}
if (fAttemptStepOut)
{
LOG((LF_CORDB,LL_INFO1000,"DS::DHI: Doing TSO!\n"));
// TrapStepOut could alter the step reason if we're stepping out of an inteceptor and it looks like we're
// running off the top of the program. So hold onto it here, and if our step reason becomes STEP_EXIT, then
// reset it to what it was.
CorDebugStepReason holdReason = m_reason;
// @todo - should this be TrapStepNext??? But that may stop in a child...
TrapStepOut(info);
EnableUnwind(m_fp);
if (m_reason == STEP_EXIT)
{
m_reason = holdReason;
}
return true;
}
// We're not in a special area of code, so we don't want to continue unless some other part of the code decides that
// we should.
LOG((LF_CORDB,LL_INFO1000,"DS::DHI: Returning false, finally!\n"));
return false;
}
//---------------------------------------------------------------------------------------
//
// This function checks whether the given IP is in an LCG method. If so, it enables
// JMC and does a step out. This effectively makes sure that we never stop in an LCG method.
//
// There are two common scnearios here:
// 1) We single-step into an LCG method from a managed method.
// 2) We single-step off the end of a method called by an LCG method and end up in the calling LCG method.
//
// In both cases, we don't want to stop in the LCG method. If the LCG method directly or indirectly calls
// another user method, we want to stop there. Otherwise, we just want to step out back to the caller of
// LCG method. In other words, what we want is exactly the JMC behaviour.
//
// Arguments:
// ip - the current IP where the thread is stopped at
// pMD - This is the MethodDesc for the specified ip. This can be NULL, but if it's not,
// then it has to match the specified IP.
// pInfo - the ControllerStackInfo taken at the specified IP (see Notes below)
//
// Return Value:
// Returns TRUE if the specified IP is indeed in an LCG method, in which case this function has already
// enabled all the traps to catch the thread, including turning on JMC, enabling unwind callback, and
// putting a patch in the caller.
//
// Notes:
// LCG methods don't show up in stackwalks done by the ControllerStackInfo. So even if the specified IP
// is in an LCG method, the LCG method won't show up in the call strack. That's why we need to call
// ControllerStackInfo::SetReturnFrameWithActiveFrame() in this function before calling TrapStepOut().
// Otherwise TrapStepOut() will put a patch in the caller's caller (if there is one).
//
BOOL DebuggerStepper::DetectHandleLCGMethods(const PCODE ip, MethodDesc * pMD, ControllerStackInfo * pInfo)
{
// Look up the MethodDesc for the given IP.
if (pMD == NULL)
{
if (g_pEEInterface->IsManagedNativeCode((const BYTE *)ip))
{
pMD = g_pEEInterface->GetNativeCodeMethodDesc(ip);
_ASSERTE(pMD != NULL);
}
}
#if defined(_DEBUG)
else
{
// If a MethodDesc is specified, it has to match the given IP.
_ASSERTE(pMD == g_pEEInterface->GetNativeCodeMethodDesc(ip));
}
#endif // _DEBUG
// If the given IP is in unmanaged code, then we won't have a MethodDesc by this point.
if (pMD != NULL)
{
if (pMD->IsLCGMethod())
{
// Enable all the traps to catch the thread.
EnableUnwind(m_fp);
EnableJMCBackStop(pMD);
pInfo->SetReturnFrameWithActiveFrame();
TrapStepOut(pInfo);
return TRUE;
}
}
return FALSE;
}
// Steppers override these so that they can skip func-evals. Note that steppers can
// be created & used inside of func-evals (nested-break states).
// On enter, we check for freezing the stepper.
void DebuggerStepper::TriggerFuncEvalEnter(Thread * thread)
{
LOG((LF_CORDB, LL_INFO10000, "DS::TFEEnter, this=0x%p, old nest=%d\n", this, m_cFuncEvalNesting));
// Since this is always called on the hijacking thread, we should be thread-safe
_ASSERTE(thread == this->GetThread());
if (IsDead())
return;
m_cFuncEvalNesting++;
if (m_cFuncEvalNesting == 1)
{
// We're entering our 1st funceval, so freeze us.
LOG((LF_CORDB, LL_INFO100000, "DS::TFEEnter - freezing stepper\n"));
// Freeze the stepper by disabling all triggers
m_bvFrozenTriggers = 0;
//
// We dont explicitly disable single-stepping because the OS
// gives us a new thread context during an exception. Since
// all func-evals are done inside exceptions, we should never
// have this problem.
//
// Note: however, that if func-evals were no longer done in
// exceptions, this would have to change.
//
if (IsMethodEnterEnabled())
{
m_bvFrozenTriggers |= kMethodEnter;
DisableMethodEnter();
}
}
else
{
LOG((LF_CORDB, LL_INFO100000, "DS::TFEEnter - new nest=%d\n", m_cFuncEvalNesting));
}
}
// On Func-EvalExit, we check if the stepper is trying to step-out of a func-eval
// (in which case we kill it)
// or if we previously entered this func-eval and should thaw it now.
void DebuggerStepper::TriggerFuncEvalExit(Thread * thread)
{
LOG((LF_CORDB, LL_INFO10000, "DS::TFEExit, this=0x%p, old nest=%d\n", this, m_cFuncEvalNesting));
// Since this is always called on the hijacking thread, we should be thread-safe
_ASSERTE(thread == this->GetThread());
if (IsDead())
return;
m_cFuncEvalNesting--;
if (m_cFuncEvalNesting == -1)
{
LOG((LF_CORDB, LL_INFO100000, "DS::TFEExit - disabling stepper\n"));
// we're exiting the func-eval session we were created in. So we just completely
// disable ourselves so that we don't fire anything anymore.
// The RS still has to free the stepper though.
// This prevents us from stepping-out of a func-eval. For traditional steppers,
// this is overkill since it won't have any outstanding triggers. (trap-step-out
// won't patch if it crosses a func-eval frame).
// But JMC-steppers have Method-Enter; and so this is the only place we have to
// disable that.
DisableAll();
}
else if (m_cFuncEvalNesting == 0)
{
// We're back to our starting Func-eval session, we should have been frozen,
// so now we thaw.
LOG((LF_CORDB, LL_INFO100000, "DS::TFEExit - thawing stepper\n"));
// Thaw the stepper (reenable triggers)
if ((m_bvFrozenTriggers & kMethodEnter) != 0)
{
EnableMethodEnter();
}
m_bvFrozenTriggers = 0;
}
else
{
LOG((LF_CORDB, LL_INFO100000, "DS::TFEExit - new nest=%d\n", m_cFuncEvalNesting));
}
}
// Return true iff we set a patch (which implies to caller that we should
// let controller run free and hit that patch)
bool DebuggerStepper::TrapStepInto(ControllerStackInfo *info,
const BYTE *ip,
TraceDestination *pTD)
{
_ASSERTE( pTD != NULL );
_ASSERTE(this->GetDCType() == DEBUGGER_CONTROLLER_STEPPER);
EnableTraceCall(LEAF_MOST_FRAME);
if (IsCloserToRoot(info->m_activeFrame.fp, m_fpStepInto))
m_fpStepInto = info->m_activeFrame.fp;
LOG((LF_CORDB, LL_INFO1000, "Ds::TSI this:0x%x m_fpStepInto:0x%x\n",
this, m_fpStepInto.GetSPValue()));
TraceDestination trace;
// Trace through the stubs.
// If we're calling from managed code, this should either succeed
// or become an ecall into mscorwks.
// @Todo - what about stubs in mscorwks.
// @todo - if this fails, we want to provde as much info as possible.
if (!g_pEEInterface->TraceStub(ip, &trace)
|| !g_pEEInterface->FollowTrace(&trace))
{
return false;
}
(*pTD) = trace; //bitwise copy
// Step-in always operates at the leaf-most frame. Thus the frame pointer for any
// patch for step-in should be LEAF_MOST_FRAME, regardless of whatever our current fp
// is before the step-in.
// Note that step-in may skip 'internal' frames (FrameInfo w/ internal=true) since
// such frames may really just be a marker for an internal EE Frame on the stack.
// However, step-out uses these frames b/c it may call frame->TraceFrame() on them.
return PatchTrace(&trace,
LEAF_MOST_FRAME, // step-in is always leaf-most frame.
(m_rgfMappingStop&STOP_UNMANAGED)?(true):(false));
}
// Enable the JMC backstop for stepping on Step-In.
// This activate the JMC probes, which will provide a safety net
// to stop a stepper if the StubManagers don't predict the call properly.
// Ideally, this should never be necessary (because the SMs would do their job).
void DebuggerStepper::EnableJMCBackStop(MethodDesc * pStartMethod)
{
// JMC steppers should not need the JMC backstop unless a thread inadvertently stops in an LCG method.
//_ASSERTE(DEBUGGER_CONTROLLER_JMC_STEPPER != this->GetDCType());
// Since we should never hit the JMC backstop (since it's really a SM issue), we'll assert if we actually do.
// However, there's 1 corner case here. If we trace calls at the start of the method before the JMC-probe,
// then we'll still hit the JMC backstop in our own method.
// Record that starting method. That way, if we end up hitting our JMC backstop in our own method,
// we don't over aggressively fire the assert. (This won't work for recursive cases, but since this is just
// changing an assert, we don't care).
#ifdef _DEBUG
// May be NULL if we didn't start in a method.
m_StepInStartMethod = pStartMethod;
#endif
// We don't want traditional steppers to rely on MethodEnter (b/c it's not guaranteed to be correct),
// but it may be a useful last resort.
this->EnableMethodEnter();
}
// Return true if the stepper can run free.
bool DebuggerStepper::TrapStepInHelper(
ControllerStackInfo * pInfo,
const BYTE * ipCallTarget,
const BYTE * ipNext,
bool fCallingIntoFunclet)
{
TraceDestination td;
#ifdef _DEBUG
// Begin logging the step-in activity in debug builds.
StubManager::DbgBeginLog((TADDR) ipNext, (TADDR) ipCallTarget);
#endif
if (TrapStepInto(pInfo, ipCallTarget, &td))
{
// If we placed a patch, see if we need to update our step-reason
if (td.GetTraceType() == TRACE_MANAGED )
{
// Possible optimization: Roll all of g_pEEInterface calls into
// one function so we don't repeatedly get the CodeMan,etc
MethodDesc *md = NULL;
_ASSERTE( g_pEEInterface->IsManagedNativeCode((const BYTE *)td.GetAddress()) );
md = g_pEEInterface->GetNativeCodeMethodDesc(td.GetAddress());
DebuggerJitInfo* pDJI = g_pDebugger->GetJitInfoFromAddr(td.GetAddress());
CodeRegionInfo code = CodeRegionInfo::GetCodeRegionInfo(pDJI, md);
if (code.AddressToOffset((const BYTE *)td.GetAddress()) == 0)
{
LOG((LF_CORDB,LL_INFO1000,"\tDS::TS 0x%x m_reason = STEP_CALL"
"@ip0x%x\n", this, (BYTE*)GetControlPC(&(pInfo->m_activeFrame.registers))));
m_reason = STEP_CALL;
}
else
{
LOG((LF_CORDB, LL_INFO1000, "Didn't step: md:0x%x"
"td.type:%s td.address:0x%x, gfa:0x%x\n",
md, GetTType(td.GetTraceType()), td.GetAddress(),
g_pEEInterface->GetFunctionAddress(md)));
}
}
else
{
LOG((LF_CORDB,LL_INFO10000,"DS::TS else 0x%x m_reason = STEP_CALL\n",
this));
m_reason = STEP_CALL;
}
return true;
} // end TrapStepIn
else
{
// If we can't figure out where the stepper should call into (likely because we can't find a stub-manager),
// then enable the JMC backstop.
EnableJMCBackStop(pInfo->m_activeFrame.md);
}
// We ignore ipNext here. Instead we'll return false and let the caller (TrapStep)
// set the patch for us.
return false;
}
FORCEINLINE bool IsTailCall(const BYTE * pTargetIP)
{
return TailCallStubManager::IsTailCallStubHelper(reinterpret_cast<PCODE>(pTargetIP));
}
// bool DebuggerStepper::TrapStep() TrapStep attepts to set a
// patch at the next IL instruction to be executed. If we're stepping in &
// the next IL instruction is a call, then this'll set a breakpoint inside
// the code that will be called.
// How: There are a number of cases, depending on where the IP
// currently is:
// Unmanaged code: EnableTraceCall() & return false - try and get
// it when it returns.
// In a frame: if the <p in> param is true, then do an
// EnableTraceCall(). If the frame isn't the top frame, also do
// g_pEEInterface->TraceFrame(), g_pEEInterface->FollowTrace, and
// PatchTrace.
// Normal managed frame: create a Walker and walk the instructions until either
// leave the provided range (AddPatch there, return true), or we don't know what the
// next instruction is (say, after a call, or return, or branch - return false).
// Returns a boolean indicating if we were able to set a patch successfully
// in either this method, or (if in == true & the next instruction is a call)
// inside a callee method.
// true: Patch successfully placed either in this method or a callee,
// so the stepping is taken care of.
// false: Unable to place patch in either this method or any
// applicable callee methods, so the only option the caller has to put
// patch to control flow is to call TrapStepOut & try and place a patch
// on the method that called the current frame's method.
bool DebuggerStepper::TrapStep(ControllerStackInfo *info, bool in)
{
LOG((LF_CORDB,LL_INFO10000,"DS::TS: this:0x%x\n", this));
if (!info->m_activeFrame.managed)
{
//
// We're not in managed code. Patch up all paths back in.
//
LOG((LF_CORDB,LL_INFO10000, "DS::TS: not in managed code\n"));
if (in)
{
EnablePolyTraceCall();
}
return false;
}
if (info->m_activeFrame.frame != NULL)
{
//
// We're in some kind of weird frame. Patch further entry to the frame.
// or if we can't, patch return from the frame
//
LOG((LF_CORDB,LL_INFO10000, "DS::TS: in a weird frame\n"));
if (in)
{
EnablePolyTraceCall();
// Only traditional steppers should patch a frame. JMC steppers will
// just rely on TriggerMethodEnter.
if (DEBUGGER_CONTROLLER_STEPPER == this->GetDCType())
{
if (info->m_activeFrame.frame != FRAME_TOP)
{
TraceDestination trace;
CONTRACT_VIOLATION(GCViolation); // TraceFrame GC-triggers
// This could be anywhere, especially b/c step could be on non-leaf frame.
if (g_pEEInterface->TraceFrame(this->GetThread(),
info->m_activeFrame.frame,
FALSE, &trace,
&(info->m_activeFrame.registers))
&& g_pEEInterface->FollowTrace(&trace)
&& PatchTrace(&trace, info->m_activeFrame.fp,
(m_rgfMappingStop&STOP_UNMANAGED)?
(true):(false)))
{
return true;
}
}
}
}
return false;
}
#ifdef _TARGET_X86_
LOG((LF_CORDB,LL_INFO1000, "GetJitInfo for pc = 0x%x (addr of "
"that value:0x%x)\n", (const BYTE*)(GetControlPC(&info->m_activeFrame.registers)),
info->m_activeFrame.registers.PCTAddr));
#endif
// Note: we used to pass in the IP from the active frame to GetJitInfo, but there seems to be no value in that, and
// it was causing problems creating a stepper while sitting in ndirect stubs after we'd returned from the unmanaged
// function that had been called.
DebuggerJitInfo *ji = info->m_activeFrame.GetJitInfoFromFrame();
if( ji != NULL )
{
LOG((LF_CORDB,LL_INFO10000,"DS::TS: For code 0x%p, got DJI 0x%p, "
"from 0x%p to 0x%p\n",
(const BYTE*)(GetControlPC(&info->m_activeFrame.registers)),
ji, ji->m_addrOfCode, ji->m_addrOfCode+ji->m_sizeOfCode));
}
else
{
LOG((LF_CORDB,LL_INFO10000,"DS::TS: For code 0x%p, "
"didn't get a DJI \n",
(const BYTE*)(GetControlPC(&info->m_activeFrame.registers))));
}
//
// We're in a normal managed frame - walk the code
//
NativeWalker walker;
LOG((LF_CORDB,LL_INFO1000, "DS::TS: &info->m_activeFrame.registers 0x%p\n", &info->m_activeFrame.registers));
// !!! Eventually when using the fjit, we'll want
// to walk the IL to get the next location, & then map
// it back to native.
walker.Init((BYTE*)GetControlPC(&(info->m_activeFrame.registers)), &info->m_activeFrame.registers);
// Is the active frame really the active frame?
// What if the thread is stopped at a managed debug event outside of a filter ctx? Eg, stopped
// somewhere directly in mscorwks (like sending a LogMsg or ClsLoad event) or even at WaitForSingleObject.
// ActiveFrame is either the stepper's initial frame or the frame of a filterctx.
bool fIsActivFrameLive = (info->m_activeFrame.fp == info->m_bottomFP);
// If this thread isn't stopped in managed code, it can't be at the active frame.
if (GetManagedStoppedCtx(this->GetThread()) == NULL)
{
fIsActivFrameLive = false;
}
bool fIsJump = false;
bool fCallingIntoFunclet = false;
// If m_activeFrame is not the actual active frame,
// we should skip this first switch - never single step, and
// assume our context is bogus.
if (fIsActivFrameLive)
{
LOG((LF_CORDB,LL_INFO10000, "DC::TS: immediate?\n"));
// Note that by definition our walker must always be able to step
// through a single instruction, so any return
// of NULL IP's from those cases on the first step
// means that an exception is going to be generated.
//
// (On future steps, it can also mean that the destination
// simply can't be computed.)
WALK_TYPE wt = walker.GetOpcodeWalkType();
{
switch (wt)
{
case WALK_RETURN:
{
LOG((LF_CORDB,LL_INFO10000, "DC::TS:Imm:WALK_RETURN\n"));
// Normally a 'ret' opcode means we're at the end of a function and doing a step-out.
// But the jit is free to use a 'ret' opcode to implement various goofy constructs like
// managed filters, in which case we may ret to the same function or we may ret to some
// internal CLR stub code.
// So we'll just ignore this and tell the Stepper to enable every notification it has
// and let the thread run free. This will include TrapStepOut() and EnableUnwind()
// to catch any potential filters.
// Go ahead and enable the single-step flag too. We know it's safe.
// If this lands in random code, then TriggerSingleStep will just ignore it.
EnableSingleStep();
// Don't set step-reason yet. If another trigger gets hit, it will set the reason.
return false;
}
case WALK_BRANCH:
LOG((LF_CORDB,LL_INFO10000, "DC::TS:Imm:WALK_BRANCH\n"));
// A branch can be handled just like a call. If the branch is within the current method, then we just
// down to WALK_UNKNOWN, otherwise we handle it just like a call. Note: we need to force in=true
// because for a jmp, in or over is the same thing, we're still going there, and the in==true case is
// the case we want to use...
fIsJump = true;
// fall through...
case WALK_CALL:
LOG((LF_CORDB,LL_INFO10000, "DC::TS:Imm:WALK_CALL ip=%p nextip=%p\n", walker.GetIP(), walker.GetNextIP()));
// If we're doing some sort of intra-method jump (usually, to get EIP in a clever way, via the CALL
// instruction), then put the bp where we're going, NOT at the instruction following the call
if (IsAddrWithinFrame(ji, info->m_activeFrame.md, walker.GetIP(), walker.GetNextIP()))
{
LOG((LF_CORDB, LL_INFO1000, "Walk call within method!" ));
goto LWALK_UNKNOWN;
}
if (walker.GetNextIP() != NULL)
{
#ifdef WIN64EXCEPTIONS
// There are 4 places we could be jumping:
// 1) to the beginning of the same method (recursive call)
// 2) somewhere in the same funclet, that isn't the method start
// 3) somewhere in the same method but different funclet
// 4) somewhere in a different method
//
// IsAddrWithinFrame ruled out option 2, IsAddrWithinMethodIncludingFunclet rules out option 4,
// and checking the IP against the start address rules out option 1. That leaves option only what we
// wanted, option #3
fCallingIntoFunclet = IsAddrWithinMethodIncludingFunclet(ji, info->m_activeFrame.md, walker.GetNextIP()) &&
((CORDB_ADDRESS)(SIZE_T)walker.GetNextIP() != ji->m_addrOfCode);
#endif
// At this point, we know that the call/branch target is not in the current method.
// So if the current instruction is a jump, this must be a tail call or possibly a jump to the finally.
// So, check if the call/branch target is the JIT helper for handling tail calls if we are not calling
// into the funclet.
if ((fIsJump && !fCallingIntoFunclet) || IsTailCall(walker.GetNextIP()))
{
// A step-over becomes a step-out for a tail call.
if (!in)
{
TrapStepOut(info);
return true;
}
}
// To preserve the old behaviour, if this is not a tail call, then we assume we want to
// follow the call/jump.
if (fIsJump)
{
in = true;
}
// There are two cases where we need to perform a step-in. One, if the step operation is
// a step-in. Two, if the target address of the call is in a funclet of the current method.
// In this case, we want to step into the funclet even if the step operation is a step-over.
if (in || fCallingIntoFunclet)
{
if (TrapStepInHelper(info, walker.GetNextIP(), walker.GetSkipIP(), fCallingIntoFunclet))
{
return true;
}
}
}
if (walker.GetSkipIP() == NULL)
{
LOG((LF_CORDB,LL_INFO10000,"DS::TS 0x%x m_reason = STEP_CALL (skip)\n",
this));
m_reason = STEP_CALL;
return true;
}
LOG((LF_CORDB,LL_INFO100000, "DC::TS:Imm:WALK_CALL Skip instruction\n"));
walker.Skip();
break;
case WALK_UNKNOWN:
LWALK_UNKNOWN:
LOG((LF_CORDB,LL_INFO10000,"DS::TS:WALK_UNKNOWN - curIP:0x%x "
"nextIP:0x%x skipIP:0x%x 1st byte of opcode:0x%x\n", (BYTE*)GetControlPC(&(info->m_activeFrame.
registers)), walker.GetNextIP(),walker.GetSkipIP(),
*(BYTE*)GetControlPC(&(info->m_activeFrame.registers))));
EnableSingleStep();
return true;
default:
if (walker.GetNextIP() == NULL)
{
return true;
}
walker.Next();
}
}
} // if (fIsActivFrameLive)
//
// Use our range, if we're in the original
// frame.
//
COR_DEBUG_STEP_RANGE *range;
SIZE_T rangeCount;
if (info->m_activeFrame.fp == m_fp)
{
range = m_range;
rangeCount = m_rangeCount;
}
else
{
range = NULL;
rangeCount = 0;
}
//
// Keep walking until either we're out of range, or
// else we can't predict ahead any more.
//
while (TRUE)
{
const BYTE *ip = walker.GetIP();
SIZE_T offset = CodeRegionInfo::GetCodeRegionInfo(ji, info->m_activeFrame.md).AddressToOffset(ip);
LOG((LF_CORDB, LL_INFO1000, "Walking to ip 0x%p (natOff:0x%x)\n",ip,offset));
if (!IsInRange(offset, range, rangeCount)
&& !ShouldContinueStep( info, offset ))
{
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
ji,
offset,
info->m_returnFrame.fp,
NULL);
return true;
}
switch (walker.GetOpcodeWalkType())
{
case WALK_RETURN:
LOG((LF_CORDB, LL_INFO10000, "DS::TS: WALK_RETURN Adding Patch.\n"));
// In the loop above, if we're at the return address, we'll check & see
// if we're returning to elsewhere within the same method, and if so,
// we'll single step rather than TrapStepOut. If we see a return in the
// code stream, then we'll set a breakpoint there, so that we can
// examine the return address, and decide whether to SS or TSO then
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
ji,
offset,
info->m_returnFrame.fp,
NULL);
return true;
case WALK_CALL:
LOG((LF_CORDB, LL_INFO10000, "DS::TS: WALK_CALL.\n"));
// If we're doing some sort of intra-method jump (usually, to get EIP in a clever way, via the CALL
// instruction), then put the bp where we're going, NOT at the instruction following the call
if (IsAddrWithinFrame(ji, info->m_activeFrame.md, walker.GetIP(), walker.GetNextIP()))
{
LOG((LF_CORDB, LL_INFO10000, "DS::TS: WALK_CALL IsAddrWithinFrame, Adding Patch.\n"));
// How else to detect this?
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
ji,
CodeRegionInfo::GetCodeRegionInfo(ji, info->m_activeFrame.md).AddressToOffset(walker.GetNextIP()),
info->m_returnFrame.fp,
NULL);
return true;
}
if (IsTailCall(walker.GetNextIP()))
{
if (!in)
{
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
ji,
offset,
info->m_returnFrame.fp,
NULL);
return true;
}
}
#ifdef WIN64EXCEPTIONS
fCallingIntoFunclet = IsAddrWithinMethodIncludingFunclet(ji, info->m_activeFrame.md, walker.GetNextIP());
#endif
if (in || fCallingIntoFunclet)
{
LOG((LF_CORDB, LL_INFO10000, "DS::TS: WALK_CALL step in is true\n"));
if (walker.GetNextIP() == NULL)
{
LOG((LF_CORDB, LL_INFO10000, "DS::TS: WALK_CALL NextIP == NULL\n"));
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
ji,
offset,
info->m_returnFrame.fp,
NULL);
LOG((LF_CORDB,LL_INFO10000,"DS0x%x m_reason=STEP_CALL 2\n",
this));
m_reason = STEP_CALL;
return true;
}
if (TrapStepInHelper(info, walker.GetNextIP(), walker.GetSkipIP(), fCallingIntoFunclet))
{
return true;
}
}
LOG((LF_CORDB, LL_INFO10000, "DS::TS: WALK_CALL Calling GetSkipIP\n"));
if (walker.GetSkipIP() == NULL)
{
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
ji,
offset,
info->m_returnFrame.fp,
NULL);
LOG((LF_CORDB,LL_INFO10000,"DS 0x%x m_reason=STEP_CALL4\n",this));
m_reason = STEP_CALL;
return true;
}
walker.Skip();
LOG((LF_CORDB, LL_INFO10000, "DS::TS: skipping over call.\n"));
break;
default:
if (walker.GetNextIP() == NULL)
{
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
ji,
offset,
info->m_returnFrame.fp,
NULL);
return true;
}
walker.Next();
break;
}
}
LOG((LF_CORDB,LL_INFO1000,"Ending TrapStep\n"));
}
bool DebuggerStepper::IsAddrWithinFrame(DebuggerJitInfo *dji,
MethodDesc* pMD,
const BYTE* currentAddr,
const BYTE* targetAddr)
{
_ASSERTE(dji != NULL);
bool result = IsAddrWithinMethodIncludingFunclet(dji, pMD, targetAddr);
// We need to check if this is a recursive call. In RTM we should see if this method is really necessary,
// since it looks like the X86 JIT doesn't emit intra-method jumps anymore.
if (result)
{
if ((CORDB_ADDRESS)(SIZE_T)targetAddr == dji->m_addrOfCode)
{
result = false;
}
}
#if defined(WIN64EXCEPTIONS)
// On WIN64, we also check whether the targetAddr and the currentAddr is in the same funclet.
_ASSERTE(currentAddr != NULL);
if (result)
{
int currentFuncletIndex = dji->GetFuncletIndex((CORDB_ADDRESS)currentAddr, DebuggerJitInfo::GFIM_BYADDRESS);
int targetFuncletIndex = dji->GetFuncletIndex((CORDB_ADDRESS)targetAddr, DebuggerJitInfo::GFIM_BYADDRESS);
result = (currentFuncletIndex == targetFuncletIndex);
}
#endif // WIN64EXCEPTIONS
return result;
}
// x86 shouldn't need to call this method directly. We should call IsAddrWithinFrame() on x86 instead.
// That's why I use a name with the word "funclet" in it to scare people off.
bool DebuggerStepper::IsAddrWithinMethodIncludingFunclet(DebuggerJitInfo *dji,
MethodDesc* pMD,
const BYTE* targetAddr)
{
_ASSERTE(dji != NULL);
return CodeRegionInfo::GetCodeRegionInfo(dji, pMD).IsMethodAddress(targetAddr);
}
void DebuggerStepper::TrapStepNext(ControllerStackInfo *info)
{
LOG((LF_CORDB, LL_INFO10000, "DS::TrapStepNext, this=%p\n", this));
// StepNext for a Normal stepper is just a step-out
TrapStepOut(info);
// @todo -should we also EnableTraceCall??
}
// Is this frame interesting?
// For a traditional stepper, all frames are interesting.
bool DebuggerStepper::IsInterestingFrame(FrameInfo * pFrame)
{
LIMITED_METHOD_CONTRACT;
return true;
}
// Place a single patch somewhere up the stack to do a step-out
void DebuggerStepper::TrapStepOut(ControllerStackInfo *info, bool fForceTraditional)
{
ControllerStackInfo returnInfo;
DebuggerJitInfo *dji;
LOG((LF_CORDB, LL_INFO10000, "DS::TSO this:0x%p\n", this));
bool fReturningFromFinallyFunclet = false;
#if defined(WIN64EXCEPTIONS)
// When we step out of a funclet, we should do one of two things, depending
// on the original stepping intention:
// 1) If we originally want to step out, then we should skip the parent method.
// 2) If we originally want to step in/over but we step off the end of the funclet,
// then we should resume in the parent, if possible.
if (info->m_activeFrame.IsNonFilterFuncletFrame())
{
// There should always be a frame for the parent method.
_ASSERTE(info->HasReturnFrame());
#ifdef _TARGET_ARM_
while (info->HasReturnFrame() && info->m_activeFrame.md != info->m_returnFrame.md)
{
StackTraceTicket ticket(info);
returnInfo.GetStackInfo(ticket, GetThread(), info->m_returnFrame.fp, NULL);
info = &returnInfo;
}
_ASSERTE(info->HasReturnFrame());
#endif
_ASSERTE(info->m_activeFrame.md == info->m_returnFrame.md);
if (m_eMode == cStepOut)
{
StackTraceTicket ticket(info);
returnInfo.GetStackInfo(ticket, GetThread(), info->m_returnFrame.fp, NULL);
info = &returnInfo;
}
else
{
_ASSERTE(info->m_returnFrame.managed);
_ASSERTE(info->m_returnFrame.frame == NULL);
MethodDesc *md = info->m_returnFrame.md;
dji = info->m_returnFrame.GetJitInfoFromFrame();
// The return value of a catch funclet is the control PC to resume to.
// The return value of a finally funclet has no meaning, so we need to check
// if the return value is in the main method.
LPVOID resumePC = GetRegdisplayReturnValue(&(info->m_activeFrame.registers));
// For finally funclet, there are two possible situations. Either the finally is
// called normally (i.e. no exception), in which case we simply fall through and
// let the normal loop do its work below, or the finally is called by the EH
// routines, in which case we need the unwind notification.
if (IsAddrWithinMethodIncludingFunclet(dji, md, (const BYTE *)resumePC))
{
SIZE_T reloffset = dji->m_codeRegionInfo.AddressToOffset((BYTE*)resumePC);
AddBindAndActivateNativeManagedPatch(info->m_returnFrame.md,
dji,
reloffset,
info->m_returnFrame.fp,
NULL);
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO:normally managed code AddPatch"
" in %s::%s, offset 0x%x, m_reason=%d\n",
info->m_returnFrame.md->m_pszDebugClassName,
info->m_returnFrame.md->m_pszDebugMethodName,
reloffset, m_reason));
// Do not set m_reason to STEP_RETURN here. Logically, the funclet and the parent method are the
// same method, so we should not "return" to the parent method.
LOG((LF_CORDB, LL_INFO10000,"DS::TSO: done\n"));
return;
}
else
{
// This is the case where we step off the end of a finally funclet.
fReturningFromFinallyFunclet = true;
}
}
}
#endif // WIN64EXCEPTIONS
#ifdef _DEBUG
FramePointer dbgLastFP; // for debug, make sure we're making progress through the stack.
#endif
while (info->HasReturnFrame())
{
#ifdef _DEBUG
dbgLastFP = info->m_activeFrame.fp;
#endif
// Continue walking up the stack & set a patch upon the next
// frame up. We will eventually either hit managed code
// (which we can set a definite patch in), or the top of the
// stack.
StackTraceTicket ticket(info);
// The last parameter here is part of a really targetted (*cough* dirty) fix to
// disable getting an unwanted UMChain to fix issue 650903 (See
// code:ControllerStackInfo::WalkStack and code:TrackUMChain for the other
// parts.) In the case of managed step out we know that we aren't interested in
// unmanaged frames, and generating that unmanaged frame causes the stackwalker
// not to report the managed frame that was at the same SP. However the unmanaged
// frame might be used in the mixed-mode step out case so I don't suppress it
// there.
returnInfo.GetStackInfo(ticket, GetThread(), info->m_returnFrame.fp, NULL, !(m_rgfMappingStop & STOP_UNMANAGED));
info = &returnInfo;
#ifdef _DEBUG
// If this assert fires, then it means that we're not making progress while
// tracing up the towards the root of the stack. Likely an issue in the Left-Side's
// stackwalker.
_ASSERTE(IsCloserToLeaf(dbgLastFP, info->m_activeFrame.fp));
#endif
#ifdef FEATURE_STUBS_AS_IL
if (info->m_activeFrame.md->IsILStub() && info->m_activeFrame.md->AsDynamicMethodDesc()->IsMulticastStub())
{
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO: multicast frame.\n"));
// User break should always be called from managed code, so it should never actually hit this codepath.
_ASSERTE(GetDCType() != DEBUGGER_CONTROLLER_USER_BREAKPOINT);
// JMC steppers shouldn't be patching stubs.
if (DEBUGGER_CONTROLLER_JMC_STEPPER == this->GetDCType())
{
LOG((LF_CORDB, LL_INFO10000, "DS::TSO: JMC stepper skipping frame.\n"));
continue;
}
TraceDestination trace;
EnableTraceCall(info->m_activeFrame.fp);
PCODE ip = GetControlPC(&(info->m_activeFrame.registers));
if (g_pEEInterface->TraceStub((BYTE*)ip, &trace)
&& g_pEEInterface->FollowTrace(&trace)
&& PatchTrace(&trace, info->m_activeFrame.fp,
true))
break;
}
else
#endif // FEATURE_STUBS_AS_IL
if (info->m_activeFrame.managed)
{
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO: return frame is managed.\n"));
if (info->m_activeFrame.frame == NULL)
{
// Returning normally to managed code.
_ASSERTE(info->m_activeFrame.md != NULL);
// Polymorphic check to skip over non-interesting frames.
if (!fForceTraditional && !this->IsInterestingFrame(&info->m_activeFrame))
continue;
dji = info->m_activeFrame.GetJitInfoFromFrame();
_ASSERTE(dji != NULL);
// Note: we used to pass in the IP from the active frame to GetJitInfo, but there seems to be no value
// in that, and it was causing problems creating a stepper while sitting in ndirect stubs after we'd
// returned from the unmanaged function that had been called.
ULONG reloffset = info->m_activeFrame.relOffset;
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
dji,
reloffset,
info->m_returnFrame.fp,
NULL);
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO:normally managed code AddPatch"
" in %s::%s, offset 0x%x, m_reason=%d\n",
info->m_activeFrame.md->m_pszDebugClassName,
info->m_activeFrame.md->m_pszDebugMethodName,
reloffset, m_reason));
// Do not set m_reason to STEP_RETURN here. Logically, the funclet and the parent method are the
// same method, so we should not "return" to the parent method.
if (!fReturningFromFinallyFunclet)
{
m_reason = STEP_RETURN;
}
break;
}
else if (info->m_activeFrame.frame == FRAME_TOP)
{
// Trad-stepper's step-out is actually like a step-next when we go off the top.
// JMC-steppers do a true-step out. So for JMC-steppers, don't enable trace-call.
if (DEBUGGER_CONTROLLER_JMC_STEPPER == this->GetDCType())
{
LOG((LF_CORDB, LL_EVERYTHING, "DS::TSO: JMC stepper skipping exit-frame case.\n"));
break;
}
// User break should always be called from managed code, so it should never actually hit this codepath.
_ASSERTE(GetDCType() != DEBUGGER_CONTROLLER_USER_BREAKPOINT);
// We're walking off the top of the stack. Note that if we call managed code again,
// this trace-call will cause us our stepper-to fire. So we'll actually do a
// step-next; not a true-step out.
EnableTraceCall(info->m_activeFrame.fp);
LOG((LF_CORDB, LL_INFO1000, "DS::TSO: Off top of frame!\n"));
m_reason = STEP_EXIT; //we're on the way out..
// <REVISIT_TODO>@todo not that it matters since we don't send a
// stepComplete message to the right side.</REVISIT_TODO>
break;
}
else if (info->m_activeFrame.frame->GetFrameType() == Frame::TYPE_FUNC_EVAL)
{
// Note: we treat walking off the top of the stack and
// walking off the top of a func eval the same way,
// except that we don't enable trace call since we
// know exactly where were going.
LOG((LF_CORDB, LL_INFO1000,
"DS::TSO: Off top of func eval!\n"));
m_reason = STEP_EXIT;
break;
}
else if (info->m_activeFrame.frame->GetFrameType() == Frame::TYPE_SECURITY &&
info->m_activeFrame.frame->GetInterception() == Frame::INTERCEPTION_NONE)
{
// If we're stepping out of something that was protected by (declarative) security,
// the security subsystem may leave a frame on the stack to cache it's computation.
// HOWEVER, this isn't a real frame, and so we don't want to stop here. On the other
// hand, if we're in the security goop (sec. executes managed code to do stuff), then
// we'll want to use the "returning to stub case", below. GetInterception()==NONE
// indicates that the frame is just a cache frame:
// Skip it and keep on going
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO: returning to a non-intercepting frame. Keep unwinding\n"));
continue;
}
else
{
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO: returning to a stub frame.\n"));
// User break should always be called from managed code, so it should never actually hit this codepath.
_ASSERTE(GetDCType() != DEBUGGER_CONTROLLER_USER_BREAKPOINT);
// JMC steppers shouldn't be patching stubs.
if (DEBUGGER_CONTROLLER_JMC_STEPPER == this->GetDCType())
{
LOG((LF_CORDB, LL_INFO10000, "DS::TSO: JMC stepper skipping frame.\n"));
continue;
}
// We're returning to some funky frame.
// (E.g. a security frame has called a native method.)
// Patch the frame from entering other methods. This effectively gives the Step-out
// a step-next behavior. For eg, this can be useful for step-out going between multicast delegates.
// This step-next could actually land us leaf-more on the callstack than we currently are!
// If we were a true-step out, we'd skip this and keep crawling.
// up the callstack.
//
// !!! For now, we assume that the TraceFrame entry
// point is smart enough to tell where it is in the
// calling sequence. We'll see how this holds up.
TraceDestination trace;
// We don't want notifications of trace-calls leaf-more than our current frame.
// For eg, if our current frame calls out to unmanaged code and then back in,
// we'll get a TraceCall notification. But since it's leaf-more than our current frame,
// we don't care because we just want to step out of our current frame (and everything
// our current frame may call).
EnableTraceCall(info->m_activeFrame.fp);
CONTRACT_VIOLATION(GCViolation); // TraceFrame GC-triggers
if (g_pEEInterface->TraceFrame(GetThread(),
info->m_activeFrame.frame, FALSE,
&trace, &(info->m_activeFrame.registers))
&& g_pEEInterface->FollowTrace(&trace)
&& PatchTrace(&trace, info->m_activeFrame.fp,
true))
break;
// !!! Problem: we don't know which return frame to use -
// the TraceFrame patch may be in a frame below the return
// frame, or in a frame parallel with it
// (e.g. prestub popping itself & then calling.)
//
// For now, I've tweaked the FP comparison in the
// patch dispatching code to allow either case.
}
}
else
{
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO: return frame is not managed.\n"));
// Only step out to unmanaged code if we're actually
// marked to stop in unamanged code. Otherwise, just loop
// to get us past the unmanaged frames.
if (m_rgfMappingStop & STOP_UNMANAGED)
{
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO: return to unmanaged code "
"m_reason=STEP_RETURN\n"));
// Do not set m_reason to STEP_RETURN here. Logically, the funclet and the parent method are the
// same method, so we should not "return" to the parent method.
if (!fReturningFromFinallyFunclet)
{
m_reason = STEP_RETURN;
}
// We're stepping out into unmanaged code
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO: Setting unmanaged trace patch at 0x%x(%x)\n",
GetControlPC(&(info->m_activeFrame.registers)),
info->m_returnFrame.fp.GetSPValue()));
AddAndActivateNativePatchForAddress((CORDB_ADDRESS_TYPE *)GetControlPC(&(info->m_activeFrame.registers)),
info->m_returnFrame.fp,
FALSE,
TRACE_UNMANAGED);
break;
}
}
}
// <REVISIT_TODO>If we get here, we may be stepping out of the last frame. Our thread
// exit logic should catch this case. (@todo)</REVISIT_TODO>
LOG((LF_CORDB, LL_INFO10000,"DS::TSO: done\n"));
}
// void DebuggerStepper::StepOut()
// Called by Debugger::HandleIPCEvent to setup
// everything so that the process will step over the range of IL
// correctly.
// How: Converts the provided array of ranges from IL ranges to
// native ranges (if they're not native already), and then calls
// TrapStep or TrapStepOut, like so:
// Get the appropriate MethodDesc & JitInfo
// Iterate through array of IL ranges, use
// JitInfo::MapILRangeToMapEntryRange to translate IL to native
// ranges.
// Set member variables to remember that the DebuggerStepper now uses
// the ranges: m_range, m_rangeCount, m_stepIn, m_fp
// If (!TrapStep()) then {m_stepIn = true; TrapStepOut()}
// EnableUnwind( m_fp );
void DebuggerStepper::StepOut(FramePointer fp, StackTraceTicket ticket)
{
LOG((LF_CORDB, LL_INFO10000, "Attempting to step out, fp:0x%x this:0x%x"
"\n", fp.GetSPValue(), this ));
Thread *thread = GetThread();
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(thread);
ControllerStackInfo info;
// We pass in the ticket b/c this is called both when we're live (via
// DebuggerUserBreakpoint) and when we're stopped (via normal StepOut)
info.GetStackInfo(ticket, thread, fp, context);
ResetRange();
m_stepIn = FALSE;
m_fp = info.m_activeFrame.fp;
#if defined(WIN64EXCEPTIONS)
// We need to remember the parent method frame pointer here so that we will recognize
// the range of the stepper as being valid when we return to the parent method.
if (info.m_activeFrame.IsNonFilterFuncletFrame())
{
m_fpParentMethod = info.m_returnFrame.fp;
}
#endif // WIN64EXCEPTIONS
m_eMode = cStepOut;
_ASSERTE((fp == LEAF_MOST_FRAME) || (info.m_activeFrame.md != NULL) || (info.m_returnFrame.md != NULL));
TrapStepOut(&info);
EnableUnwind(m_fp);
}
#define GROW_RANGES_IF_NECESSARY() \
if (rTo == rToEnd) \
{ \
ULONG NewSize, OldSize; \
if (!ClrSafeInt<ULONG>::multiply(sizeof(COR_DEBUG_STEP_RANGE), (ULONG)(realRangeCount*2), NewSize) || \
!ClrSafeInt<ULONG>::multiply(sizeof(COR_DEBUG_STEP_RANGE), (ULONG)realRangeCount, OldSize) || \
NewSize < OldSize) \
{ \
DeleteInteropSafe(m_range); \
m_range = NULL; \
return false; \
} \
COR_DEBUG_STEP_RANGE *_pTmp = (COR_DEBUG_STEP_RANGE*) \
g_pDebugger->GetInteropSafeHeap()->Realloc(m_range, \
NewSize, \
OldSize); \
\
if (_pTmp == NULL) \
{ \
DeleteInteropSafe(m_range); \
m_range = NULL; \
return false; \
} \
\
m_range = _pTmp; \
rTo = m_range + realRangeCount; \
rToEnd = m_range + (realRangeCount*2); \
realRangeCount *= 2; \
}
//-----------------------------------------------------------------------------
// Given a set of IL ranges, convert them to native and cache them.
// Return true on success, false on error.
//-----------------------------------------------------------------------------
bool DebuggerStepper::SetRangesFromIL(DebuggerJitInfo *dji, COR_DEBUG_STEP_RANGE *ranges, SIZE_T rangeCount)
{
CONTRACTL
{
SO_NOT_MAINLINE;
WRAPPER(THROWS);
GC_NOTRIGGER;
PRECONDITION(ThisIsHelperThreadWorker()); // Only help initializes a stepper.
PRECONDITION(m_range == NULL); // shouldn't be set already.
PRECONDITION(CheckPointer(ranges));
PRECONDITION(CheckPointer(dji));
}
CONTRACTL_END;
// Note: we used to pass in the IP from the active frame to GetJitInfo, but there seems to be no value in that, and
// it was causing problems creating a stepper while sitting in ndirect stubs after we'd returned from the unmanaged
// function that had been called.
MethodDesc *fd = dji->m_fd;
// The "+1" is for internal use, when we need to
// set an intermediate patch in pitched code. Isn't
// used unless the method is pitched & a patch is set
// inside it. Thus we still pass cRanges as the
// range count.
m_range = new (interopsafe) COR_DEBUG_STEP_RANGE[rangeCount+1];
if (m_range == NULL)
return false;
TRACE_ALLOC(m_range);
SIZE_T realRangeCount = rangeCount;
if (dji != NULL)
{
LOG((LF_CORDB,LL_INFO10000,"DeSt::St: For code md=0x%x, got DJI 0x%x, from 0x%x to 0x%x\n",
fd,
dji, dji->m_addrOfCode, (ULONG)dji->m_addrOfCode
+ (ULONG)dji->m_sizeOfCode));
//
// Map ranges to native offsets for jitted code
//
COR_DEBUG_STEP_RANGE *r, *rEnd, *rTo, *rToEnd;
r = ranges;
rEnd = r + rangeCount;
rTo = m_range;
rToEnd = rTo + realRangeCount;
// <NOTE>
// rTo may also be incremented in the middle of the loop on WIN64 platforms.
// </NOTE>
for (/**/; r < rEnd; r++, rTo++)
{
// If we are already at the end of our allocated array, but there are still
// more ranges to copy over, then grow the array.
GROW_RANGES_IF_NECESSARY();
if (r->startOffset == 0 && r->endOffset == (ULONG) ~0)
{
// {0...-1} means use the entire method as the range
// Code dup'd from below case.
LOG((LF_CORDB, LL_INFO10000, "DS:Step: Have DJI, special (0,-1) entry\n"));
rTo->startOffset = 0;
rTo->endOffset = (ULONG32)g_pEEInterface->GetFunctionSize(fd);
}
else
{
//
// One IL range may consist of multiple
// native ranges.
//
DebuggerILToNativeMap *mStart, *mEnd;
dji->MapILRangeToMapEntryRange(r->startOffset,
r->endOffset,
&mStart,
&mEnd);
// Either mStart and mEnd are both NULL (we don't have any sequence point),
// or they are both non-NULL.
_ASSERTE( ((mStart == NULL) && (mEnd == NULL)) ||
((mStart != NULL) && (mEnd != NULL)) );
if (mStart == NULL)
{
// <REVISIT_TODO>@todo Won't this result in us stepping across
// the entire method?</REVISIT_TODO>
rTo->startOffset = 0;
rTo->endOffset = 0;
}
else if (mStart == mEnd)
{
rTo->startOffset = mStart->nativeStartOffset;
rTo->endOffset = mStart->nativeEndOffset;
}
else
{
// Account for more than one continuous range here.
// Move the pointer back to work with the loop increment below.
// Don't dereference this pointer now!
rTo--;
for (DebuggerILToNativeMap* pMap = mStart;
pMap <= mEnd;
pMap = pMap + 1)
{
if ((pMap == mStart) ||
(pMap->nativeStartOffset != (pMap-1)->nativeEndOffset))
{
rTo++;
GROW_RANGES_IF_NECESSARY();
rTo->startOffset = pMap->nativeStartOffset;
rTo->endOffset = pMap->nativeEndOffset;
}
else
{
// If we have continuous ranges, then lump them together.
_ASSERTE(rTo->endOffset == pMap->nativeStartOffset);
rTo->endOffset = pMap->nativeEndOffset;
}
}
LOG((LF_CORDB, LL_INFO10000, "DS:Step: nat off:0x%x to 0x%x\n", rTo->startOffset, rTo->endOffset));
}
}
}
rangeCount = (int)((BYTE*)rTo - (BYTE*)m_range) / sizeof(COR_DEBUG_STEP_RANGE);
}
else
{
// Even if we don't have debug info, we'll be able to
// step through the method
SIZE_T functionSize = g_pEEInterface->GetFunctionSize(fd);
COR_DEBUG_STEP_RANGE *r = ranges;
COR_DEBUG_STEP_RANGE *rEnd = r + rangeCount;
COR_DEBUG_STEP_RANGE *rTo = m_range;
for(/**/; r < rEnd; r++, rTo++)
{
if (r->startOffset == 0 && r->endOffset == (ULONG) ~0)
{
LOG((LF_CORDB, LL_INFO10000, "DS:Step:No DJI, (0,-1) special entry\n"));
// Code dup'd from above case.
// {0...-1} means use the entire method as the range
rTo->startOffset = 0;
rTo->endOffset = (ULONG32)functionSize;
}
else
{
LOG((LF_CORDB, LL_INFO10000, "DS:Step:No DJI, regular entry\n"));
// We can't just leave ths IL entry - we have to
// get rid of it.
// This will just be ignored
rTo->startOffset = rTo->endOffset = (ULONG32)functionSize;
}
}
}
m_rangeCount = rangeCount;
m_realRangeCount = rangeCount;
return true;
}
// void DebuggerStepper::Step() Tells the stepper to step over
// the provided ranges.
// void *fp: frame pointer.
// bool in: true if we want to step into a function within the range,
// false if we want to step over functions within the range.
// COR_DEBUG_STEP_RANGE *ranges: Assumed to be nonNULL, it will
// always hold at least one element.
// SIZE_T rangeCount: One less than the true number of elements in
// the ranges argument.
// bool rangeIL: true if the ranges are provided in IL (they'll be
// converted to native before the DebuggerStepper uses them,
// false if they already are native.
bool DebuggerStepper::Step(FramePointer fp, bool in,
COR_DEBUG_STEP_RANGE *ranges, SIZE_T rangeCount,
bool rangeIL)
{
LOG((LF_CORDB, LL_INFO1000, "DeSt:Step this:0x%x ", this));
if (rangeCount>0)
LOG((LF_CORDB,LL_INFO10000," start,end[0]:(0x%x,0x%x)\n",
ranges[0].startOffset, ranges[0].endOffset));
else
LOG((LF_CORDB,LL_INFO10000," single step\n"));
Thread *thread = GetThread();
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(thread);
// ControllerStackInfo doesn't report IL stubs, so if we are in an IL stub, we need
// to handle the single-step specially. There are probably other problems when we stop
// in an IL stub. We need to revisit this later.
bool fIsILStub = false;
if ((context != NULL) &&
g_pEEInterface->IsManagedNativeCode(reinterpret_cast<const BYTE *>(GetIP(context))))
{
MethodDesc * pMD = g_pEEInterface->GetNativeCodeMethodDesc(GetIP(context));
if (pMD != NULL)
{
fIsILStub = pMD->IsILStub();
}
}
LOG((LF_CORDB, LL_INFO10000, "DS::S - fIsILStub = %d\n", fIsILStub));
ControllerStackInfo info;
StackTraceTicket ticket(thread);
info.GetStackInfo(ticket, thread, fp, context);
_ASSERTE((fp == LEAF_MOST_FRAME) || (info.m_activeFrame.md != NULL) ||
(info.m_returnFrame.md != NULL));
m_stepIn = in;
DebuggerJitInfo *dji = info.m_activeFrame.GetJitInfoFromFrame();
if (dji == NULL)
{
// !!! ERROR range step in frame with no code
ranges = NULL;
rangeCount = 0;
}
if (m_range != NULL)
{
TRACE_FREE(m_range);
DeleteInteropSafe(m_range);
m_range = NULL;
m_rangeCount = 0;
m_realRangeCount = 0;
}
if (rangeCount > 0)
{
if (rangeIL)
{
// IL ranges supplied, we need to convert them to native ranges.
bool fOk = SetRangesFromIL(dji, ranges, rangeCount);
if (!fOk)
{
return false;
}
}
else
{
// Native ranges, already supplied. Just copy them over.
m_range = new (interopsafe) COR_DEBUG_STEP_RANGE[rangeCount];
if (m_range == NULL)
{
return false;
}
memcpy(m_range, ranges, sizeof(COR_DEBUG_STEP_RANGE) * rangeCount);
m_realRangeCount = m_rangeCount = rangeCount;
}
_ASSERTE(m_range != NULL);
_ASSERTE(m_rangeCount > 0);
_ASSERTE(m_realRangeCount > 0);
}
else
{
// !!! ERROR cannot map IL ranges
ranges = NULL;
rangeCount = 0;
}
if (fIsILStub)
{
// Don't use the ControllerStackInfo if we are in an IL stub.
m_fp = fp;
}
else
{
m_fp = info.m_activeFrame.fp;
#if defined(WIN64EXCEPTIONS)
// We need to remember the parent method frame pointer here so that we will recognize
// the range of the stepper as being valid when we return to the parent method.
if (info.m_activeFrame.IsNonFilterFuncletFrame())
{
m_fpParentMethod = info.m_returnFrame.fp;
}
#endif // WIN64EXCEPTIONS
}
m_eMode = m_stepIn ? cStepIn : cStepOver;
LOG((LF_CORDB,LL_INFO10000,"DS 0x%x STep: STEP_NORMAL\n",this));
m_reason = STEP_NORMAL; //assume it'll be a normal step & set it to
//something else if we walk over it
if (fIsILStub)
{
LOG((LF_CORDB, LL_INFO10000, "DS:Step: stepping in an IL stub\n"));
// Enable the right triggers if the user wants to step in.
if (in)
{
if (this->GetDCType() == DEBUGGER_CONTROLLER_STEPPER)
{
EnableTraceCall(info.m_activeFrame.fp);
}
else if (this->GetDCType() == DEBUGGER_CONTROLLER_JMC_STEPPER)
{
EnableMethodEnter();
}
}
// Also perform a step-out in case this IL stub is returning to managed code.
// However, we must fix up the ControllerStackInfo first, since it doesn't
// report IL stubs. The active frame reported by the ControllerStackInfo is
// actually the return frame in this case.
info.SetReturnFrameWithActiveFrame();
TrapStepOut(&info);
}
else if (!TrapStep(&info, in))
{
LOG((LF_CORDB,LL_INFO10000,"DS:Step: Did TS\n"));
m_stepIn = true;
TrapStepNext(&info);
}
LOG((LF_CORDB,LL_INFO10000,"DS:Step: Did TS,TSO\n"));
EnableUnwind(m_fp);
return true;
}
// TP_RESULT DebuggerStepper::TriggerPatch()
// What: Triggers patch if we're not in a stub, and we're
// outside of the stepping range. Otherwise sets another patch so as to
// step out of the stub, or in the next instruction within the range.
// How: If module==NULL & managed==> we're in a stub:
// TrapStepOut() and return false. Module==NULL&!managed==> return
// true. If m_range != NULL & execution is currently in the range,
// attempt a TrapStep (TrapStepOut otherwise) & return false. Otherwise,
// return true.
TP_RESULT DebuggerStepper::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
LOG((LF_CORDB, LL_INFO10000, "DeSt::TP\n"));
// If we're frozen, we may hit a patch but we just ignore it
if (IsFrozen())
{
LOG((LF_CORDB, LL_INFO1000000, "DS::TP, ignoring patch at %p during frozen state\n", patch->address));
return TPR_IGNORE;
}
Module *module = patch->key.module;
BOOL managed = patch->IsManagedPatch();
mdMethodDef md = patch->key.md;
SIZE_T offset = patch->offset;
_ASSERTE((this->GetThread() == thread) || !"Stepper should only get patches on its thread");
// Note we can only run a stack trace if:
// - the context is in managed code (eg, not a stub)
// - OR we have a frame in place to prime the stackwalk.
ControllerStackInfo info;
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(thread);
_ASSERTE(!ISREDIRECTEDTHREAD(thread));
// Context should always be from patch.
_ASSERTE(context != NULL);
bool fSafeToDoStackTrace = true;
// If we're in a stub (module == NULL and still in managed code), then our context is off in lala-land
// Then, it's only safe to do a stackwalk if the top frame is protecting us. That's only true for a
// frame_push. If we're here on a manager_push, then we don't have any such protection, so don't do the
// stackwalk.
fSafeToDoStackTrace = patch->IsSafeForStackTrace();
if (fSafeToDoStackTrace)
{
StackTraceTicket ticket(patch);
info.GetStackInfo(ticket, thread, LEAF_MOST_FRAME, context);
LOG((LF_CORDB, LL_INFO10000, "DS::TP: this:0x%p in %s::%s (fp:0x%p, "
"off:0x%p md:0x%p), \n\texception source:%s::%s (fp:0x%p)\n",
this,
info.m_activeFrame.md!=NULL?info.m_activeFrame.md->m_pszDebugClassName:"Unknown",
info.m_activeFrame.md!=NULL?info.m_activeFrame.md->m_pszDebugMethodName:"Unknown",
info.m_activeFrame.fp.GetSPValue(), patch->offset, patch->key.md,
m_fdException!=NULL?m_fdException->m_pszDebugClassName:"None",
m_fdException!=NULL?m_fdException->m_pszDebugMethodName:"None",
m_fpException.GetSPValue()));
}
DisableAll();
if (DetectHandleLCGMethods(dac_cast<PCODE>(patch->address), NULL, &info))
{
return TPR_IGNORE;
}
if (module == NULL)
{
// JMC steppers should not be patching here...
_ASSERTE(DEBUGGER_CONTROLLER_JMC_STEPPER != this->GetDCType());
if (managed)
{
LOG((LF_CORDB, LL_INFO10000,
"Frame (stub) patch hit at offset 0x%x\n", offset));
// This is a stub patch. If it was a TRACE_FRAME_PUSH that
// got us here, then the stub's frame is pushed now, so we
// tell the frame to apply the real patch. If we got here
// via a TRACE_MGR_PUSH, however, then there is no frame
// and we tell the stub manager that generated the
// TRACE_MGR_PUSH to apply the real patch.
TraceDestination trace;
bool traceOk;
FramePointer frameFP;
PTR_BYTE traceManagerRetAddr = NULL;
if (patch->trace.GetTraceType() == TRACE_MGR_PUSH)
{
_ASSERTE(context != NULL);
CONTRACT_VIOLATION(GCViolation);
traceOk = g_pEEInterface->TraceManager(
thread,
patch->trace.GetStubManager(),
&trace,
context,
&traceManagerRetAddr);
// We don't hae an active frame here, so patch with a
// FP of NULL so anything will match.
//
// <REVISIT_TODO>@todo: should we take Esp out of the context?</REVISIT_TODO>
frameFP = LEAF_MOST_FRAME;
}
else
{
_ASSERTE(fSafeToDoStackTrace);
CONTRACT_VIOLATION(GCViolation); // TraceFrame GC-triggers
traceOk = g_pEEInterface->TraceFrame(thread,
thread->GetFrame(),
TRUE,
&trace,
&(info.m_activeFrame.registers));
frameFP = info.m_activeFrame.fp;
}
// Enable the JMC backstop for traditional steppers to catch us in case
// we didn't predict the call target properly.
EnableJMCBackStop(NULL);
if (!traceOk
|| !g_pEEInterface->FollowTrace(&trace)
|| !PatchTrace(&trace, frameFP,
(m_rgfMappingStop&STOP_UNMANAGED)?
(true):(false)))
{
//
// We can't set a patch in the frame -- we need
// to trap returning from this frame instead.
//
// Note: if we're in the TRACE_MGR_PUSH case from
// above, then we must place a patch where the
// TraceManager function told us to, since we can't
// actually unwind from here.
//
if (patch->trace.GetTraceType() != TRACE_MGR_PUSH)
{
_ASSERTE(fSafeToDoStackTrace);
LOG((LF_CORDB,LL_INFO10000,"TSO for non TRACE_MGR_PUSH case\n"));
TrapStepOut(&info);
}
else
{
LOG((LF_CORDB, LL_INFO10000,
"TSO for TRACE_MGR_PUSH case."));
// We'd better have a valid return address.
_ASSERTE(traceManagerRetAddr != NULL);
if (g_pEEInterface->IsManagedNativeCode(traceManagerRetAddr))
{
// Grab the jit info for the method.
DebuggerJitInfo *dji;
dji = g_pDebugger->GetJitInfoFromAddr((TADDR) traceManagerRetAddr);
MethodDesc * mdNative = (dji == NULL) ?
g_pEEInterface->GetNativeCodeMethodDesc(dac_cast<PCODE>(traceManagerRetAddr)) : dji->m_fd;
_ASSERTE(mdNative != NULL);
// Find the method that the return is to.
_ASSERTE(g_pEEInterface->GetFunctionAddress(mdNative) != NULL);
SIZE_T offsetRet = dac_cast<TADDR>(traceManagerRetAddr -
g_pEEInterface->GetFunctionAddress(mdNative));
// Place the patch.
AddBindAndActivateNativeManagedPatch(mdNative,
dji,
offsetRet,
LEAF_MOST_FRAME,
NULL);
LOG((LF_CORDB, LL_INFO10000,
"DS::TP: normally managed code AddPatch"
" in %s::%s, offset 0x%x\n",
mdNative->m_pszDebugClassName,
mdNative->m_pszDebugMethodName,
offsetRet));
}
else
{
// We're hitting this code path with MC++ assemblies
// that have an unmanaged entry point so the stub returns to CallDescrWorker.
_ASSERTE(g_pEEInterface->GetNativeCodeMethodDesc(dac_cast<PCODE>(patch->address))->IsILStub());
}
}
m_reason = STEP_NORMAL; //we tried to do a STEP_CALL, but since it didn't
//work, we're doing what amounts to a normal step.
LOG((LF_CORDB,LL_INFO10000,"DS 0x%x m_reason = STEP_NORMAL"
"(attempted call thru stub manager, SM didn't know where"
" we're going, so did a step out to original call\n",this));
}
else
{
m_reason = STEP_CALL;
}
EnableTraceCall(LEAF_MOST_FRAME);
EnableUnwind(m_fp);
return TPR_IGNORE;
}
else
{
// @todo - when would we hit this codepath?
// If we're not in managed, then we should have pushed a frame onto the Thread's frame chain,
// and thus we should still safely be able to do a stackwalk here.
_ASSERTE(fSafeToDoStackTrace);
if (DetectHandleInterceptors(&info) )
{
return TPR_IGNORE; //don't actually want to stop
}
LOG((LF_CORDB, LL_INFO10000,
"Unmanaged step patch hit at 0x%x\n", offset));
StackTraceTicket ticket(patch);
PrepareForSendEvent(ticket);
return TPR_TRIGGER;
}
} // end (module == NULL)
// If we're inside an interceptor but don't want to be,then we'll set a
// patch outside the current function.
_ASSERTE(fSafeToDoStackTrace);
if (DetectHandleInterceptors(&info) )
{
return TPR_IGNORE; //don't actually want to stop
}
LOG((LF_CORDB,LL_INFO10000, "DS: m_fp:0x%p, activeFP:0x%p fpExc:0x%p\n",
m_fp.GetSPValue(), info.m_activeFrame.fp.GetSPValue(), m_fpException.GetSPValue()));
if (IsInRange(offset, m_range, m_rangeCount, &info) ||
ShouldContinueStep( &info, offset))
{
LOG((LF_CORDB, LL_INFO10000,
"Intermediate step patch hit at 0x%x\n", offset));
if (!TrapStep(&info, m_stepIn))
TrapStepNext(&info);
EnableUnwind(m_fp);
return TPR_IGNORE;
}
else
{
LOG((LF_CORDB, LL_INFO10000, "Step patch hit at 0x%x\n", offset));
// For a JMC stepper, we have an additional constraint:
// skip non-user code. So if we're still in non-user code, then
// we've got to keep going
DebuggerMethodInfo * dmi = g_pDebugger->GetOrCreateMethodInfo(module, md);
if ((dmi != NULL) && DetectHandleNonUserCode(&info, dmi))
{
return TPR_IGNORE;
}
StackTraceTicket ticket(patch);
PrepareForSendEvent(ticket);
return TPR_TRIGGER;
}
}
// Return true if this should be skipped.
// For a non-jmc stepper, we don't care about non-user code, so we
// don't skip it and so we always return false.
bool DebuggerStepper::DetectHandleNonUserCode(ControllerStackInfo *info, DebuggerMethodInfo * pInfo)
{
LIMITED_METHOD_CONTRACT;
return false;
}
// For regular steppers, trace-call is just a trace-call.
void DebuggerStepper::EnablePolyTraceCall()
{
this->EnableTraceCall(LEAF_MOST_FRAME);
}
// Traditional steppers enable MethodEnter as a back-stop for step-in.
// We hope that the stub-managers will predict the step-in for us,
// but in case they don't the Method-Enter should catch us.
// MethodEnter is not fully correct for traditional steppers for a few reasons:
// - doesn't handle step-in to native
// - stops us *after* the prolog (a traditional stepper can stop us before the prolog).
// - only works for methods that have the JMC probe. That can exclude all optimized code.
void DebuggerStepper::TriggerMethodEnter(Thread * thread,
DebuggerJitInfo *dji,
const BYTE * ip,
FramePointer fp)
{
_ASSERTE(dji != NULL);
_ASSERTE(thread != NULL);
_ASSERTE(ip != NULL);
_ASSERTE(this->GetDCType() == DEBUGGER_CONTROLLER_STEPPER);
_ASSERTE(!IsFrozen());
MethodDesc * pDesc = dji->m_fd;
LOG((LF_CORDB, LL_INFO10000, "DJMCStepper::TME, desc=%p, addr=%p\n",
pDesc, ip));
// JMC steppers won't stop in Lightweight delegates. Just return & keep executing.
if (pDesc->IsNoMetadata())
{
LOG((LF_CORDB, LL_INFO100000, "DJMCStepper::TME, skipping b/c it's lw-codegen\n"));
return;
}
// This is really just a heuristic. We don't want to trigger a JMC probe when we are
// executing in an IL stub, or in one of the marshaling methods called by the IL stub.
// The problem is that the IL stub can call into arbitrary code, including custom marshalers.
// In that case the user has to put a breakpoint to stop in the code.
if (g_pEEInterface->DetectHandleILStubs(thread))
{
return;
}
#ifdef _DEBUG
// To help trace down if a problem is related to a stubmanager,
// we add a knob that lets us skip the MethodEnter checks. This lets tests directly
// go against the Stub-managers w/o the MethodEnter check backstops.
int fSkip = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DbgSkipMEOnStep);
if (fSkip)
{
return;
}
// See EnableJMCBackStop() for details here. This check just makes sure that we don't fire
// the assert if we end up in the method we started in (which could happen if we trace call
// instructions before the JMC probe).
// m_StepInStartMethod may be null (if this step-in didn't start from managed code).
if ((m_StepInStartMethod != pDesc) &&
(!m_StepInStartMethod->IsLCGMethod()))
{
// Since normal step-in should stop us at the prolog, and TME is after the prolog,
// if a stub-manager did successfully find the address, we should get a TriggerPatch first
// at native offset 0 (before the prolog) and before we get the TME. That means if
// we do get the TME, then there was no stub-manager to find us.
SString sLog;
StubManager::DbgGetLog(&sLog);
// Assert b/c the Stub-manager should have caught us first.
// We don't want people relying on TriggerMethodEnter as the real implementation for Traditional Step-in
// (see above for reasons why). However, using TME will provide a bandage for the final retail product
// in cases where we are missing a stub-manager.
CONSISTENCY_CHECK_MSGF(false, (
"\nThe Stubmanagers failed to identify and trace a stub on step-in. The stub-managers for this code-path path need to be fixed.\n"
"See http://team/sites/clrdev/Devdocs/StubManagers.rtf for more information on StubManagers.\n"
"Stepper this=0x%p, startMethod='%s::%s'\n"
"---------------------------------\n"
"Stub manager log:\n%S"
"\n"
"The thread is now in managed method '%s::%s'.\n"
"---------------------------------\n",
this,
((m_StepInStartMethod == NULL) ? "unknown" : m_StepInStartMethod->m_pszDebugClassName),
((m_StepInStartMethod == NULL) ? "unknown" : m_StepInStartMethod->m_pszDebugMethodName),
sLog.GetUnicode(),
pDesc->m_pszDebugClassName, pDesc->m_pszDebugMethodName
));
}
#endif
// Place a patch to stopus.
// Don't bind to a particular AppDomain so that we can do a Cross-Appdomain step.
AddBindAndActivateNativeManagedPatch(pDesc,
dji,
CodeRegionInfo::GetCodeRegionInfo(dji, pDesc).AddressToOffset(ip),
fp,
NULL // AppDomain
);
LOG((LF_CORDB, LL_INFO10000, "DJMCStepper::TME, after setting patch to stop\n"));
// Once we resume, we'll go hit that patch (duh, we patched our return address)
// Furthermore, we know the step will complete with reason = call, so set that now.
m_reason = STEP_CALL;
}
// We may have single-stepped over a return statement to land us up a frame.
// Or we may have single-stepped through a method.
// We never single-step into calls (we place a patch at the call destination).
bool DebuggerStepper::TriggerSingleStep(Thread *thread, const BYTE *ip)
{
LOG((LF_CORDB,LL_INFO10000,"DS:TSS this:0x%x, @ ip:0x%x\n", this, ip));
_ASSERTE(!IsFrozen());
// User break should only do a step-out and never actually need a singlestep flag.
_ASSERTE(GetDCType() != DEBUGGER_CONTROLLER_USER_BREAKPOINT);
//
// there's one weird case here - if the last instruction generated
// a hardware exception, we may be in lala land. If so, rely on the unwind
// handler to figure out what happened.
//
// <REVISIT_TODO>@todo this could be wrong when we have the incremental collector going</REVISIT_TODO>
//
if (!g_pEEInterface->IsManagedNativeCode(ip))
{
LOG((LF_CORDB,LL_INFO10000, "DS::TSS: not in managed code, Returning false (case 0)!\n"));
DisableSingleStep();
return false;
}
// If we EnC the method, we'll blast the function address,
// and so have to get it from teh DJI that we'll have. If
// we haven't gotten debugger info about a regular function, then
// we'll have to get the info from the EE, which will be valid
// since we're standing in the function at this point, and
// EnC couldn't have happened yet.
MethodDesc *fd = g_pEEInterface->GetNativeCodeMethodDesc((PCODE)ip);
SIZE_T offset;
DebuggerJitInfo *dji = g_pDebugger->GetJitInfoFromAddr((TADDR) ip);
offset = CodeRegionInfo::GetCodeRegionInfo(dji, fd).AddressToOffset(ip);
ControllerStackInfo info;
// Safe to stackwalk b/c we've already checked that our IP is in crawlable code.
StackTraceTicket ticket(ip);
info.GetStackInfo(ticket, GetThread(), LEAF_MOST_FRAME, NULL);
// This is a special case where we return from a managed method back to an IL stub. This can
// only happen if there's no more managed method frames closer to the root and we want to perform
// a step out, or if we step-next off the end of a method called by an IL stub. In either case,
// we'll get a single step in an IL stub, which we want to ignore. We also want to enable trace
// call here, just in case this IL stub is about to call the managed target (in the reverse interop case).
if (fd->IsILStub())
{
LOG((LF_CORDB,LL_INFO10000, "DS::TSS: not in managed code, Returning false (case 0)!\n"));
if (this->GetDCType() == DEBUGGER_CONTROLLER_STEPPER)
{
EnableTraceCall(info.m_activeFrame.fp);
}
else if (this->GetDCType() == DEBUGGER_CONTROLLER_JMC_STEPPER)
{
EnableMethodEnter();
}
DisableSingleStep();
return false;
}
DisableAll();
LOG((LF_CORDB,LL_INFO10000, "DS::TSS m_fp:0x%x, activeFP:0x%x fpExc:0x%x\n",
m_fp.GetSPValue(), info.m_activeFrame.fp.GetSPValue(), m_fpException.GetSPValue()));
if (DetectHandleLCGMethods((PCODE)ip, fd, &info))
{
return false;
}
if (IsInRange(offset, m_range, m_rangeCount, &info) ||
ShouldContinueStep( &info, offset))
{
if (!TrapStep(&info, m_stepIn))
TrapStepNext(&info);
EnableUnwind(m_fp);
LOG((LF_CORDB,LL_INFO10000, "DS::TSS: Returning false Case 1!\n"));
return false;
}
else
{
LOG((LF_CORDB,LL_INFO10000, "DS::TSS: Returning true Case 2 for reason STEP_%02x!\n", m_reason));
// @todo - when would a single-step (not a patch) land us in user-code?
// For a JMC stepper, we have an additional constraint:
// skip non-user code. So if we're still in non-user code, then
// we've got to keep going
DebuggerMethodInfo * dmi = g_pDebugger->GetOrCreateMethodInfo(fd->GetModule(), fd->GetMemberDef());
if ((dmi != NULL) && DetectHandleNonUserCode(&info, dmi))
return false;
PrepareForSendEvent(ticket);
return true;
}
}
void DebuggerStepper::TriggerTraceCall(Thread *thread, const BYTE *ip)
{
LOG((LF_CORDB,LL_INFO10000,"DS:TTC this:0x%x, @ ip:0x%x\n",this,ip));
TraceDestination trace;
if (IsFrozen())
{
LOG((LF_CORDB,LL_INFO10000,"DS:TTC exit b/c of Frozen\n"));
return;
}
// This is really just a heuristic. We don't want to trigger a JMC probe when we are
// executing in an IL stub, or in one of the marshaling methods called by the IL stub.
// The problem is that the IL stub can call into arbitrary code, including custom marshalers.
// In that case the user has to put a breakpoint to stop in the code.
if (g_pEEInterface->DetectHandleILStubs(thread))
{
return;
}
if (g_pEEInterface->TraceStub(ip, &trace)
&& g_pEEInterface->FollowTrace(&trace)
&& PatchTrace(&trace, LEAF_MOST_FRAME,
(m_rgfMappingStop&STOP_UNMANAGED)?(true):(false)))
{
// !!! We really want to know ahead of time if PatchTrace will succeed.
DisableAll();
PatchTrace(&trace, LEAF_MOST_FRAME, (m_rgfMappingStop&STOP_UNMANAGED)?
(true):(false));
// If we're triggering a trace call, and we're following a trace into either managed code or unjitted managed
// code, then we need to update our stepper's reason to STEP_CALL to reflect the fact that we're going to land
// into a new function because of a call.
if ((trace.GetTraceType() == TRACE_UNJITTED_METHOD) || (trace.GetTraceType() == TRACE_MANAGED))
{
m_reason = STEP_CALL;
}
EnableUnwind(m_fp);
LOG((LF_CORDB, LL_INFO10000, "DS::TTC potentially a step call!\n"));
}
}
void DebuggerStepper::TriggerUnwind(Thread *thread,
MethodDesc *fd, DebuggerJitInfo * pDJI, SIZE_T offset,
FramePointer fp,
CorDebugStepReason unwindReason)
{
CONTRACTL
{
SO_NOT_MAINLINE;
THROWS; // from GetJitInfo
GC_NOTRIGGER; // don't send IPC events
MODE_COOPERATIVE; // TriggerUnwind always is coop
PRECONDITION(!IsDbgHelperSpecialThread());
PRECONDITION(fd->IsDynamicMethod() || (pDJI != NULL));
}
CONTRACTL_END;
LOG((LF_CORDB,LL_INFO10000,"DS::TU this:0x%p, in %s::%s, offset 0x%p "
"frame:0x%p unwindReason:0x%x\n", this, fd->m_pszDebugClassName,
fd->m_pszDebugMethodName, offset, fp.GetSPValue(), unwindReason));
_ASSERTE(unwindReason == STEP_EXCEPTION_FILTER || unwindReason == STEP_EXCEPTION_HANDLER);
if (IsFrozen())
{
LOG((LF_CORDB,LL_INFO10000,"DS:TTC exit b/c of Frozen\n"));
return;
}
if (IsCloserToRoot(fp, GetUnwind()))
{
// Handler is in a parent frame . For all steps (in,out,over)
// we want to stop in the handler.
// This will be like a Step Out, so we don't need any range.
ResetRange();
}
else
{
// Handler/Filter is in the same frame as the stepper
// For a step-in/over, we want to patch the handler/filter.
// But for a step-out, we want to just continue executing (and don't change
// the step-reason either).
if (m_eMode == cStepOut)
{
LOG((LF_CORDB, LL_INFO10000, "DS::TU Step-out, returning for same-frame case.\n"));
return;
}
}
// Remember the origin of the exception, so that if the step looks like
// it's going to complete in a different frame, but the code comes from the
// same frame as the one we're in, we won't stop twice in the "same" range
m_fpException = fp;
m_fdException = fd;
//
// An exception is exiting the step region. Set a patch on
// the filter/handler.
//
DisableAll();
BOOL fOk;
fOk = AddBindAndActivateNativeManagedPatch(fd, pDJI, offset, LEAF_MOST_FRAME, NULL);
// Since we're unwinding to an already executed method, the method should already
// be jitted and placing the patch should work.
CONSISTENCY_CHECK_MSGF(fOk, ("Failed to place patch at TriggerUnwind.\npThis=0x%p md=0x%p, native offset=0x%x\n", this, fd, offset));
LOG((LF_CORDB,LL_INFO100000,"Step reason:%s\n", unwindReason==STEP_EXCEPTION_FILTER
? "STEP_EXCEPTION_FILTER":"STEP_EXCEPTION_HANDLER"));
m_reason = unwindReason;
}
// Prepare for sending an event.
// This is called 1:1 w/ SendEvent, but this guy can be called in a GC_TRIGGERABLE context
// whereas SendEvent is pretty strict.
// Caller ensures that it's safe to run a stack trace.
void DebuggerStepper::PrepareForSendEvent(StackTraceTicket ticket)
{
#ifdef _DEBUG
_ASSERTE(!m_fReadyToSend);
m_fReadyToSend = true;
#endif
LOG((LF_CORDB, LL_INFO10000, "DS::SE m_fpStepInto:0x%x\n", m_fpStepInto.GetSPValue()));
if (m_fpStepInto != LEAF_MOST_FRAME)
{
ControllerStackInfo csi;
csi.GetStackInfo(ticket, GetThread(), LEAF_MOST_FRAME, NULL);
if (csi.m_targetFrameFound &&
#if !defined(WIN64EXCEPTIONS)
IsCloserToRoot(m_fpStepInto, csi.m_activeFrame.fp)
#else
IsCloserToRoot(m_fpStepInto, (csi.m_activeFrame.IsNonFilterFuncletFrame() ? csi.m_returnFrame.fp : csi.m_activeFrame.fp))
#endif // WIN64EXCEPTIONS
)
{
m_reason = STEP_CALL;
LOG((LF_CORDB, LL_INFO10000, "DS::SE this:0x%x STEP_CALL!\n", this));
}
#ifdef _DEBUG
else
{
LOG((LF_CORDB, LL_INFO10000, "DS::SE this:0x%x not a step call!\n", this));
}
#endif
}
#ifdef _DEBUG
// Steppers should only stop in interesting code.
if (this->GetDCType() == DEBUGGER_CONTROLLER_JMC_STEPPER)
{
// If we're at either a patch or SS, we'll have a context.
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(GetThread());
if (context == NULL)
{
void * pIP = CORDbgGetIP(reinterpret_cast<DT_CONTEXT *>(context));
DebuggerJitInfo * dji = g_pDebugger->GetJitInfoFromAddr((TADDR) pIP);
DebuggerMethodInfo * dmi = NULL;
if (dji != NULL)
{
dmi = dji->m_methodInfo;
CONSISTENCY_CHECK_MSGF(dmi->IsJMCFunction(), ("JMC stepper %p stopping in non-jmc method, MD=%p, '%s::%s'",
this, dji->m_fd, dji->m_fd->m_pszDebugClassName, dji->m_fd->m_pszDebugMethodName));
}
}
}
#endif
}
bool DebuggerStepper::SendEvent(Thread *thread, bool fIpChanged)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
SENDEVENT_CONTRACT_ITEMS;
}
CONTRACTL_END;
// We practically should never have a step interupted by SetIp.
// We'll still go ahead and send the Step-complete event because we've already
// deactivated our triggers by now and we haven't placed any new patches to catch us.
// We assert here because we don't believe we'll ever be able to hit this scenario.
// This is technically an issue, but we consider it benign enough to leave in.
_ASSERTE(!fIpChanged || !"Stepper interupted by SetIp");
LOG((LF_CORDB, LL_INFO10000, "DS::SE m_fpStepInto:0x%x\n", m_fpStepInto.GetSPValue()));
_ASSERTE(m_fReadyToSend);
_ASSERTE(GetThread() == thread);
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(thread);
_ASSERTE(!ISREDIRECTEDTHREAD(thread));
// We need to send the stepper and delete the controller because our stepper
// no longer has any patches or other triggers that will let it send the step-complete event.
g_pDebugger->SendStep(thread, context, this, m_reason);
this->Delete();
#ifdef _DEBUG
// Now that we've sent the event, we can stop recording information.
StubManager::DbgFinishLog();
#endif
return true;
}
void DebuggerStepper::ResetRange()
{
if (m_range)
{
TRACE_FREE(m_range);
DeleteInteropSafe(m_range);
m_range = NULL;
}
}
//-----------------------------------------------------------------------------
// Return true if this stepper is alive, but frozen. (we freeze when the stepper
// enters a nested func-eval).
//-----------------------------------------------------------------------------
bool DebuggerStepper::IsFrozen()
{
return (m_cFuncEvalNesting > 0);
}
//-----------------------------------------------------------------------------
// Returns true if this stepper is 'dead' - which happens if a non-frozen stepper
// gets a func-eval exit.
//-----------------------------------------------------------------------------
bool DebuggerStepper::IsDead()
{
return (m_cFuncEvalNesting < 0);
}
// * ------------------------------------------------------------------------
// * DebuggerJMCStepper routines
// * ------------------------------------------------------------------------
DebuggerJMCStepper::DebuggerJMCStepper(Thread *thread,
CorDebugUnmappedStop rgfMappingStop,
CorDebugIntercept interceptStop,
AppDomain *appDomain) :
DebuggerStepper(thread, rgfMappingStop, interceptStop, appDomain)
{
LOG((LF_CORDB, LL_INFO10000, "DJMCStepper ctor, this=%p\n", this));
}
DebuggerJMCStepper::~DebuggerJMCStepper()
{
LOG((LF_CORDB, LL_INFO10000, "DJMCStepper dtor, this=%p\n", this));
}
// If we're a JMC stepper, then don't stop in non-user code.
bool DebuggerJMCStepper::IsInterestingFrame(FrameInfo * pFrame)
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_NOTRIGGER;
}
CONTRACTL_END;
DebuggerMethodInfo *pInfo = pFrame->GetMethodInfoFromFrameOrThrow();
_ASSERTE(pInfo != NULL); // throws on failure
bool fIsUserCode = pInfo->IsJMCFunction();
LOG((LF_CORDB, LL_INFO1000000, "DS::TSO, frame '%s::%s' is '%s' code\n",
pFrame->DbgGetClassName(), pFrame->DbgGetMethodName(),
fIsUserCode ? "user" : "non-user"));
return fIsUserCode;
}
// A JMC stepper's step-next stops at the next thing of code run.
// This may be a Step-Out, or any User code called before that.
// A1 -> B1 -> { A2, B2 -> B3 -> A3}
// So TrapStepNex at end of A2 should land us in A3.
void DebuggerJMCStepper::TrapStepNext(ControllerStackInfo *info)
{
LOG((LF_CORDB, LL_INFO10000, "DJMCStepper::TrapStepNext, this=%p\n", this));
EnableMethodEnter();
// This will place a patch up the stack and set m_reason = STEP_RETURN.
// If we end up hitting JMC before that patch, we'll hit TriggerMethodEnter
// and that will set our reason to STEP_CALL.
TrapStepOut(info);
}
// ip - target address for call instruction
bool DebuggerJMCStepper::TrapStepInHelper(
ControllerStackInfo * pInfo,
const BYTE * ipCallTarget,
const BYTE * ipNext,
bool fCallingIntoFunclet)
{
#ifndef WIN64EXCEPTIONS
// There are no funclets on x86.
_ASSERTE(!fCallingIntoFunclet);
#endif
// If we are calling into a funclet, then we can't rely on the JMC probe to stop us because there are no
// JMC probes in funclets. Instead, we have to perform a traditional step-in here.
if (fCallingIntoFunclet)
{
TraceDestination td;
td.InitForManaged(reinterpret_cast<PCODE>(ipCallTarget));
PatchTrace(&td, LEAF_MOST_FRAME, false);
// If this succeeds, then we still need to put a patch at the return address. This is done below.
// If this fails, then we definitely need to put a patch at the return address to trap the thread.
// So in either case, we have to execute the rest of this function.
}
MethodDesc * pDesc = pInfo->m_activeFrame.md;
DebuggerJitInfo *dji = NULL;
// We may not have a DJI if we're in an attach case. We should still be able to do a JMC-step in though.
// So NULL is ok here.
dji = g_pDebugger->GetJitInfo(pDesc, (const BYTE*) ipNext);
// Place patch after call, which is at ipNext. Note we don't need an IL->Native map here
// since we disassembled native code to find the ip after the call.
SIZE_T offset = CodeRegionInfo::GetCodeRegionInfo(dji, pDesc).AddressToOffset(ipNext);
LOG((LF_CORDB, LL_INFO100000, "DJMCStepper::TSIH, at '%s::%s', calling=0x%p, next=0x%p, offset=%d\n",
pDesc->m_pszDebugClassName,
pDesc->m_pszDebugMethodName,
ipCallTarget, ipNext,
offset));
// Place a patch at the native address (inside the managed method).
AddBindAndActivateNativeManagedPatch(pInfo->m_activeFrame.md,
dji,
offset,
pInfo->m_returnFrame.fp,
NULL);
EnableMethodEnter();
// Return true means that we want to let the stepper run free. It will either
// hit the patch after the call instruction or it will hit a TriggerMethodEnter.
return true;
}
// For JMC-steppers, we don't enable trace-call; we enable Method-Enter.
void DebuggerJMCStepper::EnablePolyTraceCall()
{
_ASSERTE(!IsFrozen());
this->EnableMethodEnter();
}
// Return true if this is non-user code. This means we've setup the proper patches &
// triggers, etc and so we expect the controller to just run free.
// This is called when all other stepping criteria are met and we're about to
// send a step-complete. For JMC, this is when we see if we're in non-user code
// and if so, continue stepping instead of send the step complete.
// Return false if this is user-code.
bool DebuggerJMCStepper::DetectHandleNonUserCode(ControllerStackInfo *pInfo, DebuggerMethodInfo * dmi)
{
_ASSERTE(dmi != NULL);
bool fIsUserCode = dmi->IsJMCFunction();
if (!fIsUserCode)
{
LOG((LF_CORDB, LL_INFO10000, "JMC stepper stopped in non-user code, continuing.\n"));
// Not-user code, we want to skip through this.
// We may be here while trying to step-out.
// Step-out just means stop at the first interesting frame above us.
// So JMC TrapStepOut won't patch a non-user frame.
// But if we're skipping over other stuff (prolog, epilog, interceptors,
// trace calls), then we may still be in the middle of non-user
//_ASSERTE(m_eMode != cStepOut);
if (m_eMode == cStepOut)
{
TrapStepOut(pInfo);
}
else if (m_stepIn)
{
EnableMethodEnter();
TrapStepOut(pInfo);
// Run until we hit the next thing of managed code.
} else {
// Do a traditional step-out since we just want to go up 1 frame.
TrapStepOut(pInfo, true); // force trad step out.
// If we're not in the original frame anymore, then
// If we did a Step-over at the end of a method, and that did a single-step over the return
// then we may already be in our parent frame. In that case, we also want to behave
// like a step-in and TriggerMethodEnter.
if (this->m_fp != pInfo->m_activeFrame.fp)
{
// If we're a step-over, then we should only be stopped in a parent frame.
_ASSERTE(m_stepIn || IsCloserToLeaf(this->m_fp, pInfo->m_activeFrame.fp));
EnableMethodEnter();
}
// Step-over shouldn't stop in a frame below us in the same callstack.
// So we do a tradional step-out of our current frame, which guarantees
// that. After that, we act just like a step-in.
m_stepIn = true;
}
EnableUnwind(m_fp);
// Must keep going...
return true;
}
return false;
}
// Dispatched right after the prolog of a JMC function.
// We may be blocking the GC here, so let's be fast!
void DebuggerJMCStepper::TriggerMethodEnter(Thread * thread,
DebuggerJitInfo *dji,
const BYTE * ip,
FramePointer fp)
{
_ASSERTE(dji != NULL);
_ASSERTE(thread != NULL);
_ASSERTE(ip != NULL);
_ASSERTE(!IsFrozen());
MethodDesc * pDesc = dji->m_fd;
LOG((LF_CORDB, LL_INFO10000, "DJMCStepper::TME, desc=%p, addr=%p\n",
pDesc, ip));
// JMC steppers won't stop in Lightweight delegates. Just return & keep executing.
if (pDesc->IsNoMetadata())
{
LOG((LF_CORDB, LL_INFO100000, "DJMCStepper::TME, skipping b/c it's lw-codegen\n"));
return;
}
// Is this user code?
DebuggerMethodInfo * dmi = dji->m_methodInfo;
bool fIsUserCode = dmi->IsJMCFunction();
LOG((LF_CORDB, LL_INFO100000, "DJMCStepper::TME, '%s::%s' is '%s' code\n",
pDesc->m_pszDebugClassName,
pDesc->m_pszDebugMethodName,
fIsUserCode ? "user" : "non-user"
));
// If this isn't user code, then just return and continue executing.
if (!fIsUserCode)
return;
// MethodEnter is only enabled when we want to stop in a JMC function.
// And that's where we are now. So patch the ip and resume.
// The stepper will hit the patch, and stop.
// It's a good thing we have the fp passed in, because we have no other
// way of getting it. We can't do a stack trace here (the stack trace
// would start at the last pushed Frame, which miss a lot of managed
// frames).
// Don't bind to a particular AppDomain so that we can do a Cross-Appdomain step.
AddBindAndActivateNativeManagedPatch(pDesc,
dji,
CodeRegionInfo::GetCodeRegionInfo(dji, pDesc).AddressToOffset(ip),
fp,
NULL // AppDomain
);
LOG((LF_CORDB, LL_INFO10000, "DJMCStepper::TME, after setting patch to stop\n"));
// Once we resume, we'll go hit that patch (duh, we patched our return address)
// Furthermore, we know the step will complete with reason = call, so set that now.
m_reason = STEP_CALL;
}
//-----------------------------------------------------------------------------
// Helper to convert form an EE Frame's interception enum to a CorDebugIntercept
// bitfield.
// The intercept value in EE Frame's is a 0-based enumeration (not a bitfield).
// The intercept value for ICorDebug is a bitfied.
//-----------------------------------------------------------------------------
CorDebugIntercept ConvertFrameBitsToDbg(Frame::Interception i)
{
_ASSERTE(i >= 0 && i < Frame::INTERCEPTION_COUNT);
// Since the ee frame is a 0-based enum, we can just use a map.
const CorDebugIntercept map[Frame::INTERCEPTION_COUNT] =
{
// ICorDebug EE Frame
INTERCEPT_NONE, // INTERCEPTION_NONE,
INTERCEPT_CLASS_INIT, // INTERCEPTION_CLASS_INIT
INTERCEPT_EXCEPTION_FILTER, // INTERCEPTION_EXCEPTION
INTERCEPT_CONTEXT_POLICY, // INTERCEPTION_CONTEXT
INTERCEPT_SECURITY, // INTERCEPTION_SECURITY
INTERCEPT_INTERCEPTION, // INTERCEPTION_OTHER
};
return map[i];
}
//-----------------------------------------------------------------------------
// This is a helper class to do a stack walk over a certain range and find all the interceptors.
// This allows a JMC stepper to see if there are any interceptors it wants to skip over (though
// there's nothing JMC-specific about this).
// Note that we only want to walk the stack range that the stepper is operating in.
// That's because we don't care about interceptors that happened _before_ the
// stepper was created.
//-----------------------------------------------------------------------------
class InterceptorStackInfo
{
public:
#ifdef _DEBUG
InterceptorStackInfo()
{
// since this ctor just nulls out fpTop (which is already done in Init), we
// only need it in debug.
m_fpTop = LEAF_MOST_FRAME;
}
#endif
// Get a CorDebugIntercept bitfield that contains a bit for each type of interceptor
// if that interceptor is present within our stack-range.
// Stack range is from leaf-most up to and including fp
CorDebugIntercept GetInterceptorsInRange()
{
_ASSERTE(m_fpTop != LEAF_MOST_FRAME || !"Must call Init first");
return (CorDebugIntercept) m_bits;
}
// Prime the stackwalk.
void Init(FramePointer fpTop, Thread *thread, CONTEXT *pContext, BOOL contextValid)
{
_ASSERTE(fpTop != LEAF_MOST_FRAME);
_ASSERTE(thread != NULL);
m_bits = 0;
m_fpTop = fpTop;
LOG((LF_CORDB,LL_EVERYTHING, "ISI::Init - fpTop=%p, thread=%p, pContext=%p, contextValid=%d\n",
fpTop.GetSPValue(), thread, pContext, contextValid));
int result;
result = DebuggerWalkStack(
thread,
LEAF_MOST_FRAME,
pContext,
contextValid,
WalkStack,
(void *) this,
FALSE
);
}
protected:
// This is a bitfield of all the interceptors we encounter in our stack-range
int m_bits;
// This is the top of our stack range.
FramePointer m_fpTop;
static StackWalkAction WalkStack(FrameInfo *pInfo, void *data)
{
_ASSERTE(pInfo != NULL);
_ASSERTE(data != NULL);
InterceptorStackInfo * pThis = (InterceptorStackInfo*) data;
// If there's an interceptor frame here, then set those
// bits in our bitfield.
Frame::Interception i = Frame::INTERCEPTION_NONE;
Frame * pFrame = pInfo->frame;
if ((pFrame != NULL) && (pFrame != FRAME_TOP))
{
i = pFrame->GetInterception();
if (i != Frame::INTERCEPTION_NONE)
{
pThis->m_bits |= (int) ConvertFrameBitsToDbg(i);
}
}
else if (pInfo->HasMethodFrame())
{
// Check whether we are executing in a class constructor.
_ASSERTE(pInfo->md != NULL);
// Need to be careful about an off-by-one error here! Imagine your stack looks like:
// Foo.DoSomething()
// Foo..cctor <--- step starts/ends in here
// Bar.Bar();
//
// and your code looks like this:
// Foo..cctor()
// {
// Foo.DoSomething(); <-- JMC step started here
// int x = 1; <-- step ends here
// }
// This stackwalk covers the inclusive range [Foo..cctor, Foo.DoSomething()] so we will see
// the static cctor in this walk. However executing inside a static class constructor does not
// count as an interceptor. You must start the step outside the static constructor and then call
// into it to have an interceptor. Therefore only static constructors that aren't the outermost
// frame should be treated as interceptors.
if (pInfo->md->IsClassConstructor() && (pInfo->fp != pThis->m_fpTop))
{
// We called a class constructor, add the appropriate flag
pThis->m_bits |= (int) INTERCEPT_CLASS_INIT;
}
}
LOG((LF_CORDB,LL_EVERYTHING,"ISI::WS- Frame=%p, fp=%p, Frame bits=%x, Cor bits=0x%x\n", pInfo->frame, pInfo->fp.GetSPValue(), i, pThis->m_bits));
// We can stop once we hit the top frame.
if (pInfo->fp == pThis->m_fpTop)
{
return SWA_ABORT;
}
else
{
return SWA_CONTINUE;
}
}
};
// Skip interceptors for JMC steppers.
// Return true if we patch something (and thus should keep stepping)
// Return false if we're done.
bool DebuggerJMCStepper::DetectHandleInterceptors(ControllerStackInfo * info)
{
LOG((LF_CORDB,LL_INFO10000,"DJMCStepper::DHI: Start DetectHandleInterceptors\n"));
// For JMC, we could stop very far way from an interceptor.
// So we have to do a stack walk to search for interceptors...
// If we find any in our stack range (from m_fp ... current fp), then we just do a trap-step-next.
// Note that this logic should also work for regular steppers, but we've left that in
// as to keep that code-path unchanged.
// ControllerStackInfo only gives us the bottom 2 frames on the stack, so we ignore it and
// have to do our own stack walk.
// @todo - for us to properly skip filters, we need to make sure that filters show up in our chains.
InterceptorStackInfo info2;
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(this->GetThread());
CONTEXT tempContext;
_ASSERTE(!ISREDIRECTEDTHREAD(this->GetThread()));
if (context == NULL)
{
info2.Init(this->m_fp, this->GetThread(), &tempContext, FALSE);
}
else
{
info2.Init(this->m_fp, this->GetThread(), context, TRUE);
}
// The following casts are safe on WIN64 platforms.
int iOnStack = (int) info2.GetInterceptorsInRange();
int iSkip = ~((int) m_rgfInterceptStop);
LOG((LF_CORDB,LL_INFO10000,"DJMCStepper::DHI: iOnStack=%x, iSkip=%x\n", iOnStack, iSkip));
// If the bits on the stack contain any interceptors we want to skip, then we need to keep going.
if ((iOnStack & iSkip) != 0)
{
LOG((LF_CORDB,LL_INFO10000,"DJMCStepper::DHI: keep going!\n"));
TrapStepNext(info);
EnableUnwind(m_fp);
return true;
}
LOG((LF_CORDB,LL_INFO10000,"DJMCStepper::DHI: Done!!\n"));
return false;
}
// * ------------------------------------------------------------------------
// * DebuggerThreadStarter routines
// * ------------------------------------------------------------------------
DebuggerThreadStarter::DebuggerThreadStarter(Thread *thread)
: DebuggerController(thread, NULL)
{
LOG((LF_CORDB, LL_INFO1000, "DTS::DTS: this:0x%x Thread:0x%x\n",
this, thread));
// Check to make sure we only have 1 ThreadStarter on a given thread. (Inspired by NDPWhidbey issue 16888)
#if defined(_DEBUG)
EnsureUniqueThreadStarter(this);
#endif
}
// TP_RESULT DebuggerThreadStarter::TriggerPatch() If we're in a
// stub (module==NULL&&managed) then do a PatchTrace up the stack &
// return false. Otherwise DisableAll & return
// true
TP_RESULT DebuggerThreadStarter::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
Module *module = patch->key.module;
BOOL managed = patch->IsManagedPatch();
LOG((LF_CORDB,LL_INFO1000, "DebuggerThreadStarter::TriggerPatch for thread 0x%x\n", Debugger::GetThreadIdHelper(thread)));
if (module == NULL && managed)
{
// This is a stub patch. If it was a TRACE_FRAME_PUSH that got us here, then the stub's frame is pushed now, so
// we tell the frame to apply the real patch. If we got here via a TRACE_MGR_PUSH, however, then there is no
// frame and we go back to the stub manager that generated the stub for where to patch next.
TraceDestination trace;
bool traceOk;
if (patch->trace.GetTraceType() == TRACE_MGR_PUSH)
{
BYTE *dummy = NULL;
CONTEXT *context = GetManagedLiveCtx(thread);
CONTRACT_VIOLATION(GCViolation);
traceOk = g_pEEInterface->TraceManager(thread, patch->trace.GetStubManager(), &trace, context, &dummy);
}
else if ((patch->trace.GetTraceType() == TRACE_FRAME_PUSH) && (thread->GetFrame()->IsTransitionToNativeFrame()))
{
// If we've got a frame that is transitioning to native, there's no reason to try to keep tracing. So we
// bail early and save ourselves some effort. This also works around a problem where we deadlock trying to
// do too much work to determine the destination of a ComPlusMethodFrame. (See issue 87103.)
//
// Note: trace call is still enabled, so we can just ignore this patch and wait for trace call to fire
// again...
return TPR_IGNORE;
}
else
{
// It's questionable whether Trace_Frame_Push is actually safe or not.
ControllerStackInfo csi;
StackTraceTicket ticket(patch);
csi.GetStackInfo(ticket, thread, LEAF_MOST_FRAME, NULL);
CONTRACT_VIOLATION(GCViolation); // TraceFrame GC-triggers
traceOk = g_pEEInterface->TraceFrame(thread, thread->GetFrame(), TRUE, &trace, &(csi.m_activeFrame.registers));
}
if (traceOk && g_pEEInterface->FollowTrace(&trace))
{
PatchTrace(&trace, LEAF_MOST_FRAME, TRUE);
}
return TPR_IGNORE;
}
else
{
// We've hit user code; trigger our event.
DisableAll();
{
// Give the helper thread a chance to get ready. The temporary helper can't handle
// execution control well, and the RS won't do any execution control until it gets a
// create Thread event, which it won't get until here.
// So now's our best time to wait for the real helper thread.
g_pDebugger->PollWaitingForHelper();
}
return TPR_TRIGGER;
}
}
void DebuggerThreadStarter::TriggerTraceCall(Thread *thread, const BYTE *ip)
{
LOG((LF_CORDB, LL_EVERYTHING, "DTS::TTC called\n"));
#ifdef DEBUGGING_SUPPORTED
if (thread->GetDomain()->IsDebuggerAttached())
{
TraceDestination trace;
if (g_pEEInterface->TraceStub(ip, &trace) && g_pEEInterface->FollowTrace(&trace))
{
PatchTrace(&trace, LEAF_MOST_FRAME, true);
}
}
#endif //DEBUGGING_SUPPORTED
}
bool DebuggerThreadStarter::SendEvent(Thread *thread, bool fIpChanged)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
SENDEVENT_CONTRACT_ITEMS;
}
CONTRACTL_END;
// This SendEvent can't be interupted by a SetIp because until the client
// gets a ThreadStarter event, it doesn't even know the thread exists, so
// it certainly can't change its ip.
_ASSERTE(!fIpChanged);
LOG((LF_CORDB, LL_INFO10000, "DTS::SE: in DebuggerThreadStarter's SendEvent\n"));
// Send the thread started event.
g_pDebugger->ThreadStarted(thread);
// We delete this now because its no longer needed. We can call
// delete here because the queued count is above 0. This object
// will really be deleted when its dequeued shortly after this
// call returns.
Delete();
return true;
}
// * ------------------------------------------------------------------------
// * DebuggerUserBreakpoint routines
// * ------------------------------------------------------------------------
bool DebuggerUserBreakpoint::IsFrameInDebuggerNamespace(FrameInfo * pFrame)
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_NOTRIGGER;
}
CONTRACTL_END;
// Steppers ignore internal frames, so should only be called on real frames.
_ASSERTE(pFrame->HasMethodFrame());
// Now get the namespace of the active frame
MethodDesc *pMD = pFrame->md;
if (pMD != NULL)
{
MethodTable * pMT = pMD->GetMethodTable();
LPCUTF8 szNamespace = NULL;
LPCUTF8 szClassName = pMT->GetFullyQualifiedNameInfo(&szNamespace);
if (szClassName != NULL && szNamespace != NULL)
{
MAKE_WIDEPTR_FROMUTF8(wszNamespace, szNamespace); // throw
MAKE_WIDEPTR_FROMUTF8(wszClassName, szClassName);
if (wcscmp(wszClassName, W("Debugger")) == 0 &&
wcscmp(wszNamespace, W("System.Diagnostics")) == 0)
{
// This will continue stepping
return true;
}
}
}
return false;
}
// Helper check if we're directly in a dynamic method (ignoring any chain goo
// or stuff in the Debugger namespace.
class IsLeafFrameDynamic
{
protected:
static StackWalkAction WalkStackWrapper(FrameInfo *pInfo, void *data)
{
IsLeafFrameDynamic * pThis = reinterpret_cast<IsLeafFrameDynamic*> (data);
return pThis->WalkStack(pInfo);
}
StackWalkAction WalkStack(FrameInfo *pInfo)
{
_ASSERTE(pInfo != NULL);
// A FrameInfo may have both Method + Chain rolled into one.
if (!pInfo->HasMethodFrame() && !pInfo->HasStubFrame())
{
// We're a chain. Ignore it and keep looking.
return SWA_CONTINUE;
}
// So now this is the first non-chain, non-Debugger namespace frame.
// LW frames don't have a name, so we check if it's LW first.
if (pInfo->eStubFrameType == STUBFRAME_LIGHTWEIGHT_FUNCTION)
{
m_fInLightWeightMethod = true;
return SWA_ABORT;
}
// Ignore Debugger.Break() frames.
// All Debugger.Break calls will have this on the stack.
if (DebuggerUserBreakpoint::IsFrameInDebuggerNamespace(pInfo))
{
return SWA_CONTINUE;
}
// We've now determined leafmost thing, so stop stackwalking.
_ASSERTE(m_fInLightWeightMethod == false);
return SWA_ABORT;
}
bool m_fInLightWeightMethod;
// Need this context to do stack trace.
CONTEXT m_tempContext;
public:
// On success, copies the leafmost non-chain frameinfo (including stubs) for the current thread into pInfo
// and returns true.
// On failure, returns false.
// Return true on success.
bool DoCheck(IN Thread * pThread)
{
CONTRACTL
{
GC_TRIGGERS;
THROWS;
MODE_ANY;
PRECONDITION(CheckPointer(pThread));
}
CONTRACTL_END;
m_fInLightWeightMethod = false;
DebuggerWalkStack(
pThread,
LEAF_MOST_FRAME,
&m_tempContext, false,
WalkStackWrapper,
(void *) this,
TRUE // includes everything
);
// We don't care whether the stackwalk succeeds or not because the
// callback sets our status via this field either way, so just return it.
return m_fInLightWeightMethod;
};
};
// Handle a Debug.Break() notification.
// This may create a controller to step-out out the Debug.Break() call (so that
// we appear stopped at the callsite).
// If we can't step-out (eg, we're directly in a dynamic method), then send
// the debug event immediately.
void DebuggerUserBreakpoint::HandleDebugBreak(Thread * pThread)
{
bool fDoStepOut = true;
// If the leaf frame is not a LW method, then step-out.
IsLeafFrameDynamic info;
fDoStepOut = !info.DoCheck(pThread);
if (fDoStepOut)
{
// Create a controller that will step out for us.
new (interopsafe) DebuggerUserBreakpoint(pThread);
}
else
{
// Send debug event immediately.
g_pDebugger->SendUserBreakpointAndSynchronize(pThread);
}
}
DebuggerUserBreakpoint::DebuggerUserBreakpoint(Thread *thread)
: DebuggerStepper(thread, (CorDebugUnmappedStop) (STOP_ALL & ~STOP_UNMANAGED), INTERCEPT_ALL, NULL)
{
// Setup a step out from the current frame (which we know is
// unmanaged, actually...)
// This happens to be safe, but it's a very special case (so we have a special case ticket)
// This is called while we're live (so no filter context) and from the fcall,
// and we pushed a HelperMethodFrame to protect us. We also happen to know that we have
// done anything illegal or dangerous since then.
StackTraceTicket ticket(this);
StepOut(LEAF_MOST_FRAME, ticket);
}
// Is this frame interesting?
// Use this to skip all code in the namespace "Debugger.Diagnostics"
bool DebuggerUserBreakpoint::IsInterestingFrame(FrameInfo * pFrame)
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_NOTRIGGER;
}
CONTRACTL_END;
return !IsFrameInDebuggerNamespace(pFrame);
}
bool DebuggerUserBreakpoint::SendEvent(Thread *thread, bool fIpChanged)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
SENDEVENT_CONTRACT_ITEMS;
}
CONTRACTL_END;
// See DebuggerStepper::SendEvent for why we assert here.
// This is technically an issue, but it's too benign to fix.
_ASSERTE(!fIpChanged);
LOG((LF_CORDB, LL_INFO10000,
"DUB::SE: in DebuggerUserBreakpoint's SendEvent\n"));
// Send the user breakpoint event.
g_pDebugger->SendRawUserBreakpoint(thread);
// We delete this now because its no longer needed. We can call
// delete here because the queued count is above 0. This object
// will really be deleted when its dequeued shortly after this
// call returns.
Delete();
return true;
}
// * ------------------------------------------------------------------------
// * DebuggerFuncEvalComplete routines
// * ------------------------------------------------------------------------
DebuggerFuncEvalComplete::DebuggerFuncEvalComplete(Thread *thread,
void *dest)
: DebuggerController(thread, NULL)
{
#ifdef _TARGET_ARM_
m_pDE = reinterpret_cast<DebuggerEvalBreakpointInfoSegment*>(((DWORD)dest) & ~THUMB_CODE)->m_associatedDebuggerEval;
#else
m_pDE = reinterpret_cast<DebuggerEvalBreakpointInfoSegment*>(dest)->m_associatedDebuggerEval;
#endif
// Add an unmanaged patch at the destination.
AddAndActivateNativePatchForAddress((CORDB_ADDRESS_TYPE*)dest, LEAF_MOST_FRAME, FALSE, TRACE_UNMANAGED);
}
TP_RESULT DebuggerFuncEvalComplete::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
// It had better be an unmanaged patch...
_ASSERTE((patch->key.module == NULL) && !patch->IsManagedPatch());
// set ThreadFilterContext back here because we need make stack crawlable! In case,
// GC got triggered.
// Restore the thread's context to what it was before we hijacked it for this func eval.
CONTEXT *pCtx = GetManagedLiveCtx(thread);
CORDbgCopyThreadContext(reinterpret_cast<DT_CONTEXT *>(pCtx),
reinterpret_cast<DT_CONTEXT *>(&(m_pDE->m_context)));
// We've hit our patch, so simply disable all (which removes the
// patch) and trigger the event.
DisableAll();
return TPR_TRIGGER;
}
bool DebuggerFuncEvalComplete::SendEvent(Thread *thread, bool fIpChanged)
{
CONTRACTL
{
SO_NOT_MAINLINE;
THROWS;
SENDEVENT_CONTRACT_ITEMS;
}
CONTRACTL_END;
// This should not ever be interupted by a SetIp.
// The BP will be off in random native code for which SetIp would be illegal.
// However, func-eval conroller will restore the context from when we're at the patch,
// so that will look like the IP changed on us.
_ASSERTE(fIpChanged);
LOG((LF_CORDB, LL_INFO10000, "DFEC::SE: in DebuggerFuncEval's SendEvent\n"));
_ASSERTE(!ISREDIRECTEDTHREAD(thread));
// The DebuggerEval is at our faulting address.
DebuggerEval *pDE = m_pDE;
// Send the func eval complete (or exception) event.
g_pDebugger->FuncEvalComplete(thread, pDE);
// We delete this now because its no longer needed. We can call
// delete here because the queued count is above 0. This object
// will really be deleted when its dequeued shortly after this
// call returns.
Delete();
return true;
}
#ifdef EnC_SUPPORTED
// * ------------------------------------------------------------------------ *
// * DebuggerEnCBreakpoint routines
// * ------------------------------------------------------------------------ *
//---------------------------------------------------------------------------------------
//
// DebuggerEnCBreakpoint constructor - creates and activates a new EnC breakpoint
//
// Arguments:
// offset - native offset in the function to place the patch
// jitInfo - identifies the function in which the breakpoint is being placed
// fTriggerType - breakpoint type: either REMAP_PENDING or REMAP_COMPLETE
// pAppDomain - the breakpoint applies to the specified AppDomain only
//
DebuggerEnCBreakpoint::DebuggerEnCBreakpoint(SIZE_T offset,
DebuggerJitInfo *jitInfo,
DebuggerEnCBreakpoint::TriggerType fTriggerType,
AppDomain *pAppDomain)
: DebuggerController(NULL, pAppDomain),
m_fTriggerType(fTriggerType),
m_jitInfo(jitInfo)
{
_ASSERTE( jitInfo != NULL );
// Add and activate the specified patch
AddBindAndActivateNativeManagedPatch(jitInfo->m_fd, jitInfo, offset, LEAF_MOST_FRAME, pAppDomain);
LOG((LF_ENC,LL_INFO1000, "DEnCBPDEnCBP::adding %S patch!\n",
fTriggerType == REMAP_PENDING ? W("remap pending") : W("remap complete")));
}
//---------------------------------------------------------------------------------------
//
// DebuggerEnCBreakpoint::TriggerPatch
// called by the debugging infrastructure when the patch is hit.
//
// Arguments:
// patch - specifies the patch that was hit
// thread - identifies the thread on which the patch was hit
// tyWhy - TY_SHORT_CIRCUIT for normal REMAP_PENDING EnC patches
//
// Return value:
// TPR_IGNORE if the debugger chooses not to take a remap opportunity
// TPR_IGNORE_AND_STOP when a remap-complete event is sent
// Doesn't return at all if the debugger remaps execution to the new version of the method
//
TP_RESULT DebuggerEnCBreakpoint::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
_ASSERTE(HasLock());
Module *module = patch->key.module;
mdMethodDef md = patch->key.md;
SIZE_T offset = patch->offset;
// Map the current native offset back to the IL offset in the old
// function. This will be mapped to the new native offset within
// ResumeInUpdatedFunction
CorDebugMappingResult map;
DWORD which;
SIZE_T currentIP = (SIZE_T)m_jitInfo->MapNativeOffsetToIL(offset,
&map, &which);
// We only lay DebuggerEnCBreakpoints at sequence points
_ASSERTE(map == MAPPING_EXACT);
LOG((LF_ENC, LL_ALWAYS,
"DEnCBP::TP: triggered E&C %S breakpoint: tid=0x%x, module=0x%08x, "
"method def=0x%08x, version=%d, native offset=0x%x, IL offset=0x%x\n this=0x%x\n",
m_fTriggerType == REMAP_PENDING ? W("ResumePending") : W("ResumeComplete"),
thread, module, md, m_jitInfo->m_encVersion, offset, currentIP, this));
// If this is a REMAP_COMPLETE patch, then dispatch the RemapComplete callback
if (m_fTriggerType == REMAP_COMPLETE)
{
return HandleRemapComplete(patch, thread, tyWhy);
}
// This must be a REMAP_PENDING patch
// unless we got here on an explicit short-circuit, don't do any work
if (tyWhy != TY_SHORT_CIRCUIT)
{
LOG((LF_ENC, LL_ALWAYS, "DEnCBP::TP: not short-circuit ... bailing\n"));
return TPR_IGNORE;
}
_ASSERTE(patch->IsManagedPatch());
// Grab the MethodDesc for this function.
_ASSERTE(module != NULL);
// GENERICS: @todo generics. This should be replaced by a similar loop
// over the DJIs for the DMI as in BindPatch up above.
MethodDesc *pFD = g_pEEInterface->FindLoadedMethodRefOrDef(module, md);
_ASSERTE(pFD != NULL);
LOG((LF_ENC, LL_ALWAYS,
"DEnCBP::TP: in %s::%s\n", pFD->m_pszDebugClassName,pFD->m_pszDebugMethodName));
// Grab the jit info for the original copy of the method, which is
// what we are executing right now.
DebuggerJitInfo *pJitInfo = m_jitInfo;
_ASSERTE(pJitInfo);
_ASSERTE(pJitInfo->m_fd == pFD);
// Grab the context for this thread. This is the context that was
// passed to COMPlusFrameHandler.
CONTEXT *pContext = GetManagedLiveCtx(thread);
// We use the module the current function is in.
_ASSERTE(module->IsEditAndContinueEnabled());
EditAndContinueModule *pModule = (EditAndContinueModule*)module;
// Release the controller lock for the rest of this method
CrstBase::UnsafeCrstInverseHolder inverseLock(&g_criticalSection);
// resumeIP is the native offset in the new version of the method the debugger wants
// to resume to. We'll pass the address of this variable over to the right-side
// and if it modifies the contents while we're stopped dispatching the RemapOpportunity,
// then we know it wants a remap.
// This form of side-channel communication seems like an error-prone workaround. Ideally the
// remap IP (if any) would just be returned in a response event.
SIZE_T resumeIP = (SIZE_T) -1;
// Debugging code to enable a break after N RemapOpportunities
#ifdef _DEBUG
static int breakOnRemapOpportunity = -1;
if (breakOnRemapOpportunity == -1)
breakOnRemapOpportunity = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_EnCBreakOnRemapOpportunity);
static int remapOpportunityCount = 0;
++remapOpportunityCount;
if (breakOnRemapOpportunity == 1 || breakOnRemapOpportunity == remapOpportunityCount)
{
_ASSERTE(!"BreakOnRemapOpportunity");
}
#endif
// Send an event to the RS to call the RemapOpportunity callback, passing the address of resumeIP.
// If the debugger responds with a call to RemapFunction, the supplied IP will be copied into resumeIP
// and we will know to update the context and resume the function at the new IP. Otherwise we just do
// nothing and try again on next RemapFunction breakpoint
g_pDebugger->LockAndSendEnCRemapEvent(pJitInfo, currentIP, &resumeIP);
LOG((LF_ENC, LL_ALWAYS,
"DEnCBP::TP: resume IL offset is 0x%x\n", resumeIP));
// Has the debugger requested a remap?
if (resumeIP != (SIZE_T) -1)
{
// This will jit the function, update the context, and resume execution at the new location.
g_pEEInterface->ResumeInUpdatedFunction(pModule,
pFD,
(void*)pJitInfo,
resumeIP,
pContext);
_ASSERTE(!"Returned from ResumeInUpdatedFunction!");
}
LOG((LF_CORDB, LL_ALWAYS, "DEnCB::TP: We've returned from ResumeInUpd"
"atedFunction, we're going to skip the EnC patch ####\n"));
// We're returning then we'll have to re-get this lock. Be careful that we haven't kept any controller/patches
// in the caller. They can move when we unlock, so when we release the lock and reget it here, things might have
// changed underneath us.
// inverseLock holder will reaquire lock.
return TPR_IGNORE;
}
//
// HandleResumeComplete is called for an EnC patch in the newly updated function
// so that we can notify the debugger that the remap has completed and they can
// now remap their steppers or anything else that depends on the new code actually
// being on the stack. We return TPR_IGNORE_AND_STOP because it's possible that the
// function was edited after we handled remap complete and want to make sure we
// start a fresh call to TriggerPatch
//
TP_RESULT DebuggerEnCBreakpoint::HandleRemapComplete(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
LOG((LF_ENC, LL_ALWAYS, "DEnCBP::HRC: HandleRemapComplete\n"));
// Debugging code to enable a break after N RemapCompletes
#ifdef _DEBUG
static int breakOnRemapComplete = -1;
if (breakOnRemapComplete == -1)
breakOnRemapComplete = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_EnCBreakOnRemapComplete);
static int remapCompleteCount = 0;
++remapCompleteCount;
if (breakOnRemapComplete == 1 || breakOnRemapComplete == remapCompleteCount)
{
_ASSERTE(!"BreakOnRemapComplete");
}
#endif
_ASSERTE(HasLock());
bool fApplied = m_jitInfo->m_encBreakpointsApplied;
// Need to delete this before unlock below so if any other thread come in after the unlock
// they won't handle this patch.
Delete();
// We just deleted ourselves. Can't access anything any instances after this point.
// if have somehow updated this function before we resume into it then just bail
if (fApplied)
{
LOG((LF_ENC, LL_ALWAYS, "DEnCBP::HRC: function already updated, ignoring\n"));
return TPR_IGNORE_AND_STOP;
}
// GENERICS: @todo generics. This should be replaced by a similar loop
// over the DJIs for the DMI as in BindPatch up above.
MethodDesc *pFD = g_pEEInterface->FindLoadedMethodRefOrDef(patch->key.module, patch->key.md);
LOG((LF_ENC, LL_ALWAYS, "DEnCBP::HRC: unlocking controller\n"));
// Unlock the controller lock and dispatch the remap complete event
CrstBase::UnsafeCrstInverseHolder inverseLock(&g_criticalSection);
LOG((LF_ENC, LL_ALWAYS, "DEnCBP::HRC: sending RemapCompleteEvent\n"));
g_pDebugger->LockAndSendEnCRemapCompleteEvent(pFD);
// We're returning then we'll have to re-get this lock. Be careful that we haven't kept any controller/patches
// in the caller. They can move when we unlock, so when we release the lock and reget it here, things might have
// changed underneath us.
// inverseLock holder will reacquire.
return TPR_IGNORE_AND_STOP;
}
#endif //EnC_SUPPORTED
// continuable-exceptions
// * ------------------------------------------------------------------------ *
// * DebuggerContinuableExceptionBreakpoint routines
// * ------------------------------------------------------------------------ *
//---------------------------------------------------------------------------------------
//
// constructor
//
// Arguments:
// pThread - the thread on which we are intercepting an exception
// nativeOffset - This is the target native offset. It is where we are going to resume execution.
// jitInfo - the DebuggerJitInfo of the method at which we are intercepting
// pAppDomain - the AppDomain in which the thread is executing
//
DebuggerContinuableExceptionBreakpoint::DebuggerContinuableExceptionBreakpoint(Thread *pThread,
SIZE_T nativeOffset,
DebuggerJitInfo *jitInfo,
AppDomain *pAppDomain)
: DebuggerController(pThread, pAppDomain)
{
_ASSERTE( jitInfo != NULL );
// Add a native patch at the specified native offset, which is where we are going to resume execution.
AddBindAndActivateNativeManagedPatch(jitInfo->m_fd, jitInfo, nativeOffset, LEAF_MOST_FRAME, pAppDomain);
}
//---------------------------------------------------------------------------------------
//
// This function is called when the patch added in the constructor is hit. At this point,
// we have already resumed execution, and the exception is no longer in flight.
//
// Arguments:
// patch - the patch added in the constructor; unused
// thread - the thread in question; unused
// tyWhy - a flag which is only useful for EnC; unused
//
// Return Value:
// This function always returns TPR_TRIGGER, meaning that it wants to send an event to notify the RS.
//
TP_RESULT DebuggerContinuableExceptionBreakpoint::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
LOG((LF_CORDB, LL_INFO10000, "DCEBP::TP\n"));
//
// Disable the patch
//
DisableAll();
// We will send a notification to the RS when the patch is triggered.
return TPR_TRIGGER;
}
//---------------------------------------------------------------------------------------
//
// This function is called when we want to notify the RS that an interception is complete.
// At this point, we have already resumed execution, and the exception is no longer in flight.
//
// Arguments:
// thread - the thread in question
// fIpChanged - whether the IP has changed by SetIP after the patch is hit but
// before this function is called
//
bool DebuggerContinuableExceptionBreakpoint::SendEvent(Thread *thread, bool fIpChanged)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
SENDEVENT_CONTRACT_ITEMS;
}
CONTRACTL_END;
LOG((LF_CORDB, LL_INFO10000,
"DCEBP::SE: in DebuggerContinuableExceptionBreakpoint's SendEvent\n"));
if (!fIpChanged)
{
g_pDebugger->SendInterceptExceptionComplete(thread);
}
// On WIN64, by the time we get here the DebuggerExState is gone already.
// ExceptionTrackers are cleaned up before we resume execution for a handled exception.
#if !defined(WIN64EXCEPTIONS)
thread->GetExceptionState()->GetDebuggerState()->SetDebuggerInterceptContext(NULL);
#endif // !WIN64EXCEPTIONS
//
// We delete this now because its no longer needed. We can call
// delete here because the queued count is above 0. This object
// will really be deleted when its dequeued shortly after this
// call returns.
//
Delete();
return true;
}
#endif // !DACCESS_COMPILE
|
Java
|
---
title: ເວລາສຳລັບຄວາມດຸ່ນດ່ຽງ
date: 16/12/2020
---
`ອ່ານມັດທາຍ 12:11-13 ແລະ ລູກາ 13:10-17. ຂໍ້ພຣະຄຳພີເຫຼົ່ານີ້ສະແດງໃຫ້ພວກເຮົາເຫັນວ່າ ພຣະເຢຊູໄດ້ຊົງສອນປະຊາຊົນໃນສະໄໝນັ້ນແລະໃນສະໄໝຂອງເຮົາເຖິ່ງເລື່ອງໃດ?`
ພຣະເຢຊູໄດ້ຮັກສາຄົນເຈັບປ່ວຍໃນວັນສະບາໂຕ ການອັດສະຈັນຂອງພຣະອົງໄດ້ເຮັດໃຫ້ຊາວຢິວນັ້ນເລີ່ມສົນທະນາກັນກ່ຽວກັບຄຳຖາມຝ່າຍຈິດວິນຍານທີ່ສຳຄັນ. ຄວາມບາບນັ້ນແມ່ນຫຍັງ? ແມ່ນຫຍັງຄືເຫດຜົນຫຼືຈຸດປະສົງຂອງວັນສະບາໂຕ? ພຣະເຢຊູນັ້ນຊົງທຽບເທົ່າກັບພຣະບິດາຫຼືບໍ່? ພຣະເຢຊູນັ້ນມີອຳນາດຫຼາຍຊໍ່າໃດ?
ຄວາມຮູ້ສຶກຂອງພຣະເຢຊູກ່ຽວກັບວັນສະບາໂຕນັ້ນຖືກສະແດງອອກໃນຂໍ້ຄວນຈຳສຳລັບອາທິດນີ້: “ແລ້ວພຣະເຢຊູເຈົ້າກໍກ່າວແກ່ພວກເຂົາວ່າ ວັນສະບາໂຕຖືກຕັ້ງໄວ້ເພື່ອປະໂຫຍດອັນນຳຄວາມສຸກມາສູ່ມະນຸດ ບໍ່ແມ່ນສ້າງມະນຸດໄວ້ເພື່ອວັນສະບາໂຕ. ສະນັ້ນແຫຼະ ບຸດມະນຸດຈຶ່ງເປັນອົງພຣະຜູ້ເປັນເຈົ້າເໜືອວັນສະບາໂຕ” (ມາຣະໂກ 2:27, 28). ພຣະເຢຊູຕ້ອງການທີ່ຈະສະແດງໃຫ້ເຫັນວ່າວັນສະບາໂຕບໍ່ຄວນເປັນພາລະໜັກ. ພຣະເຈົ້າ “ໄດ້ສ້າງ” ວັນສະບາໂຕ ໃຫ້ເປັນເວລາທີ່ຄົນຈະຮຽນຮູ້ກ່ຽວກັບພຣະເຈົ້າ. ທາງໜຶ່ງທີ່ພວກເຮົາຮຽນຮູ້ກ່ຽວກັບພຣະເຈົ້າໃນວັນສະບາໂຕໄດ້ນັ້ນກໍຄືໂດຍການໃຊ້ເວລາກັບທຳມະຊາດ.
`ວັນສະບາໂຕແມ່ນອັນໃດສຳລັບທ່ານ? ມັນເປັນພຽງມື້ສຳລັບການບໍ່ໃຫ້ເຮັດອັນນັ້ນ ແລະ ບໍ່ໃຫ້ເຮັດອັນນີ້ບໍ່? ຫຼື ມັນເປັນເວລາທີ່ຈະພັກຜ່ອນໃນອົງພຣະຜູ້ເປັນເຈົ້າ ແລະ ຮຽນຮູ້ພຣະອົງຫຼາຍຂຶ້ນ? ຖ້າເປັນດັ່ງນັ້ນແລ້ວ ທ່ານສາມາດປ່ຽນແປງແນວໃດ ເພື່ອວ່າທ່ານຈະສາມາດໄດ້ຮັບພຣະພອນຈາກວັນສະບາໂຕທີ່ພຣະເຈົ້າຕ້ອງການໃຫ້ທ່ານໄດ້ຮັບ?`
|
Java
|
[](https://registry.hub.docker.com/u/hopsoft/ruby-rbx/)
[](https://gratipay.com/hopsoft/)
# Trusted Docker Image for Rubinius Ruby
## Use the Trusted Image
```
sudo docker run -i -t hopsoft/ruby-rbx:2.5.3 bash
ruby -v
```
## Build the Image Manually
#### Dependencies
* [Virtual Box](https://www.virtualbox.org/)
* [Vagrant](http://www.vagrantup.com/)
```
git clone https://github.com/hopsoft/docker-ruby-rbx.git
cd docker-ruby-rbx
vagrant up
vagrant ssh
sudo docker build -t hopsoft/ruby-rbx /vagrant
```
Once the build finishes, you can [use the image](#use-the-trusted-image).
|
Java
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html><head><title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<link rel="stylesheet" type="text/css" href="search.css"/>
<script type="text/javascript" src="files_8.js"></script>
<script type="text/javascript" src="search.js"></script>
</head>
<body class="SRPage">
<div id="SRIndex">
<div class="SRStatus" id="Loading">Wczytywanie...</div>
<div id="SRResults"></div>
<script type="text/javascript"><!--
createResults();
--></script>
<div class="SRStatus" id="Searching">Szukanie...</div>
<div class="SRStatus" id="NoMatches">Brak dopasowań</div>
<script type="text/javascript"><!--
document.getElementById("Loading").style.display="none";
document.getElementById("NoMatches").style.display="none";
var searchResults = new SearchResults("searchResults");
searchResults.Search();
--></script>
</div>
</body>
</html>
|
Java
|
# Borrowed from: https://github.com/ahornung/octomap-release
# Copyright (c) 2009-2012, K. M. Wurm, A. Hornung, University of Freiburg
# 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 the University of Freiburg nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# COMPILER SETTINGS (default: Release)
# Use "-DCMAKE_BUILD_TYPE=Debug" in cmake for a Debug-build
IF(NOT CMAKE_CONFIGURATION_TYPES AND NOT CMAKE_BUILD_TYPE)
SET(CMAKE_BUILD_TYPE Release)
ENDIF(NOT CMAKE_CONFIGURATION_TYPES AND NOT CMAKE_BUILD_TYPE)
MESSAGE ("\n")
MESSAGE (STATUS "${PROJECT_NAME} building as ${CMAKE_BUILD_TYPE}")
# COMPILER FLAGS
IF (CMAKE_COMPILER_IS_GNUCC)
SET (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wno-error")
SET (CMAKE_C_FLAGS_RELEASE "-O3 -fmessage-length=0 -fno-strict-aliasing -DNDEBUG")
SET (CMAKE_C_FLAGS_DEBUG "-O0 -g3 -DTRACE=1")
SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wno-error")
SET (CMAKE_CXX_FLAGS_RELEASE "-O3 -fmessage-length=0 -fno-strict-aliasing -DNDEBUG")
SET (CMAKE_CXX_FLAGS_DEBUG "-O0 -g3 -DTRACE=1")
# Shared object compilation under 64bit (vtable)
ADD_DEFINITIONS(-fPIC)
ADD_DEFINITIONS(-DL2DBUS_MAJOR_VERSION=${L2DBUS_MAJOR_VERSION})
ADD_DEFINITIONS(-DL2DBUS_MINOR_VERSION=${L2DBUS_MINOR_VERSION})
ADD_DEFINITIONS(-DL2DBUS_RELEASE_VERSION=${L2DBUS_RELEASE_VERSION})
ENDIF()
#
# See http://www.paraview.org/Wiki/CMake_RPATH_handling for additional details
#
# Use, i.e. don't skip the full RPATH for the build tree
set(CMAKE_SKIP_BUILD_RPATH FALSE)
# When building, don't use the install RPATH already (but later on
# when installing)
set(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE)
# The RPATH to use when installing. Since it's empty the library must
# be found in a path search by other means (e.g. LD_LIBRARY_PATH, default
# library location, etc...)
set(CMAKE_INSTALL_RPATH "")
# Don't add teh automatically determined parts of the RPATH which point to
# directories outside the build tree to the install RPATH.
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH FALSE)
# no prefix needed for Lua modules
# set(CMAKE_SHARED_MODULE_PREFIX "")
|
Java
|
import * as React from "react";
import { CarbonIconProps } from "../../";
declare const Opacity24: React.ForwardRefExoticComponent<
CarbonIconProps & React.RefAttributes<SVGSVGElement>
>;
export default Opacity24;
|
Java
|
<?php
/**
* This file is part of DomainSpecificQuery
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Nicolò Martini <nicmartnic@gmail.com>
*/
namespace DSQ\Test\Compiler;
use DSQ\Compiler\CompilerChain;
use DSQ\Expression\BasicExpression;
use DSQ\Expression\Expression;
class CompilerChainTest extends \PHPUnit_Framework_TestCase
{
/**
* @param int $expectedcalls
* @return Compiler
*/
public function getCompilerMock($expectedcalls = 1)
{
$mock = $this->getMock('DSQ\Compiler\Compiler');
$mock
->expects($this->exactly($expectedcalls))
->method('compile')
->will($this->returnCallback(function(Expression $expr){
return new BasicExpression((int) $expr->getValue() + 1);
}));
return $mock;
}
public function testConstructor()
{
$chain = array($this->getMock('DSQ\Compiler\Compiler'), $this->getMock('DSQ\Compiler\Compiler'), $this->getMock('DSQ\Compiler\Compiler'));
$compiler = new CompilerChain($chain[0], $chain[1], $chain[2]);
$this->assertAttributeEquals($chain, 'chain', $compiler);
}
public function testAddCompiler()
{
$chain = array($this->getMock('DSQ\Compiler\Compiler'), $this->getMock('DSQ\Compiler\Compiler'), $this->getMock('DSQ\Compiler\Compiler'));
$compiler = new CompilerChain;
$compiler
->addCompiler($chain[0])
->addCompiler($chain[1])
->addCompiler($chain[2]);
$this->assertAttributeEquals($chain, 'chain', $compiler);
}
public function testCompile()
{
$expr = new BasicExpression(0);
$chain = new CompilerChain($this->getCompilerMock(1), $this->getCompilerMock(1), $this->getCompilerMock(1));
$compiled = $chain->compile($expr);
$this->assertEquals(3, $compiled->getValue());
}
}
|
Java
|
///
/// Copyright (c) 2016 Dropbox, Inc. All rights reserved.
///
/// Auto-generated by Stone, do not modify.
///
#import <Foundation/Foundation.h>
#import "DBSerializableProtocol.h"
@class DBTEAMLOGAdminAlertSeverityEnum;
NS_ASSUME_NONNULL_BEGIN
#pragma mark - API Object
///
/// The `AdminAlertSeverityEnum` union.
///
/// Alert severity
///
/// This class implements the `DBSerializable` protocol (serialize and
/// deserialize instance methods), which is required for all Obj-C SDK API route
/// objects.
///
@interface DBTEAMLOGAdminAlertSeverityEnum : NSObject <DBSerializable, NSCopying>
#pragma mark - Instance fields
/// The `DBTEAMLOGAdminAlertSeverityEnumTag` enum type represents the possible
/// tag states with which the `DBTEAMLOGAdminAlertSeverityEnum` union can exist.
typedef NS_CLOSED_ENUM(NSInteger, DBTEAMLOGAdminAlertSeverityEnumTag){
/// (no description).
DBTEAMLOGAdminAlertSeverityEnumHigh,
/// (no description).
DBTEAMLOGAdminAlertSeverityEnumInfo,
/// (no description).
DBTEAMLOGAdminAlertSeverityEnumLow,
/// (no description).
DBTEAMLOGAdminAlertSeverityEnumMedium,
/// (no description).
DBTEAMLOGAdminAlertSeverityEnumNa,
/// (no description).
DBTEAMLOGAdminAlertSeverityEnumOther,
};
/// Represents the union's current tag state.
@property (nonatomic, readonly) DBTEAMLOGAdminAlertSeverityEnumTag tag;
#pragma mark - Constructors
///
/// Initializes union class with tag state of "high".
///
/// @return An initialized instance.
///
- (instancetype)initWithHigh;
///
/// Initializes union class with tag state of "info".
///
/// @return An initialized instance.
///
- (instancetype)initWithInfo;
///
/// Initializes union class with tag state of "low".
///
/// @return An initialized instance.
///
- (instancetype)initWithLow;
///
/// Initializes union class with tag state of "medium".
///
/// @return An initialized instance.
///
- (instancetype)initWithMedium;
///
/// Initializes union class with tag state of "na".
///
/// @return An initialized instance.
///
- (instancetype)initWithNa;
///
/// Initializes union class with tag state of "other".
///
/// @return An initialized instance.
///
- (instancetype)initWithOther;
- (instancetype)init NS_UNAVAILABLE;
#pragma mark - Tag state methods
///
/// Retrieves whether the union's current tag state has value "high".
///
/// @return Whether the union's current tag state has value "high".
///
- (BOOL)isHigh;
///
/// Retrieves whether the union's current tag state has value "info".
///
/// @return Whether the union's current tag state has value "info".
///
- (BOOL)isInfo;
///
/// Retrieves whether the union's current tag state has value "low".
///
/// @return Whether the union's current tag state has value "low".
///
- (BOOL)isLow;
///
/// Retrieves whether the union's current tag state has value "medium".
///
/// @return Whether the union's current tag state has value "medium".
///
- (BOOL)isMedium;
///
/// Retrieves whether the union's current tag state has value "na".
///
/// @return Whether the union's current tag state has value "na".
///
- (BOOL)isNa;
///
/// Retrieves whether the union's current tag state has value "other".
///
/// @return Whether the union's current tag state has value "other".
///
- (BOOL)isOther;
///
/// Retrieves string value of union's current tag state.
///
/// @return A human-readable string representing the union's current tag state.
///
- (NSString *)tagName;
@end
#pragma mark - Serializer Object
///
/// The serialization class for the `DBTEAMLOGAdminAlertSeverityEnum` union.
///
@interface DBTEAMLOGAdminAlertSeverityEnumSerializer : NSObject
///
/// Serializes `DBTEAMLOGAdminAlertSeverityEnum` instances.
///
/// @param instance An instance of the `DBTEAMLOGAdminAlertSeverityEnum` API
/// object.
///
/// @return A json-compatible dictionary representation of the
/// `DBTEAMLOGAdminAlertSeverityEnum` API object.
///
+ (nullable NSDictionary<NSString *, id> *)serialize:(DBTEAMLOGAdminAlertSeverityEnum *)instance;
///
/// Deserializes `DBTEAMLOGAdminAlertSeverityEnum` instances.
///
/// @param dict A json-compatible dictionary representation of the
/// `DBTEAMLOGAdminAlertSeverityEnum` API object.
///
/// @return An instantiation of the `DBTEAMLOGAdminAlertSeverityEnum` object.
///
+ (DBTEAMLOGAdminAlertSeverityEnum *)deserialize:(NSDictionary<NSString *, id> *)dict;
@end
NS_ASSUME_NONNULL_END
|
Java
|
import os
import pygtk
pygtk.require('2.0')
import gtk
from gtkcodebuffer import CodeBuffer, SyntaxLoader
class Ui(object):
"""
The user interface. This dialog is the LaTeX input window and includes
widgets to display compilation logs and a preview. It uses GTK2 which
must be installed an importable.
"""
app_name = 'InkTeX'
help_text = r"""You can set a preamble file and scale factor in the <b>settings</b> tab. The preamble should not include <b>\documentclass</b> and <b>\begin{document}</b>.
The LaTeX code you write is only the stuff between <b>\begin{document}</b> and <b>\end{document}</b>. Compilation errors are reported in the <b>log</b> tab.
The preamble file and scale factor are stored on a per-drawing basis, so in a new document, these information must be set again."""
about_text = r"""Written by <a href="mailto:janoliver@oelerich.org">Jan Oliver Oelerich <janoliver@oelerich.org></a>"""
def __init__(self, render_callback, src, settings):
"""Takes the following parameters:
* render_callback: callback function to execute with "apply" button
* src: source code that should be pre-inserted into the LaTeX input"""
self.render_callback = render_callback
self.src = src if src else ""
self.settings = settings
# init the syntax highlighting buffer
lang = SyntaxLoader("latex")
self.syntax_buffer = CodeBuffer(lang=lang)
self.setup_ui()
def render(self, widget, data=None):
"""Extracts the input LaTeX code and calls the render callback. If that
returns true, we quit and are happy."""
buf = self.text.get_buffer()
tex = buf.get_text(buf.get_start_iter(), buf.get_end_iter())
settings = dict()
if self.preamble.get_filename():
settings['preamble'] = self.preamble.get_filename()
settings['scale'] = self.scale.get_value()
if self.render_callback(tex, settings):
gtk.main_quit()
return False
def cancel(self, widget, data=None):
"""Close button pressed: Exit"""
raise SystemExit(1)
def destroy(self, widget, event, data=None):
"""Destroy hook for the GTK window. Quit and return False."""
gtk.main_quit()
return False
def setup_ui(self):
"""Creates the actual UI."""
# create a floating toplevel window and set some title and border
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DIALOG)
self.window.set_title(self.app_name)
self.window.set_border_width(8)
# connect delete and destroy events
self.window.connect("destroy", self.destroy)
self.window.connect("delete-event", self.destroy)
# This is our main container, vertically ordered.
self.box_container = gtk.VBox(False, 5)
self.box_container.show()
self.notebook = gtk.Notebook()
self.page_latex = gtk.HBox(False, 5)
self.page_latex.set_border_width(8)
self.page_latex.show()
self.page_log = gtk.HBox(False, 5)
self.page_log.set_border_width(8)
self.page_log.show()
self.page_settings = gtk.HBox(False, 5)
self.page_settings.set_border_width(8)
self.page_settings.show()
self.page_help = gtk.VBox(False, 5)
self.page_help.set_border_width(8)
self.page_help.show()
self.notebook.append_page(self.page_latex, gtk.Label("LaTeX"))
self.notebook.append_page(self.page_log, gtk.Label("Log"))
self.notebook.append_page(self.page_settings, gtk.Label("Settings"))
self.notebook.append_page(self.page_help, gtk.Label("Help"))
self.notebook.show()
# First component: The input text view for the LaTeX code.
# It lives in a ScrolledWindow so we can get some scrollbars when the
# text is too long.
self.text = gtk.TextView(self.syntax_buffer)
self.text.get_buffer().set_text(self.src)
self.text.show()
self.text_container = gtk.ScrolledWindow()
self.text_container.set_policy(gtk.POLICY_AUTOMATIC,
gtk.POLICY_AUTOMATIC)
self.text_container.set_shadow_type(gtk.SHADOW_IN)
self.text_container.add(self.text)
self.text_container.set_size_request(400, 200)
self.text_container.show()
self.page_latex.pack_start(self.text_container)
# Second component: The log view
self.log_view = gtk.TextView()
self.log_view.show()
self.log_container = gtk.ScrolledWindow()
self.log_container.set_policy(gtk.POLICY_AUTOMATIC,
gtk.POLICY_AUTOMATIC)
self.log_container.set_shadow_type(gtk.SHADOW_IN)
self.log_container.add(self.log_view)
self.log_container.set_size_request(400, 200)
self.log_container.show()
self.page_log.pack_start(self.log_container)
# third component: settings
self.settings_container = gtk.Table(2,2)
self.settings_container.set_row_spacings(8)
self.settings_container.show()
self.label_preamble = gtk.Label("Preamble")
self.label_preamble.set_alignment(0, 0.5)
self.label_preamble.show()
self.preamble = gtk.FileChooserButton("...")
if 'preamble' in self.settings and os.path.exists(self.settings['preamble']):
self.preamble.set_filename(self.settings['preamble'])
self.preamble.set_action(gtk.FILE_CHOOSER_ACTION_OPEN)
self.preamble.show()
self.settings_container.attach(self.label_preamble, yoptions=gtk.SHRINK,
left_attach=0, right_attach=1, top_attach=0, bottom_attach=1)
self.settings_container.attach(self.preamble, yoptions=gtk.SHRINK,
left_attach=1, right_attach=2, top_attach=0, bottom_attach=1)
self.label_scale = gtk.Label("Scale")
self.label_scale.set_alignment(0, 0.5)
self.label_scale.show()
self.scale_adjustment = gtk.Adjustment(value=1.0, lower=0, upper=100,
step_incr=0.1)
self.scale = gtk.SpinButton(adjustment=self.scale_adjustment, digits=1)
if 'scale' in self.settings:
self.scale.set_value(float(self.settings['scale']))
self.scale.show()
self.settings_container.attach(self.label_scale, yoptions=gtk.SHRINK,
left_attach=0, right_attach=1, top_attach=1, bottom_attach=2)
self.settings_container.attach(self.scale, yoptions=gtk.SHRINK,
left_attach=1, right_attach=2, top_attach=1, bottom_attach=2)
self.page_settings.pack_start(self.settings_container)
# help tab
self.help_label = gtk.Label()
self.help_label.set_markup(Ui.help_text)
self.help_label.set_line_wrap(True)
self.help_label.show()
self.about_label = gtk.Label()
self.about_label.set_markup(Ui.about_text)
self.about_label.set_line_wrap(True)
self.about_label.show()
self.separator_help = gtk.HSeparator()
self.separator_help.show()
self.page_help.pack_start(self.help_label)
self.page_help.pack_start(self.separator_help)
self.page_help.pack_start(self.about_label)
self.box_container.pack_start(self.notebook, True, True)
# separator between buttonbar and notebook
self.separator_buttons = gtk.HSeparator()
self.separator_buttons.show()
self.box_container.pack_start(self.separator_buttons, False, False)
# the button bar
self.box_buttons = gtk.HButtonBox()
self.box_buttons.set_layout(gtk.BUTTONBOX_END)
self.box_buttons.show()
self.button_render = gtk.Button(stock=gtk.STOCK_APPLY)
self.button_cancel = gtk.Button(stock=gtk.STOCK_CLOSE)
self.button_render.set_flags(gtk.CAN_DEFAULT)
self.button_render.connect("clicked", self.render, None)
self.button_cancel.connect("clicked", self.cancel, None)
self.button_render.show()
self.button_cancel.show()
self.box_buttons.pack_end(self.button_cancel)
self.box_buttons.pack_end(self.button_render)
self.box_container.pack_start(self.box_buttons, False, False)
self.window.add(self.box_container)
self.window.set_default(self.button_render)
self.window.show()
def log(self, msg):
buffer = self.log_view.get_buffer()
buffer.set_text(msg)
self.notebook.set_current_page(1)
def main(self):
gtk.main()
|
Java
|
#Javascript Introduction/Javascript简介
JavaScript is the programming language of the Web. The overwhelming majority of modern websites use JavaScript, and all modern web browsers—on desktops, game consoles, tablets, and smart phones—include JavaScript interpreters, making Java-Script the most ubiquitous programming language in history. JavaScript is part of the triad of technologies that all Web developers must learn: HTML to specify the content of web pages, CSS to specify the presentation of web pages, and JavaScript to specify the behavior of web pages.
JavaScript是面向web的编程语言。大多数现代浏览器都在使用JavaScript,并且所有的现代web浏览器——基于pc桌面、游戏机、平板电脑和智能手机的浏览器,都包含了JavaScript解释器。这使得JavaScript成为史上应用最广泛的编程语言。JavaScript也是前端工程师必须掌握的三大技能之一:展示网页内容的HTML、描述网页样式的CSS以及描述网页行为的JavaScript。
|
Java
|
'use strict';
var convert = require('./convert'),
func = convert('findLastIndexFrom', require('../findLastIndex'));
func.placeholder = require('./placeholder');
module.exports = func;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL2NsaWVudC9saWIvbG9kYXNoL2ZwL2ZpbmRMYXN0SW5kZXhGcm9tLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsSUFBSSxVQUFVLFFBQVEsV0FBUixDQUFkO0lBQ0ksT0FBTyxRQUFRLG1CQUFSLEVBQTZCLFFBQVEsa0JBQVIsQ0FBN0IsQ0FEWDs7QUFHQSxLQUFLLFdBQUwsR0FBbUIsUUFBUSxlQUFSLENBQW5CO0FBQ0EsT0FBTyxPQUFQLEdBQWlCLElBQWpCIiwiZmlsZSI6ImZpbmRMYXN0SW5kZXhGcm9tLmpzIiwic291cmNlc0NvbnRlbnQiOlsidmFyIGNvbnZlcnQgPSByZXF1aXJlKCcuL2NvbnZlcnQnKSxcbiAgICBmdW5jID0gY29udmVydCgnZmluZExhc3RJbmRleEZyb20nLCByZXF1aXJlKCcuLi9maW5kTGFzdEluZGV4JykpO1xuXG5mdW5jLnBsYWNlaG9sZGVyID0gcmVxdWlyZSgnLi9wbGFjZWhvbGRlcicpO1xubW9kdWxlLmV4cG9ydHMgPSBmdW5jO1xuIl19
|
Java
|
<?php
/**
* Functions related to starring private messages.
*
* @package BuddyPress
* @subpackage MessagesStar
* @since 2.3.0
*/
// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;
/** UTILITY **************************************************************/
/**
* Return the starred messages slug. Defaults to 'starred'.
*
* @since 2.3.0
*
* @return string
*/
function bp_get_messages_starred_slug() {
/**
* Filters the starred message slug.
*
* @since 2.3.0
*
* @param string
*/
return sanitize_title( apply_filters( 'bp_get_messages_starred_slug', 'starred' ) );
}
/**
* Function to determine if a message ID is starred.
*
* @since 2.3.0
*
* @param int $mid The message ID. Please note that this isn't the message thread ID.
* @param int $user_id The user ID.
* @return bool
*/
function bp_messages_is_message_starred( $mid = 0, $user_id = 0 ) {
if ( empty( $user_id ) ) {
$user_id = bp_displayed_user_id();
}
if ( empty( $mid ) ) {
return false;
}
$starred = array_flip( (array) bp_messages_get_meta( $mid, 'starred_by_user', false ) );
if ( isset( $starred[$user_id] ) ) {
return true;
} else {
return false;
}
}
/**
* Output the link or raw URL for starring or unstarring a message.
*
* @since 2.3.0
*
* @param array $args See bp_get_the_message_star_action_link() for full documentation.
*/
function bp_the_message_star_action_link( $args = array() ) {
echo bp_get_the_message_star_action_link( $args );
}
/**
* Return the link or raw URL for starring or unstarring a message.
*
* @since 2.3.0
*
* @param array $args {
* Array of arguments.
* @type int $user_id The user ID. Defaults to the logged-in user ID.
* @type int $thread_id The message thread ID. Default: 0. If not zero, this takes precedence over
* $message_id.
* @type int $message_id The individual message ID. If on a single thread page, defaults to the
* current message ID in the message loop.
* @type bool $url_only Whether to return the URL only. If false, returns link with markup.
* Default: false.
* @type string $text_unstar Link text for the 'unstar' action. Only applicable if $url_only is false.
* @type string $text_star Link text for the 'star' action. Only applicable if $url_only is false.
* @type string $title_unstar Link title for the 'unstar' action. Only applicable if $url_only is false.
* @type string $title_star Link title for the 'star' action. Only applicable if $url_only is false.
* @type string $title_unstar_thread Link title for the 'unstar' action when displayed in a thread loop.
* Only applicable if $message_id is set and if $url_only is false.
* @type string $title_star_thread Link title for the 'star' action when displayed in a thread loop.
* Only applicable if $message_id is set and if $url_only is false.
* }
* @return string
*/
function bp_get_the_message_star_action_link( $args = array() ) {
// Default user ID.
$user_id = bp_displayed_user_id()
? bp_displayed_user_id()
: bp_loggedin_user_id();
$r = bp_parse_args( $args, array(
'user_id' => (int) $user_id,
'thread_id' => 0,
'message_id' => (int) bp_get_the_thread_message_id(),
'url_only' => false,
'text_unstar' => __( 'Unstar', 'buddypress' ),
'text_star' => __( 'Star', 'buddypress' ),
'title_unstar' => __( 'Starred', 'buddypress' ),
'title_star' => __( 'Not starred', 'buddypress' ),
'title_unstar_thread' => __( 'Remove all starred messages in this thread', 'buddypress' ),
'title_star_thread' => __( 'Star the first message in this thread', 'buddypress' ),
), 'messages_star_action_link' );
// Check user ID and determine base user URL.
switch ( $r['user_id'] ) {
// Current user.
case bp_loggedin_user_id() :
$user_domain = bp_loggedin_user_domain();
break;
// Displayed user.
case bp_displayed_user_id() :
$user_domain = bp_displayed_user_domain();
break;
// Empty or other.
default :
$user_domain = bp_core_get_user_domain( $r['user_id'] );
break;
}
// Bail if no user domain was calculated.
if ( empty( $user_domain ) ) {
return '';
}
// Define local variables.
$retval = $bulk_attr = '';
// Thread ID.
if ( (int) $r['thread_id'] > 0 ) {
// See if we're in the loop.
if ( bp_get_message_thread_id() == $r['thread_id'] ) {
// Grab all message ids.
$mids = wp_list_pluck( $GLOBALS['messages_template']->thread->messages, 'id' );
// Make sure order is ASC.
// Order is DESC when used in the thread loop by default.
$mids = array_reverse( $mids );
// Pull up the thread.
} else {
$thread = new BP_Messages_Thread( $r['thread_id'] );
$mids = wp_list_pluck( $thread->messages, 'id' );
}
$is_starred = false;
$message_id = 0;
foreach ( $mids as $mid ) {
// Try to find the first msg that is starred in a thread.
if ( true === bp_messages_is_message_starred( $mid ) ) {
$is_starred = true;
$message_id = $mid;
break;
}
}
// No star, so default to first message in thread.
if ( empty( $message_id ) ) {
$message_id = $mids[0];
}
$message_id = (int) $message_id;
// Nonce.
$nonce = wp_create_nonce( "bp-messages-star-{$message_id}" );
if ( true === $is_starred ) {
$action = 'unstar';
$bulk_attr = ' data-star-bulk="1"';
$retval = $user_domain . bp_get_messages_slug() . '/unstar/' . $message_id . '/' . $nonce . '/all/';
} else {
$action = 'star';
$retval = $user_domain . bp_get_messages_slug() . '/star/' . $message_id . '/' . $nonce . '/';
}
$title = $r["title_{$action}_thread"];
// Message ID.
} else {
$message_id = (int) $r['message_id'];
$is_starred = bp_messages_is_message_starred( $message_id );
$nonce = wp_create_nonce( "bp-messages-star-{$message_id}" );
if ( true === $is_starred ) {
$action = 'unstar';
$retval = $user_domain . bp_get_messages_slug() . '/unstar/' . $message_id . '/' . $nonce . '/';
} else {
$action = 'star';
$retval = $user_domain . bp_get_messages_slug() . '/star/' . $message_id . '/' . $nonce . '/';
}
$title = $r["title_{$action}"];
}
/**
* Filters the star action URL for starring / unstarring a message.
*
* @since 2.3.0
*
* @param string $retval URL for starring / unstarring a message.
* @param array $r Parsed link arguments. See $args in bp_get_the_message_star_action_link().
*/
$retval = esc_url( apply_filters( 'bp_get_the_message_star_action_urlonly', $retval, $r ) );
if ( true === (bool) $r['url_only'] ) {
return $retval;
}
/**
* Filters the star action link, including markup.
*
* @since 2.3.0
*
* @param string $retval Link for starring / unstarring a message, including markup.
* @param array $r Parsed link arguments. See $args in bp_get_the_message_star_action_link().
*/
return apply_filters( 'bp_get_the_message_star_action_link', '<a data-bp-tooltip="' . esc_attr( $title ) . '" class="bp-tooltip message-action-' . esc_attr( $action ) . '" data-star-status="' . esc_attr( $action ) .'" data-star-nonce="' . esc_attr( $nonce ) . '"' . $bulk_attr . ' data-message-id="' . esc_attr( (int) $message_id ) . '" href="' . $retval . '" role="button" aria-pressed="false"><span class="icon"></span> <span class="bp-screen-reader-text">' . $r['text_' . $action] . '</span></a>', $r );
}
/**
* Save or delete star message meta according to a message's star status.
*
* @since 2.3.0
*
* @param array $args {
* Array of arguments.
* @type string $action The star action. Either 'star' or 'unstar'. Default: 'star'.
* @type int $thread_id The message thread ID. Default: 0. If not zero, this takes precedence over
* $message_id.
* @type int $message_id The indivudal message ID to star or unstar. Default: 0.
* @type int $user_id The user ID. Defaults to the logged-in user ID.
* @type bool $bulk Whether to mark all messages in a thread as a certain action. Only relevant
* when $action is 'unstar' at the moment. Default: false.
* }
* @return bool
*/
function bp_messages_star_set_action( $args = array() ) {
$r = wp_parse_args( $args, array(
'action' => 'star',
'thread_id' => 0,
'message_id' => 0,
'user_id' => bp_displayed_user_id(),
'bulk' => false
) );
// Set thread ID.
if ( ! empty( $r['thread_id'] ) ) {
$thread_id = (int) $r['thread_id'];
} else {
$thread_id = messages_get_message_thread_id( $r['message_id'] );
}
if ( empty( $thread_id ) ) {
return false;
}
// Check if user has access to thread.
if( ! messages_check_thread_access( $thread_id, $r['user_id'] ) ) {
return false;
}
$is_starred = bp_messages_is_message_starred( $r['message_id'], $r['user_id'] );
// Star.
if ( 'star' == $r['action'] ) {
if ( true === $is_starred ) {
return true;
} else {
bp_messages_add_meta( $r['message_id'], 'starred_by_user', $r['user_id'] );
return true;
}
// Unstar.
} else {
// Unstar one message.
if ( false === $r['bulk'] ) {
if ( false === $is_starred ) {
return true;
} else {
bp_messages_delete_meta( $r['message_id'], 'starred_by_user', $r['user_id'] );
return true;
}
// Unstar all messages in a thread.
} else {
$thread = new BP_Messages_Thread( $thread_id );
$mids = wp_list_pluck( $thread->messages, 'id' );
foreach ( $mids as $mid ) {
if ( true === bp_messages_is_message_starred( $mid, $r['user_id'] ) ) {
bp_messages_delete_meta( $mid, 'starred_by_user', $r['user_id'] );
}
}
return true;
}
}
}
/** SCREENS **************************************************************/
/**
* Screen handler to display a user's "Starred" private messages page.
*
* @since 2.3.0
*/
function bp_messages_star_screen() {
add_action( 'bp_template_content', 'bp_messages_star_content' );
/**
* Fires right before the loading of the "Starred" messages box.
*
* @since 2.3.0
*/
do_action( 'bp_messages_screen_star' );
bp_core_load_template( 'members/single/plugins' );
}
/**
* Screen content callback to display a user's "Starred" messages page.
*
* @since 2.3.0
*/
function bp_messages_star_content() {
// Add our message thread filter.
add_filter( 'bp_after_has_message_threads_parse_args', 'bp_messages_filter_starred_message_threads' );
// Load the message loop template part.
bp_get_template_part( 'members/single/messages/messages-loop' );
// Remove our filter.
remove_filter( 'bp_after_has_message_threads_parse_args', 'bp_messages_filter_starred_message_threads' );
}
/**
* Filter message threads by those starred by the logged-in user.
*
* @since 2.3.0
*
* @param array $r Current message thread arguments.
* @return array $r Array of starred message threads.
*/
function bp_messages_filter_starred_message_threads( $r = array() ) {
$r['box'] = 'starred';
$r['meta_query'] = array( array(
'key' => 'starred_by_user',
'value' => $r['user_id']
) );
return $r;
}
/** ACTIONS **************************************************************/
/**
* Action handler to set a message's star status for those not using JS.
*
* @since 2.3.0
*/
function bp_messages_star_action_handler() {
if ( ! bp_is_user_messages() ) {
return;
}
if ( false === ( bp_is_current_action( 'unstar' ) || bp_is_current_action( 'star' ) ) ) {
return;
}
if ( ! wp_verify_nonce( bp_action_variable( 1 ), 'bp-messages-star-' . bp_action_variable( 0 ) ) ) {
wp_die( "Oops! That's a no-no!" );
}
// Check capability.
if ( ! is_user_logged_in() || ! bp_core_can_edit_settings() ) {
return;
}
// Mark the star.
bp_messages_star_set_action( array(
'action' => bp_current_action(),
'message_id' => bp_action_variable(),
'bulk' => (bool) bp_action_variable( 2 )
) );
// Redirect back to previous screen.
$redirect = wp_get_referer() ? wp_get_referer() : bp_displayed_user_domain() . bp_get_messages_slug();
bp_core_redirect( $redirect );
die();
}
add_action( 'bp_actions', 'bp_messages_star_action_handler' );
/**
* Bulk manage handler to set the star status for multiple messages.
*
* @since 2.3.0
*/
function bp_messages_star_bulk_manage_handler() {
if ( empty( $_POST['messages_bulk_nonce' ] ) ) {
return;
}
// Check the nonce.
if ( ! wp_verify_nonce( $_POST['messages_bulk_nonce'], 'messages_bulk_nonce' ) ) {
return;
}
// Check capability.
if ( ! is_user_logged_in() || ! bp_core_can_edit_settings() ) {
return;
}
$action = ! empty( $_POST['messages_bulk_action'] ) ? $_POST['messages_bulk_action'] : '';
$threads = ! empty( $_POST['message_ids'] ) ? $_POST['message_ids'] : '';
$threads = wp_parse_id_list( $threads );
// Bail if action doesn't match our star actions or no IDs.
if ( false === in_array( $action, array( 'star', 'unstar' ), true ) || empty( $threads ) ) {
return;
}
// It's star time!
switch ( $action ) {
case 'star' :
$count = count( $threads );
// If we're starring a thread, we only star the first message in the thread.
foreach ( $threads as $thread ) {
$thread = new BP_Messages_thread( $thread );
$mids = wp_list_pluck( $thread->messages, 'id' );
bp_messages_star_set_action( array(
'action' => 'star',
'message_id' => $mids[0],
) );
}
bp_core_add_message( sprintf( _n( '%s message was successfully starred', '%s messages were successfully starred', $count, 'buddypress' ), $count ) );
break;
case 'unstar' :
$count = count( $threads );
foreach ( $threads as $thread ) {
bp_messages_star_set_action( array(
'action' => 'unstar',
'thread_id' => $thread,
'bulk' => true
) );
}
bp_core_add_message( sprintf( _n( '%s message was successfully unstarred', '%s messages were successfully unstarred', $count, 'buddypress' ), $count ) );
break;
}
// Redirect back to message box.
bp_core_redirect( bp_displayed_user_domain() . bp_get_messages_slug() . '/' . bp_current_action() . '/' );
die();
}
add_action( 'bp_actions', 'bp_messages_star_bulk_manage_handler', 5 );
/** HOOKS ****************************************************************/
/**
* Enqueues the dashicons font.
*
* The dashicons font is used for the star / unstar icon.
*
* @since 2.3.0
*/
function bp_messages_star_enqueue_scripts() {
if ( ! bp_is_user_messages() ) {
return;
}
wp_enqueue_style( 'dashicons' );
}
add_action( 'bp_enqueue_scripts', 'bp_messages_star_enqueue_scripts' );
/**
* Add the "Add star" and "Remove star" options to the bulk management list.
*
* @since 2.3.0
*/
function bp_messages_star_bulk_management_dropdown() {
?>
<option value="star"><?php _e( 'Add star', 'buddypress' ); ?></option>
<option value="unstar"><?php _e( 'Remove star', 'buddypress' ); ?></option>
<?php
}
add_action( 'bp_messages_bulk_management_dropdown', 'bp_messages_star_bulk_management_dropdown', 1 );
/**
* Add CSS class for the current message depending on starred status.
*
* @since 2.3.0
*
* @param array $retval Current CSS classes.
* @return array
*/
function bp_messages_star_message_css_class( $retval = array() ) {
if ( true === bp_messages_is_message_starred( bp_get_the_thread_message_id() ) ) {
$status = 'starred';
} else {
$status = 'not-starred';
}
// Add css class based on star status for the current message.
$retval[] = "message-{$status}";
return $retval;
}
add_filter( 'bp_get_the_thread_message_css_class', 'bp_messages_star_message_css_class' );
|
Java
|
<!doctype html>
<html>
<head>
<title>Radian to degree</title>
<script src="/require.js"></script>
<!-- ATTENTION: Remove in non-test code -->
<script src="/requireconfig.js"></script>
</head>
<body>
</body>
</html>
|
Java
|
<?php
namespace Illuminate\Cache;
use Closure;
use Exception;
use Carbon\Carbon;
use Illuminate\Contracts\Cache\Store;
use Illuminate\Database\ConnectionInterface;
class DatabaseStore implements Store
{
use RetrievesMultipleKeys;
/**
* The database connection instance.
*
* @var \Illuminate\Database\ConnectionInterface
*/
protected $connection;
/**
* The name of the cache table.
*
* @var string
*/
protected $table;
/**
* A string that should be prepended to keys.
*
* @var string
*/
protected $prefix;
/**
* Create a new database store.
*
* @param \Illuminate\Database\ConnectionInterface $connection
* @param string $table
* @param string $prefix
* @return void
*/
public function __construct(ConnectionInterface $connection, $table, $prefix = '')
{
$this->table = $table;
$this->prefix = $prefix;
$this->connection = $connection;
}
/**
* Retrieve an item from the cache by key.
*
* @param string|array $key
* @return mixed
*/
public function get($key)
{
$prefixed = $this->prefix.$key;
$cache = $this->table()->where('key', '=', $prefixed)->first();
// If we have a cache record we will check the expiration time against current
// time on the system and see if the record has expired. If it has, we will
// remove the records from the database table so it isn't returned again.
if (is_null($cache)) {
return;
}
$cache = is_array($cache) ? (object) $cache : $cache;
// If this cache expiration date is past the current time, we will remove this
// item from the cache. Then we will return a null value since the cache is
// expired. We will use "Carbon" to make this comparison with the column.
if (Carbon::now()->getTimestamp() >= $cache->expiration) {
$this->forget($key);
return;
}
return unserialize($cache->value);
}
/**
* Store an item in the cache for a given number of minutes.
*
* @param string $key
* @param mixed $value
* @param float|int $minutes
* @return void
*/
public function put($key, $value, $minutes)
{
$key = $this->prefix.$key;
$value = serialize($value);
$expiration = $this->getTime() + (int) ($minutes * 60);
try {
$this->table()->insert(compact('key', 'value', 'expiration'));
} catch (Exception $e) {
$this->table()->where('key', $key)->update(compact('value', 'expiration'));
}
}
/**
* Increment the value of an item in the cache.
*
* @param string $key
* @param mixed $value
* @return int|bool
*/
public function increment($key, $value = 1)
{
return $this->incrementOrDecrement($key, $value, function ($current, $value) {
return $current + $value;
});
}
/**
* Decrement the value of an item in the cache.
*
* @param string $key
* @param mixed $value
* @return int|bool
*/
public function decrement($key, $value = 1)
{
return $this->incrementOrDecrement($key, $value, function ($current, $value) {
return $current - $value;
});
}
/**
* Increment or decrement an item in the cache.
*
* @param string $key
* @param mixed $value
* @param \Closure $callback
* @return int|bool
*/
protected function incrementOrDecrement($key, $value, Closure $callback)
{
return $this->connection->transaction(function () use ($key, $value, $callback) {
$prefixed = $this->prefix.$key;
$cache = $this->table()->where('key', $prefixed)
->lockForUpdate()->first();
// If there is no value in the cache, we will return false here. Otherwise the
// value will be decrypted and we will proceed with this function to either
// increment or decrement this value based on the given action callbacks.
if (is_null($cache)) {
return false;
}
$cache = is_array($cache) ? (object) $cache : $cache;
$current = unserialize($cache->value);
// Here we'll call this callback function that was given to the function which
// is used to either increment or decrement the function. We use a callback
// so we do not have to recreate all this logic in each of the functions.
$new = $callback((int) $current, $value);
if (! is_numeric($current)) {
return false;
}
// Here we will update the values in the table. We will also encrypt the value
// since database cache values are encrypted by default with secure storage
// that can't be easily read. We will return the new value after storing.
$this->table()->where('key', $prefixed)->update([
'value' => serialize($new),
]);
return $new;
});
}
/**
* Get the current system time.
*
* @return int
*/
protected function getTime()
{
return Carbon::now()->getTimestamp();
}
/**
* Store an item in the cache indefinitely.
*
* @param string $key
* @param mixed $value
* @return void
*/
public function forever($key, $value)
{
$this->put($key, $value, 5256000);
}
/**
* Remove an item from the cache.
*
* @param string $key
* @return bool
*/
public function forget($key)
{
$this->table()->where('key', '=', $this->prefix.$key)->delete();
return true;
}
/**
* Remove all items from the cache.
*
* @return bool
*/
public function flush()
{
return (bool) $this->table()->delete();
}
/**
* Get a query builder for the cache table.
*
* @return \Illuminate\Database\Query\Builder
*/
protected function table()
{
return $this->connection->table($this->table);
}
/**
* Get the underlying database connection.
*
* @return \Illuminate\Database\ConnectionInterface
*/
public function getConnection()
{
return $this->connection;
}
/**
* Get the cache key prefix.
*
* @return string
*/
public function getPrefix()
{
return $this->prefix;
}
}
|
Java
|
package net.sf.esfinge.metadata.validate.minValue;
|
Java
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* Person object.
*
*/
class PersonResult {
/**
* Create a PersonResult.
* @member {string} personId personId of the target face list.
* @member {array} [persistedFaceIds] persistedFaceIds of registered faces in
* the person. These persistedFaceIds are returned from Person - Add a Person
* Face, and will not expire.
* @member {string} [name] Person's display name.
* @member {string} [userData] User-provided data attached to this person.
*/
constructor() {
}
/**
* Defines the metadata of PersonResult
*
* @returns {object} metadata of PersonResult
*
*/
mapper() {
return {
required: false,
serializedName: 'PersonResult',
type: {
name: 'Composite',
className: 'PersonResult',
modelProperties: {
personId: {
required: true,
serializedName: 'personId',
type: {
name: 'String'
}
},
persistedFaceIds: {
required: false,
serializedName: 'persistedFaceIds',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
name: {
required: false,
serializedName: 'name',
type: {
name: 'String'
}
},
userData: {
required: false,
serializedName: 'userData',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = PersonResult;
|
Java
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Test;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpKernel\HttpKernelInterface;
/**
* WebTestCase is the base class for functional tests.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
abstract class WebTestCase extends \PHPUnit_Framework_TestCase
{
protected static $class;
protected static $kernel;
/**
* Creates a Client.
*
* @param array $options An array of options to pass to the createKernel class
* @param array $server An array of server parameters
*
* @return Client A Client instance
*/
protected static function createClient(array $options = array(), array $server = array())
{
if (null !== static::$kernel) {
static::$kernel->shutdown();
}
static::$kernel = static::createKernel($options);
static::$kernel->boot();
$client = static::$kernel->getContainer()->get('test.client');
$client->setServerParameters($server);
return $client;
}
/**
* Finds the directory where the phpunit.xml(.dist) is stored.
*
* If you run tests with the PHPUnit CLI tool, everything will work as expected.
* If not, override this method in your test classes.
*
* @return string The directory where phpunit.xml(.dist) is stored
*/
protected static function getPhpUnitXmlDir()
{
if (!isset($_SERVER['argv']) || false === strpos($_SERVER['argv'][0], 'phpunit')) {
throw new \RuntimeException('You must override the WebTestCase::createKernel() method.');
}
$dir = static::getPhpUnitCliConfigArgument();
if ($dir === null &&
(is_file(getcwd().DIRECTORY_SEPARATOR.'phpunit.xml') ||
is_file(getcwd().DIRECTORY_SEPARATOR.'phpunit.xml.dist'))) {
$dir = getcwd();
}
// Can't continue
if ($dir === null) {
throw new \RuntimeException('Unable to guess the Kernel directory.');
}
if (!is_dir($dir)) {
$dir = dirname($dir);
}
return $dir;
}
/**
* Finds the value of configuration flag from cli
*
* PHPUnit will use the last configuration argument on the command line, so this only returns
* the last configuration argument
*
* @return string The value of the phpunit cli configuration option
*/
private static function getPhpUnitCliConfigArgument()
{
$dir = null;
$reversedArgs = array_reverse($_SERVER['argv']);
foreach ($reversedArgs as $argIndex => $testArg) {
if ($testArg === '-c' || $testArg === '--configuration') {
$dir = realpath($reversedArgs[$argIndex - 1]);
break;
} elseif (strpos($testArg, '--configuration=') === 0) {
$argPath = substr($testArg, strlen('--configuration='));
$dir = realpath($argPath);
break;
}
}
return $dir;
}
/**
* Attempts to guess the kernel location.
*
* When the Kernel is located, the file is required.
*
* @return string The Kernel class name
*/
protected static function getKernelClass()
{
$dir = isset($_SERVER['KERNEL_DIR']) ? $_SERVER['KERNEL_DIR'] : static::getPhpUnitXmlDir();
$finder = new Finder();
$finder->name('*Kernel.php')->depth(0)->in($dir);
$results = iterator_to_array($finder);
if (!count($results)) {
throw new \RuntimeException('Either set KERNEL_DIR in your phpunit.xml according to http://symfony.com/doc/current/book/testing.html#your-first-functional-test or override the WebTestCase::createKernel() method.');
}
$file = current($results);
$class = $file->getBasename('.php');
require_once $file;
return $class;
}
/**
* Creates a Kernel.
*
* Available options:
*
* * environment
* * debug
*
* @param array $options An array of options
*
* @return HttpKernelInterface A HttpKernelInterface instance
*/
protected static function createKernel(array $options = array())
{
if (null === static::$class) {
static::$class = static::getKernelClass();
}
return new static::$class(
isset($options['environment']) ? $options['environment'] : 'test',
isset($options['debug']) ? $options['debug'] : true
);
}
/**
* Shuts the kernel down if it was used in the test.
*/
protected function tearDown()
{
if (null !== static::$kernel) {
static::$kernel->shutdown();
}
}
}
|
Java
|
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Ical.Net.DataTypes;
namespace Ical.Net.Serialization.DataTypes
{
public class RequestStatusSerializer : StringSerializer
{
public RequestStatusSerializer() { }
public RequestStatusSerializer(SerializationContext ctx) : base(ctx) { }
public override Type TargetType => typeof (RequestStatus);
public override string SerializeToString(object obj)
{
try
{
var rs = obj as RequestStatus;
if (rs == null)
{
return null;
}
// Push the object onto the serialization stack
SerializationContext.Push(rs);
try
{
var factory = GetService<ISerializerFactory>();
var serializer = factory?.Build(typeof (StatusCode), SerializationContext) as IStringSerializer;
if (serializer == null)
{
return null;
}
var builder = new StringBuilder();
builder.Append(Escape(serializer.SerializeToString(rs.StatusCode)));
builder.Append(";");
builder.Append(Escape(rs.Description));
if (!string.IsNullOrWhiteSpace(rs.ExtraData))
{
builder.Append(";");
builder.Append(Escape(rs.ExtraData));
}
return Encode(rs, builder.ToString());
}
finally
{
// Pop the object off the serialization stack
SerializationContext.Pop();
}
}
catch
{
return null;
}
}
internal static readonly Regex NarrowRequestMatch = new Regex(@"(.*?[^\\]);(.*?[^\\]);(.+)", RegexOptions.Compiled);
internal static readonly Regex BroadRequestMatch = new Regex(@"(.*?[^\\]);(.+)", RegexOptions.Compiled);
public override object Deserialize(TextReader tr)
{
var value = tr.ReadToEnd();
var rs = CreateAndAssociate() as RequestStatus;
if (rs == null)
{
return null;
}
// Decode the value as needed
value = Decode(rs, value);
// Push the object onto the serialization stack
SerializationContext.Push(rs);
try
{
var factory = GetService<ISerializerFactory>();
if (factory == null)
{
return null;
}
var match = NarrowRequestMatch.Match(value);
if (!match.Success)
{
match = BroadRequestMatch.Match(value);
}
if (match.Success)
{
var serializer = factory.Build(typeof(StatusCode), SerializationContext) as IStringSerializer;
if (serializer == null)
{
return null;
}
rs.StatusCode = serializer.Deserialize(new StringReader(Unescape(match.Groups[1].Value))) as StatusCode;
rs.Description = Unescape(match.Groups[2].Value);
if (match.Groups.Count == 4)
{
rs.ExtraData = Unescape(match.Groups[3].Value);
}
return rs;
}
}
finally
{
// Pop the object off the serialization stack
SerializationContext.Pop();
}
return null;
}
}
}
|
Java
|
# angucomplete-alt contributors (sorted alphabeticaly)
---
### [@alexbeletsky: Alexander Beletsky](https://github.com/alexbeletsky)
* Publish to NPM #111, #121
### [@alindber: Andy Lindberg](https://github.com/alindber)
* Required support #23
* Auto match #29
### [@andretw: Andre Lee](https://github.com/andretw)
* Bug fix #109
### [@annmirosh](https://github.com/annmirosh)
* Fix input event for mobile device #232 #178
### [@antony: Antony Jones](https://github.com/antony)
* Allow the user to set an initial value OBJECT instead of just a string #173
* Documentation update #180
### [@baloo2401](https://github.com/baloo2401)
* display-searching and display-no-result #129
### [@boshen](https://github.com/Boshen)
* Collaborator and excellent developer
* Add autocapitalize="off" autocorrect="off" autocomplete="off" #15
### [@davidgeary: David Geary](https://github.com/davidgeary)
* Missing 'type' field on input element when not specified #167
### [@Freezystem: Nico](https://github.com/Freezystem)
* Add focus-first #92 #242
### [@handiwijoyo: Handi Wijoyo](https://github.com/handiwijoyo)
* Add css to bower.json main #68
### [@iamgurdip](https://github.com/iamgurdip)
* Escape regular expression #123
### [@jbuquet: Javier Buquet](https://github.com/jbuquet)
* Add custom API handler #128
### [@jermspeaks: Jeremy Wong](https://github.com/jermspeaks)
* Support withCredentials for $http #113
### [@Leocrest](https://github.com/Leocrest)
* Clear input #61
### [@mcnocopo: Pachito Marco Calabrese](https://github.com/mcnocopo)
* Add input name and a not-empty class #124
### [@mmBs](https://github.com/mmBs)
* Add type attribute #96
### [@mrdevin: David Hartman](https://github.com/mrdevin)
* Set the form field to valid when the initialValue is added #59
### [@nekcih](https://github.com/nekcih)
* New callback handler, response translator, better template code format, and css fix #6
* Fixed support for IE8 #13
### [@peterjkirby: Peter Kirby](https://github.com/peterjkirby)
* Bug fix #97
### [@sdbondi: Stan Bondi](https://github.com/sdbondi)
* Custom template #74
### [@SpaceK33z: Kees Kluskens](https://github.com/SpaceK33z)
* Bug fix #62
### [@termleech](https://github.com/termleech)
* Add maxlength #136
### [@tomgutz: Tomas Gutierrez](https://github.com/tomgutz)
* Added delete keystroke together with backspace #4
### [@tuduong2](https://github.com/tuduong2)
* Encode search parameter #119
### [@urecio](https://github.com/urecio)
* Added input changed callback #12
### [@vhuerta: Victor Huerta Hernández](https://github.com/vhuerta)
* Custom strings for "searching" and "no results" #22
### [@YasuhiroYoshida: Yasuhiro Yoshida](https://github.com/YasuhiroYoshida)
* Fix pressing enter without selecting an item results in "No results found" message #31
* Implement 'update input field' #42
|
Java
|
<?php return array(
//Use the below link to get the parameters to be passed.
//http://www.tig12.net/downloads/apidocs/wp/wp-includes/PHPMailer.class.html#det_fields_to
"type"=>array(
// Sets Mailer to send message using PHP mail() function. (true, false)
"IsMail"=>false,
// Sets Mailer to send message using SMTP. If set to true, other options are also available. (true, false )
"IsSMTP"=>true,
// Sets Mailer to send message using the Sendmail program. (true, false)
"IsSendmail"=>false,
// Sets Mailer to send message using the qmail MTA. (true, false )
"IsQmail"=>false
),
"smtp"=>array(
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
"SMTPDebug" => 0,
//Ask for HTML-friendly debug output
"Debugoutput" => 'html',
//Set the hostname of the mail server
"Host" => 'smtp.gmail.com',
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
"Port" => 587,
//Set the encryption system to use - ssl (deprecated) or tls
"SMTPSecure" => 'tls',
//Whether to use SMTP authentication
"SMTPAuth" => true,
//Username to use for SMTP authentication - use full email address for gmail
"Username" => "",
//Password to use for SMTP authentication
"Password" => "",
//Set who the message is to be sent from
"From" =>"",
//Set Name of the sender
"FromName"=>""
),
//Authenticate via POP3 (true, false)
//Now you should be clear to submit messages over SMTP for a while
//Only applies if your host supports POP-before-SMTP
"pop"=>array(false,"'pop3.example.com', 110, 30, 'username', 'password', 1")
);
|
Java
|
<?php
namespace Oro\Bundle\ApiBundle\Tests\Unit\Processor;
use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\Form\Extension\Validator\ValidatorExtension;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormExtensionInterface;
use Symfony\Component\Form\Forms;
use Symfony\Component\Validator\Validation;
use Oro\Bundle\ApiBundle\Config\EntityDefinitionConfigExtra;
use Oro\Bundle\ApiBundle\Processor\FormContext;
use Oro\Bundle\ApiBundle\Processor\SingleItemContext;
use Oro\Bundle\ApiBundle\Request\RequestType;
class FormProcessorTestCase extends \PHPUnit_Framework_TestCase
{
const TEST_VERSION = '1.1';
const TEST_REQUEST_TYPE = RequestType::REST;
/** @var FormContext|SingleItemContext */
protected $context;
/** @var \PHPUnit_Framework_MockObject_MockObject */
protected $configProvider;
/** @var \PHPUnit_Framework_MockObject_MockObject */
protected $metadataProvider;
protected function setUp()
{
$this->configProvider = $this->getMockBuilder('Oro\Bundle\ApiBundle\Provider\ConfigProvider')
->disableOriginalConstructor()
->getMock();
$this->metadataProvider = $this->getMockBuilder('Oro\Bundle\ApiBundle\Provider\MetadataProvider')
->disableOriginalConstructor()
->getMock();
$this->context = $this->createContext();
$this->context->setVersion(self::TEST_VERSION);
$this->context->getRequestType()->add(self::TEST_REQUEST_TYPE);
$this->context->setConfigExtras(
[
new EntityDefinitionConfigExtra($this->context->getAction())
]
);
}
/**
* @return FormContext
*/
protected function createContext()
{
return new FormContextStub($this->configProvider, $this->metadataProvider);
}
/**
* @param FormExtensionInterface[] $extensions
*
* @return FormBuilder
*/
protected function createFormBuilder(array $extensions = [])
{
$formFactory = Forms::createFormFactoryBuilder()
->addExtensions(array_merge($this->getFormExtensions(), $extensions))
->getFormFactory();
$dispatcher = $this->createMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
return new FormBuilder(null, null, $dispatcher, $formFactory);
}
/**
* @return FormExtensionInterface[]
*/
protected function getFormExtensions()
{
$validator = Validation::createValidatorBuilder()
->enableAnnotationMapping(new AnnotationReader())
->getValidator();
return [new ValidatorExtension($validator)];
}
}
|
Java
|
# How to write your own technology
Starting with ENB version 0.8, we recommend using the `BuildFlow` helper for writing technologies.
[The helper source code](https://github.com/enb/enb/blob/master/lib/build-flow.js)
This guide doesn't cover all `BuildFlow` features. For a complete list of methods with descriptions, see the JSDoc file `build-flow.js`.
## Theory
A technology is aimed at building a [target](../../terms/terms.en.md) in the node. For example, the `css` technology can build `index.css` in the `pages/index` node from the `css` files for the [redefinition levels](https://en.beta.bem.info/methodology/key-concepts/#redefinition-level).
Each technology can accept settings.
The `BuildFlow` helper ensures that the maximum number of parameters is customizable.
Technologies can use the result of other technologies. For example, the list of source `css` files is built using the `files` technology.
## Technology for combining files by suffix
In general, the technology for combining files with a certain suffix looks like this:
```javascript
module.exports = require('enb/lib/build-flow').create() // Creates a BuildFlow instance
.name('js') // Choose the technology name
.target('target', '?.js') // Name of the option that sets the name for the output file and the default value
.useFileList('js') // Specify the suffixes for the build
.justJoinFilesWithComments() // One more helper. Joins the result and wraps it in /* ... */ comments
// The comments contain the path to the file from which the fragment was formed.
.createTech(); // Creates the technology with the helper
```
Consider a similar technology that doesn't use `justJoinFilesWithComments`:
```javascript
var Vow = require('vow'); // Promise library used in ENB
var vowFs = require('vow-fs'); // Using Vow to work with file system
module.exports = require('enb/lib/build-flow').create()
.name('js')
.target('target', '?.js')
.useFileList('js')
.builder(function(jsFiles) { // Returns the promise for ENB to wait until the asynchronous technology is executed
var node = this.node; // Saves the link to the `Node` class instance.
return Vow.all(jsFiles.map(function(file) { // Waits until the promises are resolved
return vowFs.read(file.fullname, 'utf8').then(function(data) { // Reads each source file
var filename = node.relativePath(file.fullname); // Receives the path from the node
// Builds fragments from the source file content
return '/* begin: ' + filename + ' *' + '/\n' + data + '\n/* end: ' + filename + ' *' + '/';
});
})).then(function(contents) { // Received the result of processing all source files
return contents.join('\n'); // Joins the received fragments using the line feed
});
})
.createTech();
```
Since we used the `useFileList` method, the `builder` received an argument with a list of files for the specified suffix.
Each `use` method adds an argument to the `builder`. The type and content of the arguments depend on which `use` method is used.
Let's add internationalization files to the resulting technology:
```javascript
var Vow = require('vow'); // The promise library used in ENB
var vowFs = require('vow-fs'); // Using Vow to work with the file system
module.exports = require('enb/lib/build-flow').create()
.name('js')
.target('target', '?.js')
.defineRequiredOption('lang') // Defines the required 'lang' option to set the language
.useFileList('js')
.useSourceText('allLangTarget', '?.lang.all.js') // Connects internationalization common for all languages,
// using the useSourceText, that adds the content of the specified source file
// to the builder as an argument
.useSourceText('langTarget', '?.lang.{lang}.js') // Connects the keysets of the specified language;
// here the lang option value is used to
// form the default value
.builder(function(jsFiles, allLangText, langText) {
var node = this.node;
return Vow.all(jsFiles.map(function(file) {
return vowFs.read(file.fullname, 'utf8').then(function(data) {
var filename = node.relativePath(file.fullname);
return '/* begin: ' + filename + ' *' + '/\n' + data + '\n/* end: ' + filename + ' *' + '/';
});
})).then(function(contents) {
return contents
.concat([allLangText, langText]) // Adds content fragments from internationalization files
.join('\n');
});
})
.createTech();
```
## Technology for joining multiple targets
Consider a ready-made example:
```javascript
// This example builds a localized priv.js
module.exports = require('enb/lib/build-flow').create()
.name('priv-js-i18n')
.target('target', '?.{lang}.priv.js')
.defineRequiredOption('lang')
// All the targets are prepared by other technologies:
.useSourceFilename('allLangTarget', '?.lang.all.js') // Sets the dependency from the name of the
// common internationalization file
.useSourceFilename('langTarget', '?.lang.{lang}.js') // Sets the dependency from the name of the
// specific language file
.useSourceFilename('privJsTarget', '?.priv.js') // Sets the dependency from the name of the
// priv-js file
.justJoinFilesWithComments() // Uses the helper to join the files
.createTech();
```
Joining without the helper:
```javascript
module.exports = require('enb/lib/build-flow').create()
.name('priv-js-i18n')
.target('target', '?.{lang}.priv.js')
.defineRequiredOption('lang')
.useSourceFilename('allLangTarget', '?.lang.all.js')
.useSourceFilename('langTarget', '?.lang.{lang}.js')
.useSourceFilename('privJsTarget', '?.priv.js')
.builder(function(allLangFilename, langFilename, privJsFilename) {
var node = this.node;
// Iterates through the source files
return Vow.all([allLangFilename, langFilename, privJsFilename].map(function(absoluteFilename) {
// Reads each source file
return vowFs.read(absoluteFilename, 'utf8').then(function(data) {
// Receives a relative file path
var filename = node.relativePath(absoluteFilename);
// Forms a fragment
return '/* begin: ' + filename + ' *' + '/\n' + data + '\n/* end: ' + filename + ' *' + '/';
});
})).then(function(contents) {
return contents.join('\n'); // Combines the fragments
});
})
.createTech();
```
## Dependencies from the files not included in the build
If you need to add a modular system in the beginning of a file and save the result with a new name:
```javascript
var vowFs = require('vow-fs'); // Connects the module for working with the file system
var path = require('path'); // Connects utilities for working with paths
module.exports = require('enb/lib/build-flow').create()
.name('prepend-modules')
.target('target', '?.js')
.defineRequiredOption('source') // Specifies the required option
.useSourceText('source', '?') // Sets the dependency from the content of the target defined by the 'source' option
.needRebuild(function(cache) { // Specifies an additional cache check
// In this case, the modular system isn't located at the source redefinition levels,
// but it can be found in the 'ym' package; for the rebuild to work correctly if
// the modules.js content changes, add the check
this._modulesFile = path.join(__dirname, '..', 'node_modules', 'ym', 'modules.js'); // Forms the path
return cache.needRebuildFile( // Checks if the file changed
'modules-file', // Key for caching the file information; must be unique within the technology
this._modulesFile // Path to the file for which the cache should be checked
);
})
.saveCache(function(cache) { // Saves the cache data in the used file
cache.cacheFileInfo( // Saves the file information
'modules-file', // Key for caching the file information; must be unique within the technology
this._modulesFile // Path to the file for which the cache should be checked
);
})
.builder(function(preTargetSource) {
// Reads the content of the modular system file
return vowFs.read(this._modulesFile, 'utf8').then(function(modulesRes) {
return modulesRes + preTargetSource; // Joins the results
});
})
.createTech();
```
### Creating a new technology from an existing one
Sometimes you need to to extend existing technologies.
Every technology made with `BuildFlow` contains the `buildFlow()` method that can be called to create a new technology from the functionality of the existing one.
For example, there is a `css` technology:
```javascript
module.exports = require('enb/lib/build-flow').create()
.name('css')
.target('target', '?.css')
.useFileList('css')
.builder(function(cssFiles) {
// ...
})
.methods({
// ...
})
.createTech();
```
To build `light.css` suffixes together with `css` suffixes, you need to write a new technology that borrows the functionality of the old one:
```javascript
module.exports = require('enb/techs/css').buildFlow()
.name('css-light') // Changes the name
.useFileList(['css', 'light.css']) // Changes the necessary parameters
.createTech();
```
|
Java
|
.help {
cursor: help;
display: inline-block;
font-size: 18px;
margin-left: .33em;
vertical-align: middle;
}
|
Java
|
---
layout: page-fullwidth
subheadline: "Celebration"
title: "Tết Nguyên Đán 2015"
meta_teaser: "Tet Nguyen Đan 2015 at VACSF"
teaser: 'Celebration of <font face="Open Sans">Tết Nguyên Đán</font> (Lunar New Year) of 2015 at <font face="Open Sans">Hội Thánh Tin Lành Việt Nam</font> in the city of San Francisco (VACSF). Enjoy this collection of photos.'
header: no
categories:
- events
---
<!--more-->
<div class="flex-video"> <iframe width="100%" height="720" src="http://rgb-scale.com/vacsfj336/index.php/photo-galleries/135-t-t-nguyen-dan-2015" frameborder="0" allowfullscreen=""></iframe></div>
<div class="small-12 columns" style="padding: 0px; border-bottom: none;">
<p> </p>
{% include next-previous-post-in-category %}
</div>
|
Java
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (fn /*, ...args*/) {
var args = (0, _slice2.default)(arguments, 1);
return function () /*callArgs*/{
var callArgs = (0, _slice2.default)(arguments);
return fn.apply(null, args.concat(callArgs));
};
};
var _slice = require('./internal/slice');
var _slice2 = _interopRequireDefault(_slice);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
;
/**
* Creates a continuation function with some arguments already applied.
*
* Useful as a shorthand when combined with other control flow functions. Any
* arguments passed to the returned function are added to the arguments
* originally passed to apply.
*
* @name apply
* @static
* @memberOf module:Utils
* @method
* @category Util
* @param {Function} fn - The function you want to eventually apply all
* arguments to. Invokes with (arguments...).
* @param {...*} arguments... - Any number of arguments to automatically apply
* when the continuation is called.
* @returns {Function} the partially-applied function
* @example
*
* // using apply
* async.parallel([
* async.apply(fs.writeFile, 'testfile1', 'test1'),
* async.apply(fs.writeFile, 'testfile2', 'test2')
* ]);
*
*
* // the same process without using apply
* async.parallel([
* function(callback) {
* fs.writeFile('testfile1', 'test1', callback);
* },
* function(callback) {
* fs.writeFile('testfile2', 'test2', callback);
* }
* ]);
*
* // It's possible to pass any number of additional arguments when calling the
* // continuation:
*
* node> var fn = async.apply(sys.puts, 'one');
* node> fn('two', 'three');
* one
* two
* three
*/
module.exports = exports['default'];
|
Java
|
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2009-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __CCTMX_LAYER_H__
#define __CCTMX_LAYER_H__
#include "CCTMXObjectGroup.h"
#include "base_nodes/CCAtlasNode.h"
#include "sprite_nodes/CCSpriteBatchNode.h"
#include "CCTMXXMLParser.h"
#include "support/data_support/ccCArray.h"
NS_CC_BEGIN
class TMXMapInfo;
class TMXLayerInfo;
class TMXTilesetInfo;
struct _ccCArray;
/**
* @addtogroup tilemap_parallax_nodes
* @{
*/
/** @brief TMXLayer represents the TMX layer.
It is a subclass of SpriteBatchNode. By default the tiles are rendered using a TextureAtlas.
If you modify a tile on runtime, then, that tile will become a Sprite, otherwise no Sprite objects are created.
The benefits of using Sprite objects as tiles are:
- tiles (Sprite) can be rotated/scaled/moved with a nice API
If the layer contains a property named "cc_vertexz" with an integer (in can be positive or negative),
then all the tiles belonging to the layer will use that value as their OpenGL vertex Z for depth.
On the other hand, if the "cc_vertexz" property has the "automatic" value, then the tiles will use an automatic vertex Z value.
Also before drawing the tiles, GL_ALPHA_TEST will be enabled, and disabled after drawing them. The used alpha func will be:
glAlphaFunc( GL_GREATER, value )
"value" by default is 0, but you can change it from Tiled by adding the "cc_alpha_func" property to the layer.
The value 0 should work for most cases, but if you have tiles that are semi-transparent, then you might want to use a different
value, like 0.5.
For further information, please see the programming guide:
http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:tiled_maps
@since v0.8.1
Tiles can have tile flags for additional properties. At the moment only flip horizontal and flip vertical are used. These bit flags are defined in TMXXMLParser.h.
@since 1.1
*/
class CC_DLL TMXLayer : public SpriteBatchNode
{
public:
/** creates a TMXLayer with an tileset info, a layer info and a map info */
static TMXLayer * create(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo);
TMXLayer();
virtual ~TMXLayer();
/** initializes a TMXLayer with a tileset info, a layer info and a map info */
bool initWithTilesetInfo(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo);
/** dealloc the map that contains the tile position from memory.
Unless you want to know at runtime the tiles positions, you can safely call this method.
If you are going to call layer->tileGIDAt() then, don't release the map
*/
void releaseMap();
/** returns the tile (Sprite) at a given a tile coordinate.
The returned Sprite will be already added to the TMXLayer. Don't add it again.
The Sprite can be treated like any other Sprite: rotated, scaled, translated, opacity, color, etc.
You can remove either by calling:
- layer->removeChild(sprite, cleanup);
- or layer->removeTileAt(Point(x,y));
*/
Sprite* getTileAt(const Point& tileCoordinate);
CC_DEPRECATED_ATTRIBUTE Sprite* tileAt(const Point& tileCoordinate) { return getTileAt(tileCoordinate); };
/** returns the tile gid at a given tile coordinate. It also returns the tile flags.
This method requires the the tile map has not been previously released (eg. don't call [layer releaseMap])
*/
unsigned int getTileGIDAt(const Point& tileCoordinate, ccTMXTileFlags* flags = nullptr);
CC_DEPRECATED_ATTRIBUTE unsigned int tileGIDAt(const Point& tileCoordinate, ccTMXTileFlags* flags = nullptr){
return getTileGIDAt(tileCoordinate, flags);
};
/** sets the tile gid (gid = tile global id) at a given tile coordinate.
The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor -> Tileset Mgr +1.
If a tile is already placed at that position, then it will be removed.
*/
void setTileGID(unsigned int gid, const Point& tileCoordinate);
/** sets the tile gid (gid = tile global id) at a given tile coordinate.
The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor -> Tileset Mgr +1.
If a tile is already placed at that position, then it will be removed.
Use withFlags if the tile flags need to be changed as well
*/
void setTileGID(unsigned int gid, const Point& tileCoordinate, ccTMXTileFlags flags);
/** removes a tile at given tile coordinate */
void removeTileAt(const Point& tileCoordinate);
/** returns the position in points of a given tile coordinate */
Point getPositionAt(const Point& tileCoordinate);
CC_DEPRECATED_ATTRIBUTE Point positionAt(const Point& tileCoordinate) { return getPositionAt(tileCoordinate); };
/** return the value for the specific property name */
String* getProperty(const char *propertyName) const;
CC_DEPRECATED_ATTRIBUTE String* propertyNamed(const char *propertyName) const { return getProperty(propertyName); };
/** Creates the tiles */
void setupTiles();
inline const char* getLayerName(){ return _layerName.c_str(); }
inline void setLayerName(const char *layerName){ _layerName = layerName; }
/** size of the layer in tiles */
inline const Size& getLayerSize() const { return _layerSize; };
inline void setLayerSize(const Size& size) { _layerSize = size; };
/** size of the map's tile (could be different from the tile's size) */
inline const Size& getMapTileSize() const { return _mapTileSize; };
inline void setMapTileSize(const Size& size) { _mapTileSize = size; };
/** pointer to the map of tiles */
inline unsigned int* getTiles() const { return _tiles; };
inline void setTiles(unsigned int* tiles) { _tiles = tiles; };
/** Tileset information for the layer */
inline TMXTilesetInfo* getTileSet() const { return _tileSet; };
inline void setTileSet(TMXTilesetInfo* info) {
CC_SAFE_RETAIN(info);
CC_SAFE_RELEASE(_tileSet);
_tileSet = info;
};
/** Layer orientation, which is the same as the map orientation */
inline unsigned int getLayerOrientation() const { return _layerOrientation; };
inline void setLayerOrientation(unsigned int orientation) { _layerOrientation = orientation; };
/** properties from the layer. They can be added using Tiled */
inline Dictionary* getProperties() const { return _properties; };
inline void setProperties(Dictionary* properties) {
CC_SAFE_RETAIN(properties);
CC_SAFE_RELEASE(_properties);
_properties = properties;
};
//
// Override
//
/** TMXLayer doesn't support adding a Sprite manually.
@warning addchild(z, tag); is not supported on TMXLayer. Instead of setTileGID.
*/
virtual void addChild(Node * child, int zOrder, int tag) override;
// super method
void removeChild(Node* child, bool cleanup) override;
private:
Point getPositionForIsoAt(const Point& pos);
Point getPositionForOrthoAt(const Point& pos);
Point getPositionForHexAt(const Point& pos);
Point calculateLayerOffset(const Point& offset);
/* optimization methods */
Sprite* appendTileForGID(unsigned int gid, const Point& pos);
Sprite* insertTileForGID(unsigned int gid, const Point& pos);
Sprite* updateTileForGID(unsigned int gid, const Point& pos);
/* The layer recognizes some special properties, like cc_vertez */
void parseInternalProperties();
void setupTileSprite(Sprite* sprite, Point pos, unsigned int gid);
Sprite* reusedTileWithRect(Rect rect);
int getVertexZForPos(const Point& pos);
// index
unsigned int atlasIndexForExistantZ(unsigned int z);
unsigned int atlasIndexForNewZ(int z);
protected:
//! name of the layer
std::string _layerName;
//! TMX Layer supports opacity
unsigned char _opacity;
unsigned int _minGID;
unsigned int _maxGID;
//! Only used when vertexZ is used
int _vertexZvalue;
bool _useAutomaticVertexZ;
//! used for optimization
Sprite *_reusedTile;
ccCArray *_atlasIndexArray;
// used for retina display
float _contentScaleFactor;
/** size of the layer in tiles */
Size _layerSize;
/** size of the map's tile (could be different from the tile's size) */
Size _mapTileSize;
/** pointer to the map of tiles */
unsigned int* _tiles;
/** Tileset information for the layer */
TMXTilesetInfo* _tileSet;
/** Layer orientation, which is the same as the map orientation */
unsigned int _layerOrientation;
/** properties from the layer. They can be added using Tiled */
Dictionary* _properties;
};
// end of tilemap_parallax_nodes group
/// @}
NS_CC_END
#endif //__CCTMX_LAYER_H__
|
Java
|
# app
The `app` module is responsible for controlling the application's lifecycle.
The following example shows how to quit the application when the last window is
closed:
```javascript
const app = require('electron').app;
app.on('window-all-closed', function() {
app.quit();
});
```
## Events
The `app` object emits the following events:
### Event: 'will-finish-launching'
Emitted when the application has finished basic startup. On Windows and Linux,
the `will-finish-launching` event is the same as the `ready` event; on OS X,
this event represents the `applicationWillFinishLaunching` notification of
`NSApplication`. You would usually set up listeners for the `open-file` and
`open-url` events here, and start the crash reporter and auto updater.
In most cases, you should just do everything in the `ready` event handler.
### Event: 'ready'
Emitted when Electron has finished initialization.
### Event: 'window-all-closed'
Emitted when all windows have been closed.
This event is only emitted when the application is not going to quit. If the
user pressed `Cmd + Q`, or the developer called `app.quit()`, Electron will
first try to close all the windows and then emit the `will-quit` event, and in
this case the `window-all-closed` event would not be emitted.
### Event: 'before-quit'
Returns:
* `event` Event
Emitted before the application starts closing its windows.
Calling `event.preventDefault()` will prevent the default behaviour, which is
terminating the application.
### Event: 'will-quit'
Returns:
* `event` Event
Emitted when all windows have been closed and the application will quit.
Calling `event.preventDefault()` will prevent the default behaviour, which is
terminating the application.
See the description of the `window-all-closed` event for the differences between
the `will-quit` and `window-all-closed` events.
### Event: 'quit'
Returns:
* `event` Event
* `exitCode` Integer
Emitted when the application is quitting.
### Event: 'open-file' _OS X_
Returns:
* `event` Event
* `path` String
Emitted when the user wants to open a file with the application. The `open-file`
event is usually emitted when the application is already open and the OS wants
to reuse the application to open the file. `open-file` is also emitted when a
file is dropped onto the dock and the application is not yet running. Make sure
to listen for the `open-file` event very early in your application startup to
handle this case (even before the `ready` event is emitted).
You should call `event.preventDefault()` if you want to handle this event.
On Windows, you have to parse `process.argv` to get the filepath.
### Event: 'open-url' _OS X_
Returns:
* `event` Event
* `url` String
Emitted when the user wants to open a URL with the application. The URL scheme
must be registered to be opened by your application.
You should call `event.preventDefault()` if you want to handle this event.
### Event: 'activate' _OS X_
Returns:
* `event` Event
* `hasVisibleWindows` Boolean
Emitted when the application is activated, which usually happens when clicks on
the applications's dock icon.
### Event: 'browser-window-blur'
Returns:
* `event` Event
* `window` BrowserWindow
Emitted when a [browserWindow](browser-window.md) gets blurred.
### Event: 'browser-window-focus'
Returns:
* `event` Event
* `window` BrowserWindow
Emitted when a [browserWindow](browser-window.md) gets focused.
### Event: 'browser-window-created'
Returns:
* `event` Event
* `window` BrowserWindow
Emitted when a new [browserWindow](browser-window.md) is created.
### Event: 'certificate-error'
Returns:
* `event` Event
* `webContents` [WebContents](web-contents.md)
* `url` URL
* `error` String - The error code
* `certificate` Object
* `data` Buffer - PEM encoded data
* `issuerName` String
* `callback` Function
Emitted when failed to verify the `certificate` for `url`, to trust the
certificate you should prevent the default behavior with
`event.preventDefault()` and call `callback(true)`.
```javascript
session.on('certificate-error', function(event, webContents, url, error, certificate, callback) {
if (url == "https://github.com") {
// Verification logic.
event.preventDefault();
callback(true);
} else {
callback(false);
}
});
```
### Event: 'select-client-certificate'
Returns:
* `event` Event
* `webContents` [WebContents](web-contents.md)
* `url` URL
* `certificateList` [Objects]
* `data` Buffer - PEM encoded data
* `issuerName` String - Issuer's Common Name
* `callback` Function
Emitted when a client certificate is requested.
The `url` corresponds to the navigation entry requesting the client certificate
and `callback` needs to be called with an entry filtered from the list. Using
`event.preventDefault()` prevents the application from using the first
certificate from the store.
```javascript
app.on('select-client-certificate', function(event, webContents, url, list, callback) {
event.preventDefault();
callback(list[0]);
})
```
### Event: 'login'
Returns:
* `event` Event
* `webContents` [WebContents](web-contents.md)
* `request` Object
* `method` String
* `url` URL
* `referrer` URL
* `authInfo` Object
* `isProxy` Boolean
* `scheme` String
* `host` String
* `port` Integer
* `realm` String
* `callback` Function
Emitted when `webContents` wants to do basic auth.
The default behavior is to cancel all authentications, to override this you
should prevent the default behavior with `event.preventDefault()` and call
`callback(username, password)` with the credentials.
```javascript
app.on('login', function(event, webContents, request, authInfo, callback) {
event.preventDefault();
callback('username', 'secret');
})
```
### Event: 'gpu-process-crashed'
Emitted when the gpu process crashes.
## Methods
The `app` object has the following methods:
**Note:** Some methods are only available on specific operating systems and are labeled as such.
### `app.quit()`
Try to close all windows. The `before-quit` event will be emitted first. If all
windows are successfully closed, the `will-quit` event will be emitted and by
default the application will terminate.
This method guarantees that all `beforeunload` and `unload` event handlers are
correctly executed. It is possible that a window cancels the quitting by
returning `false` in the `beforeunload` event handler.
### `app.hide()` _OS X_
Hides all application windows without minimising them.
### `app.show()` _OS X_
Shows application windows after they were hidden. Does not automatically focus them.
### `app.exit(exitCode)`
* `exitCode` Integer
Exits immediately with `exitCode`.
All windows will be closed immediately without asking user and the `before-quit`
and `will-quit` events will not be emitted.
### `app.getAppPath()`
Returns the current application directory.
### `app.getPath(name)`
* `name` String
Retrieves a path to a special directory or file associated with `name`. On
failure an `Error` is thrown.
You can request the following paths by the name:
* `home` User's home directory.
* `appData` Per-user application data directory, which by default points to:
* `%APPDATA%` on Windows
* `$XDG_CONFIG_HOME` or `~/.config` on Linux
* `~/Library/Application Support` on OS X
* `userData` The directory for storing your app's configuration files, which by
default it is the `appData` directory appended with your app's name.
* `temp` Temporary directory.
* `exe` The current executable file.
* `module` The `libchromiumcontent` library.
* `desktop` The current user's Desktop directory.
* `documents` Directory for a user's "My Documents".
* `downloads` Directory for a user's downloads.
* `music` Directory for a user's music.
* `pictures` Directory for a user's pictures.
* `videos` Directory for a user's videos.
### `app.setPath(name, path)`
* `name` String
* `path` String
Overrides the `path` to a special directory or file associated with `name`. If
the path specifies a directory that does not exist, the directory will be
created by this method. On failure an `Error` is thrown.
You can only override paths of a `name` defined in `app.getPath`.
By default, web pages' cookies and caches will be stored under the `userData`
directory. If you want to change this location, you have to override the
`userData` path before the `ready` event of the `app` module is emitted.
### `app.getVersion()`
Returns the version of the loaded application. If no version is found in the
application's `package.json` file, the version of the current bundle or
executable is returned.
### `app.getName()`
Returns the current application's name, which is the name in the application's
`package.json` file.
Usually the `name` field of `package.json` is a short lowercased name, according
to the npm modules spec. You should usually also specify a `productName`
field, which is your application's full capitalized name, and which will be
preferred over `name` by Electron.
### `app.getLocale()`
Returns the current application locale.
### `app.addRecentDocument(path)` _OS X_ _Windows_
* `path` String
Adds `path` to the recent documents list.
This list is managed by the OS. On Windows you can visit the list from the task
bar, and on OS X you can visit it from dock menu.
### `app.clearRecentDocuments()` _OS X_ _Windows_
Clears the recent documents list.
### `app.setUserTasks(tasks)` _Windows_
* `tasks` Array - Array of `Task` objects
Adds `tasks` to the [Tasks][tasks] category of the JumpList on Windows.
`tasks` is an array of `Task` objects in the following format:
`Task` Object:
* `program` String - Path of the program to execute, usually you should
specify `process.execPath` which opens the current program.
* `arguments` String - The command line arguments when `program` is
executed.
* `title` String - The string to be displayed in a JumpList.
* `description` String - Description of this task.
* `iconPath` String - The absolute path to an icon to be displayed in a
JumpList, which can be an arbitrary resource file that contains an icon. You
can usually specify `process.execPath` to show the icon of the program.
* `iconIndex` Integer - The icon index in the icon file. If an icon file
consists of two or more icons, set this value to identify the icon. If an
icon file consists of one icon, this value is 0.
### `app.allowNTLMCredentialsForAllDomains(allow)`
* `allow` Boolean
Dynamically sets whether to always send credentials for HTTP NTLM or Negotiate
authentication - normally, Electron will only send NTLM/Kerberos credentials for
URLs that fall under "Local Intranet" sites (i.e. are in the same domain as you).
However, this detection often fails when corporate networks are badly configured,
so this lets you co-opt this behavior and enable it for all URLs.
### `app.makeSingleInstance(callback)`
* `callback` Function
This method makes your application a Single Instance Application - instead of
allowing multiple instances of your app to run, this will ensure that only a
single instance of your app is running, and other instances signal this
instance and exit.
`callback` will be called with `callback(argv, workingDirectory)` when a second
instance has been executed. `argv` is an Array of the second instance's command
line arguments, and `workingDirectory` is its current working directory. Usually
applications respond to this by making their primary window focused and
non-minimized.
The `callback` is guaranteed to be executed after the `ready` event of `app`
gets emitted.
This method returns `false` if your process is the primary instance of the
application and your app should continue loading. And returns `true` if your
process has sent its parameters to another instance, and you should immediately
quit.
On OS X the system enforces single instance automatically when users try to open
a second instance of your app in Finder, and the `open-file` and `open-url`
events will be emitted for that. However when users start your app in command
line the system's single instance machanism will be bypassed and you have to
use this method to ensure single instance.
An example of activating the window of primary instance when a second instance
starts:
```js
var myWindow = null;
var shouldQuit = app.makeSingleInstance(function(commandLine, workingDirectory) {
// Someone tried to run a second instance, we should focus our window.
if (myWindow) {
if (myWindow.isMinimized()) myWindow.restore();
myWindow.focus();
}
return true;
});
if (shouldQuit) {
app.quit();
return;
}
// Create myWindow, load the rest of the app, etc...
app.on('ready', function() {
});
```
### `app.setAppUserModelId(id)` _Windows_
* `id` String
Changes the [Application User Model ID][app-user-model-id] to `id`.
### `app.isAeroGlassEnabled()` _Windows_
This method returns `true` if [DWM composition](https://msdn.microsoft.com/en-us/library/windows/desktop/aa969540.aspx)
(Aero Glass) is enabled, and `false` otherwise. You can use it to determine if
you should create a transparent window or not (transparent windows won't work
correctly when DWM composition is disabled).
Usage example:
```js
let browserOptions = {width: 1000, height: 800};
// Make the window transparent only if the platform supports it.
if (process.platform !== 'win32' || app.isAeroGlassEnabled()) {
browserOptions.transparent = true;
browserOptions.frame = false;
}
// Create the window.
win = new BrowserWindow(browserOptions);
// Navigate.
if (browserOptions.transparent) {
win.loadURL('file://' + __dirname + '/index.html');
} else {
// No transparency, so we load a fallback that uses basic styles.
win.loadURL('file://' + __dirname + '/fallback.html');
}
```
### `app.commandLine.appendSwitch(switch[, value])`
Append a switch (with optional `value`) to Chromium's command line.
**Note:** This will not affect `process.argv`, and is mainly used by developers
to control some low-level Chromium behaviors.
### `app.commandLine.appendArgument(value)`
Append an argument to Chromium's command line. The argument will be quoted
correctly.
**Note:** This will not affect `process.argv`.
### `app.dock.bounce([type])` _OS X_
* `type` String (optional) - Can be `critical` or `informational`. The default is
`informational`
When `critical` is passed, the dock icon will bounce until either the
application becomes active or the request is canceled.
When `informational` is passed, the dock icon will bounce for one second.
However, the request remains active until either the application becomes active
or the request is canceled.
Returns an ID representing the request.
### `app.dock.cancelBounce(id)` _OS X_
* `id` Integer
Cancel the bounce of `id`.
### `app.dock.setBadge(text)` _OS X_
* `text` String
Sets the string to be displayed in the dock’s badging area.
### `app.dock.getBadge()` _OS X_
Returns the badge string of the dock.
### `app.dock.hide()` _OS X_
Hides the dock icon.
### `app.dock.show()` _OS X_
Shows the dock icon.
### `app.dock.setMenu(menu)` _OS X_
* `menu` Menu
Sets the application's [dock menu][dock-menu].
### `app.dock.setIcon(image)` _OS X_
* `image` [NativeImage](native-image.md)
Sets the `image` associated with this dock icon.
[dock-menu]:https://developer.apple.com/library/mac/documentation/Carbon/Conceptual/customizing_docktile/concepts/dockconcepts.html#//apple_ref/doc/uid/TP30000986-CH2-TPXREF103
[tasks]:http://msdn.microsoft.com/en-us/library/windows/desktop/dd378460(v=vs.85).aspx#tasks
[app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx
|
Java
|
'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;
var assert = require('yeoman-assert');
describe('test framework', function () {
describe('mocha', function () {
before(function (done) {
helpers.run(path.join(__dirname, '../app'))
.inDir(path.join(__dirname, '.tmp'))
.withOptions({
'skip-install': true,
'test-framework': 'mocha'
})
.withPrompts({features: []})
.on('end', done);
});
it('adds the Grunt plugin', function () {
assert.fileContent('package.json', '"grunt-mocha"');
});
it('adds the Grunt task', function () {
assert.fileContent('Gruntfile.js', 'mocha');
});
it('uses the ESLint environment', function () {
assert.fileContent('package.json', '"mocha"');
});
});
describe('jasmine', function () {
before(function (done) {
helpers.run(path.join(__dirname, '../app'))
.inDir(path.join(__dirname, '.tmp'))
.withOptions({
'skip-install': true,
'test-framework': 'jasmine'
})
.withPrompts({features: []})
.on('end', done);
});
it('adds the Grunt plugin', function () {
assert.fileContent('package.json', '"grunt-contrib-jasmine"');
});
it('adds the Grunt task', function () {
assert.fileContent('Gruntfile.js', 'jasmine');
});
it('uses the ESLint environment', function () {
assert.fileContent('package.json', '"jasmine"');
});
});
});
|
Java
|
/*jshint maxstatements:false*/
define(function (require, exports) {
"use strict";
var moment = require("moment"),
Promise = require("bluebird"),
_ = brackets.getModule("thirdparty/lodash"),
CodeInspection = brackets.getModule("language/CodeInspection"),
CommandManager = brackets.getModule("command/CommandManager"),
Commands = brackets.getModule("command/Commands"),
Dialogs = brackets.getModule("widgets/Dialogs"),
DocumentManager = brackets.getModule("document/DocumentManager"),
EditorManager = brackets.getModule("editor/EditorManager"),
FileUtils = brackets.getModule("file/FileUtils"),
FileViewController = brackets.getModule("project/FileViewController"),
KeyBindingManager = brackets.getModule("command/KeyBindingManager"),
LanguageManager = brackets.getModule("language/LanguageManager"),
FileSystem = brackets.getModule("filesystem/FileSystem"),
Menus = brackets.getModule("command/Menus"),
FindInFiles = brackets.getModule("search/FindInFiles"),
PanelManager = brackets.getModule("view/PanelManager"),
ProjectManager = brackets.getModule("project/ProjectManager"),
StringUtils = brackets.getModule("utils/StringUtils"),
Svn = require("src/svn/Svn"),
Events = require("./Events"),
EventEmitter = require("./EventEmitter"),
Preferences = require("./Preferences"),
ErrorHandler = require("./ErrorHandler"),
ExpectedError = require("./ExpectedError"),
Main = require("./Main"),
GutterManager = require("./GutterManager"),
Strings = require("../strings"),
Utils = require("src/Utils"),
SettingsDialog = require("./SettingsDialog"),
PANEL_COMMAND_ID = "brackets-git.panel";
var svnPanelTemplate = require("text!templates/svn-panel.html"),
gitPanelResultsTemplate = require("text!templates/git-panel-results.html"),
gitAuthorsDialogTemplate = require("text!templates/authors-dialog.html"),
gitCommitDialogTemplate = require("text!templates/git-commit-dialog.html"),
gitDiffDialogTemplate = require("text!templates/git-diff-dialog.html"),
questionDialogTemplate = require("text!templates/git-question-dialog.html");
var showFileWhiteList = /^\.gitignore$/;
var gitPanel = null,
$gitPanel = $(null),
gitPanelDisabled = null,
gitPanelMode = null,
showingUntracked = true,
$tableContainer = $(null);
/**
* Reloads the Document's contents from disk, discarding any unsaved changes in the editor.
*
* @param {!Document} doc
* @return {Promise} Resolved after editor has been refreshed; rejected if unable to load the
* file's new content. Errors are logged but no UI is shown.
*/
function _reloadDoc(doc) {
return Promise.cast(FileUtils.readAsText(doc.file))
.then(function (text) {
doc.refreshText(text, new Date());
})
.catch(function (err) {
ErrorHandler.logError("Error reloading contents of " + doc.file.fullPath);
ErrorHandler.logError(err);
});
}
function lintFile(filename) {
return CodeInspection.inspectFile(FileSystem.getFileForPath(Utils.getProjectRoot() + filename));
}
function _makeDialogBig($dialog) {
var $wrapper = $dialog.parents(".modal-wrapper").first();
if ($wrapper.length === 0) { return; }
// We need bigger commit dialog
var minWidth = 500,
minHeight = 300,
maxWidth = $wrapper.width(),
maxHeight = $wrapper.height(),
desiredWidth = maxWidth / 2,
desiredHeight = maxHeight / 2;
if (desiredWidth < minWidth) { desiredWidth = minWidth; }
if (desiredHeight < minHeight) { desiredHeight = minHeight; }
$dialog
.width(desiredWidth)
.children(".modal-body")
.css("max-height", desiredHeight)
.end();
return { width: desiredWidth, height: desiredHeight };
}
function _showCommitDialog(stagedDiff, lintResults, prefilledMessage) {
// Flatten the error structure from various providers
lintResults.forEach(function (lintResult) {
lintResult.errors = [];
if (Array.isArray(lintResult.result)) {
lintResult.result.forEach(function (resultSet) {
if (!resultSet.result || !resultSet.result.errors) { return; }
var providerName = resultSet.provider.name;
resultSet.result.errors.forEach(function (e) {
lintResult.errors.push((e.pos.line + 1) + ": " + e.message + " (" + providerName + ")");
});
});
} else {
ErrorHandler.logError("[brackets-git] lintResults contain object in unexpected format: " + JSON.stringify(lintResult));
}
lintResult.hasErrors = lintResult.errors.length > 0;
});
// Filter out only results with errors to show
lintResults = _.filter(lintResults, function (lintResult) {
return lintResult.hasErrors;
});
// Open the dialog
var compiledTemplate = Mustache.render(gitCommitDialogTemplate, {
Strings: Strings,
hasLintProblems: lintResults.length > 0,
lintResults: lintResults
}),
dialog = Dialogs.showModalDialogUsingTemplate(compiledTemplate),
$dialog = dialog.getElement();
// We need bigger commit dialog
_makeDialogBig($dialog);
// Show nicely colored commit diff
$dialog.find(".commit-diff").append(Utils.formatDiff(stagedDiff));
function getCommitMessageElement() {
var r = $dialog.find("[name='commit-message']:visible");
if (r.length !== 1) {
r = $dialog.find("[name='commit-message']");
for (var i = 0; i < r.length; i++) {
if ($(r[i]).css("display") !== "none") {
return $(r[i]);
}
}
}
return r;
}
var $commitMessageCount = $dialog.find("input[name='commit-message-count']");
// Add event to count characters in commit message
var recalculateMessageLength = function () {
var val = getCommitMessageElement().val().trim(),
length = val.length;
if (val.indexOf("\n")) {
// longest line
length = Math.max.apply(null, val.split("\n").map(function (l) { return l.length; }));
}
$commitMessageCount
.val(length)
.toggleClass("over50", length > 50 && length <= 100)
.toggleClass("over100", length > 100);
};
var usingTextArea = false;
// commit message handling
function switchCommitMessageElement() {
usingTextArea = !usingTextArea;
var findStr = "[name='commit-message']",
currentValue = $dialog.find(findStr + ":visible").val();
$dialog.find(findStr).toggle();
$dialog.find(findStr + ":visible")
.val(currentValue)
.focus();
recalculateMessageLength();
}
$dialog.find("button.primary").on("click", function (e) {
var $commitMessage = getCommitMessageElement();
if ($commitMessage.val().trim().length === 0) {
e.stopPropagation();
$commitMessage.addClass("invalid");
} else {
$commitMessage.removeClass("invalid");
}
});
$dialog.find("button.extendedCommit").on("click", function () {
switchCommitMessageElement();
// this value will be set only when manually triggered
Preferences.set("useTextAreaForCommitByDefault", usingTextArea);
});
function prefillMessage(msg) {
if (msg.indexOf("\n") !== -1 && !usingTextArea) {
switchCommitMessageElement();
}
$dialog.find("[name='commit-message']:visible").val(msg);
recalculateMessageLength();
}
if (Preferences.get("useTextAreaForCommitByDefault")) {
switchCommitMessageElement();
}
if (prefilledMessage) {
prefillMessage(prefilledMessage.trim());
}
// Add focus to commit message input
getCommitMessageElement().focus();
$dialog.find("[name='commit-message']")
.on("keyup", recalculateMessageLength)
.on("change", recalculateMessageLength);
recalculateMessageLength();
dialog.done(function (buttonId) {
if (buttonId === "ok") {
// this event won't launch when commit-message is empty so its safe to assume that it is not
var commitMessage = getCommitMessageElement().val();
// if commit message is extended and has a newline, put an empty line after first line to separate subject and body
var s = commitMessage.split("\n");
if (s.length > 1 && s[1].trim() !== "") {
s.splice(1, 0, "");
}
commitMessage = s.join("\n");
// now we are going to be paranoid and we will check if some mofo didn't change our diff
_getStagedDiff().then(function (diff) {
if (diff === stagedDiff) {
return Svn.commit(commitMessage);
} else {
throw new Error("Index was changed while commit dialog was shown!");
}
}).catch(function (err) {
ErrorHandler.showError(err, "Git Commit failed");
}).finally(function () {
EventEmitter.emit(Events.GIT_COMMITED);
refresh();
});
} else {
// this will trigger refreshing where appropriate
Svn.status();
}
});
}
function _showAuthors(file, blame, fromLine, toLine) {
var linesTotal = blame.length;
var blameStats = blame.reduce(function (stats, lineInfo) {
var name = lineInfo.author + " " + lineInfo["author-mail"];
if (stats[name]) {
stats[name] += 1;
} else {
stats[name] = 1;
}
return stats;
}, {});
blameStats = _.reduce(blameStats, function (arr, val, key) {
arr.push({
authorName: key,
lines: val,
percentage: Math.round(val / (linesTotal / 100))
});
return arr;
}, []);
blameStats = _.sortBy(blameStats, "lines").reverse();
if (fromLine || toLine) {
file += " (" + Strings.LINES + " " + fromLine + "-" + toLine + ")";
}
var compiledTemplate = Mustache.render(gitAuthorsDialogTemplate, {
file: file,
blameStats: blameStats,
Strings: Strings
});
Dialogs.showModalDialogUsingTemplate(compiledTemplate);
}
function _getCurrentFilePath(editor) {
var projectRoot = Utils.getProjectRoot(),
document = editor ? editor.document : DocumentManager.getCurrentDocument(),
filePath = document.file.fullPath;
if (filePath.indexOf(projectRoot) === 0) {
filePath = filePath.substring(projectRoot.length);
}
return filePath;
}
function handleAuthorsSelection() {
var editor = EditorManager.getActiveEditor(),
filePath = _getCurrentFilePath(editor),
currentSelection = editor.getSelection(),
fromLine = currentSelection.start.line + 1,
toLine = currentSelection.end.line + 1;
// fix when nothing is selected on that line
if (currentSelection.end.ch === 0) { toLine = toLine - 1; }
var isSomethingSelected = currentSelection.start.line !== currentSelection.end.line ||
currentSelection.start.ch !== currentSelection.end.ch;
if (!isSomethingSelected) {
ErrorHandler.showError(new ExpectedError("Nothing is selected!"));
return;
}
Svn.getBlame(filePath, fromLine, toLine).then(function (blame) {
return _showAuthors(filePath, blame, fromLine, toLine);
}).catch(function (err) {
ErrorHandler.showError(err, "Git Blame failed");
});
}
function handleAuthorsFile() {
var filePath = _getCurrentFilePath();
Svn.getBlame(filePath).then(function (blame) {
return _showAuthors(filePath, blame);
}).catch(function (err) {
ErrorHandler.showError(err, "Git Blame failed");
});
}
function handleGitDiff(file) {
Svn.diffFileNice(file).then(function (diff) {
// show the dialog with the diff
var compiledTemplate = Mustache.render(gitDiffDialogTemplate, { file: file, Strings: Strings }),
dialog = Dialogs.showModalDialogUsingTemplate(compiledTemplate),
$dialog = dialog.getElement();
_makeDialogBig($dialog);
$dialog.find(".commit-diff").append(Utils.formatDiff(diff));
}).catch(function (err) {
ErrorHandler.showError(err, "SVN Diff failed");
});
}
function handleGitUndo(file) {
var compiledTemplate = Mustache.render(questionDialogTemplate, {
title: Strings.UNDO_CHANGES,
question: StringUtils.format(Strings.Q_UNDO_CHANGES, _.escape(file)),
Strings: Strings
});
Dialogs.showModalDialogUsingTemplate(compiledTemplate).done(function (buttonId) {
if (buttonId === "ok") {
Svn.discardFileChanges(file).then(function () {
var currentProjectRoot = Utils.getProjectRoot();
DocumentManager.getAllOpenDocuments().forEach(function (doc) {
if (doc.file.fullPath === currentProjectRoot + file) {
_reloadDoc(doc);
}
});
refresh();
}).catch(function (err) {
ErrorHandler.showError(err, "Git Checkout failed");
});
}
});
}
function handleGitDelete(file) {
var compiledTemplate = Mustache.render(questionDialogTemplate, {
title: Strings.DELETE_FILE,
question: StringUtils.format(Strings.Q_DELETE_FILE, _.escape(file)),
Strings: Strings
});
Dialogs.showModalDialogUsingTemplate(compiledTemplate).done(function (buttonId) {
if (buttonId === "ok") {
FileSystem.resolve(Utils.getProjectRoot() + file, function (err, fileEntry) {
if (err) {
ErrorHandler.showError(err, "Could not resolve file");
return;
}
Promise.cast(ProjectManager.deleteItem(fileEntry))
.then(function () {
refresh();
})
.catch(function (err) {
ErrorHandler.showError(err, "File deletion failed");
});
});
}
});
}
function handleGlobalUpdate(){
var files = [];
return handleSvnUpdate(files);
}
function handleSvnUpdate(files){
if(!_.isArray(files)) return;
return Svn.updateFile(files).then(function(stdout){
refresh();
});
}
/**
* strips trailing whitespace from all the diffs and adds \n to the end
*/
function stripWhitespaceFromFile(filename, clearWholeFile) {
return new Promise(function (resolve, reject) {
var fullPath = Utils.getProjectRoot() + filename,
removeBom = Preferences.get("removeByteOrderMark"),
normalizeLineEndings = Preferences.get("normalizeLineEndings");
var _cleanLines = function (lineNumbers) {
// clean the file
var fileEntry = FileSystem.getFileForPath(fullPath);
return FileUtils.readAsText(fileEntry).then(function (text) {
if (removeBom) {
// remove BOM - \ufeff
text = text.replace(/\ufeff/g, "");
}
if (normalizeLineEndings) {
// normalizes line endings
text = text.replace(/\r\n/g, "\n");
}
// process lines
var lines = text.split("\n");
if (lineNumbers) {
lineNumbers.forEach(function (lineNumber) {
lines[lineNumber] = lines[lineNumber].replace(/\s+$/, "");
});
} else {
lines.forEach(function (ln, lineNumber) {
lines[lineNumber] = lines[lineNumber].replace(/\s+$/, "");
});
}
// add empty line to the end, i've heard that git likes that for some reason
if (Preferences.get("addEndlineToTheEndOfFile")) {
var lastLineNumber = lines.length - 1;
if (lines[lastLineNumber].length > 0) {
lines[lastLineNumber] = lines[lastLineNumber].replace(/\s+$/, "");
}
if (lines[lastLineNumber].length > 0) {
lines.push("");
}
}
//-
text = lines.join("\n");
return Promise.cast(FileUtils.writeText(fileEntry, text))
.catch(function (err) {
ErrorHandler.logError("Wasn't able to clean whitespace from file: " + fullPath);
resolve();
throw err;
})
.then(function () {
// refresh the file if it's open in the background
DocumentManager.getAllOpenDocuments().forEach(function (doc) {
if (doc.file.fullPath === fullPath) {
_reloadDoc(doc);
}
});
// diffs were cleaned in this file
resolve();
});
});
};
if (clearWholeFile) {
_cleanLines(null);
} else {
Svn.diffFile(filename).then(function (diff) {
if (!diff) { return resolve(); }
var modified = [],
changesets = diff.split("\n").filter(function (l) { return l.match(/^@@/) !== null; });
// collect line numbers to clean
changesets.forEach(function (line) {
var i,
m = line.match(/^@@ -([,0-9]+) \+([,0-9]+) @@/),
s = m[2].split(","),
from = parseInt(s[0], 10),
to = from - 1 + (parseInt(s[1], 10) || 1);
for (i = from; i <= to; i++) { modified.push(i > 0 ? i - 1 : 0); }
});
_cleanLines(modified);
}).catch(function (ex) {
// This error will bubble up to preparing commit dialog so just log here
ErrorHandler.logError(ex);
reject(ex);
});
}
});
}
function _getStagedDiff() {
return Svn.getDiffOfStagedFiles().then(function (diff) {
if (!diff) {
return Svn.getListOfStagedFiles().then(function (filesList) {
return Strings.DIFF_FAILED_SEE_FILES + "\n\n" + filesList;
});
}
return diff;
});
}
// whatToDo gets values "continue" "skip" "abort"
function handleRebase(whatToDo) {
Svn.rebase(whatToDo).then(function () {
EventEmitter.emit(Events.REFRESH_ALL);
}).catch(function (err) {
ErrorHandler.showError(err, "Rebase " + whatToDo + " failed");
});
}
function abortMerge() {
Svn.discardAllChanges().then(function () {
EventEmitter.emit(Events.REFRESH_ALL);
}).catch(function (err) {
ErrorHandler.showError(err, "Merge abort failed");
});
}
function findConflicts() {
FindInFiles.doSearch(/^<<<<<<<\s|^=======\s|^>>>>>>>\s/gm);
}
function commitMerge() {
Utils.loadPathContent(Utils.getProjectRoot() + "/.git/MERGE_MSG").then(function (msg) {
handleGitCommit(msg);
}).catch(function (err) {
ErrorHandler.showError(err, "Merge commit failed");
});
}
function handleGitCommit(prefilledMessage) {
var codeInspectionEnabled = Preferences.get("useCodeInspection");
var stripWhitespace = Preferences.get("stripWhitespaceFromCommits");
// Disable button (it will be enabled when selecting files after reset)
Utils.setLoading($gitPanel.find(".git-commit"));
// First reset staged files, then add selected files to the index.
Svn.status().then(function (files) {
files = _.filter(files, function (file) {
return file.status.indexOf(Svn.FILE_STATUS.MODIFIED) !== -1;
});
if (files.length === 0) {
return ErrorHandler.showError(new Error("Commit button should have been disabled"), "Nothing staged to commit");
}
var lintResults = [],
promises = [];
files.forEach(function (fileObj) {
var queue = Promise.resolve();
var isDeleted = fileObj.status.indexOf(Svn.FILE_STATUS.DELETED) !== -1,
updateIndex = isDeleted;
// strip whitespace if configured to do so and file was not deleted
if (stripWhitespace && !isDeleted) {
// strip whitespace only for recognized languages so binary files won't get corrupted
var langId = LanguageManager.getLanguageForPath(fileObj.file).getId();
if (["unknown", "binary", "image", "markdown"].indexOf(langId) === -1) {
queue = queue.then(function () {
var clearWholeFile = fileObj.status.indexOf(Svn.FILE_STATUS.UNTRACKED) !== -1 ||
fileObj.status.indexOf(Svn.FILE_STATUS.RENAMED) !== -1;
return stripWhitespaceFromFile(fileObj.file, clearWholeFile);
});
}
}
// do a code inspection for the file, if it was not deleted
if (codeInspectionEnabled && !isDeleted) {
queue = queue.then(function () {
return lintFile(fileObj.file).then(function (result) {
if (result) {
lintResults.push({
filename: fileObj.file,
result: result
});
}
});
});
}
promises.push(queue);
});
return Promise.all(promises).then(function () {
// All files are in the index now, get the diff and show dialog.
return _getStagedDiff().then(function (diff) {
return _showCommitDialog(diff, lintResults, prefilledMessage);
});
});
}).catch(function (err) {
ErrorHandler.showError(err, "Preparing commit dialog failed");
}).finally(function () {
Utils.unsetLoading($gitPanel.find(".git-commit"));
});
}
function refreshCurrentFile() {
var currentProjectRoot = Utils.getProjectRoot();
var currentDoc = DocumentManager.getCurrentDocument();
if (currentDoc) {
$gitPanel.find("tr").each(function () {
var currentFullPath = currentDoc.file.fullPath,
thisFile = $(this).attr("x-file");
$(this).toggleClass("selected", currentProjectRoot + thisFile === currentFullPath);
});
} else {
$gitPanel.find("tr").removeClass("selected");
}
}
function shouldShow(fileObj) {
if (showFileWhiteList.test(fileObj.name)) {
return true;
}
return ProjectManager.shouldShow(fileObj);
}
function _refreshTableContainer(files) {
if (!gitPanel.isVisible()) {
return;
}
// remove files that we should not show
files = _.filter(files, function (file) {
return shouldShow(file);
});
var allStaged = files.length > 0 && _.all(files, function (file) { return file.status.indexOf(Svn.FILE_STATUS.STAGED) !== -1; });
$gitPanel.find(".check-all").prop("checked", allStaged).prop("disabled", files.length === 0);
var $editedList = $tableContainer.find(".git-edited-list");
var visibleBefore = $editedList.length ? $editedList.is(":visible") : true;
$editedList.remove();
if (files.length === 0) {
$tableContainer.append($("<p class='git-edited-list nothing-to-commit' />").text(Strings.NOTHING_TO_COMMIT));
} else {
// if desired, remove untracked files from the results
if (showingUntracked === false) {
files = _.filter(files, function (file) {
return file.status.indexOf(Svn.FILE_STATUS.UNTRACKED) === -1;
});
}
// -
files.forEach(function (file) {
file.staged = file.status.indexOf(Svn.FILE_STATUS.STAGED) !== -1;
file.statusText = file.status.map(function (status) {
return Strings["FILE_" + status];
}).join(", ");
file.allowDiff = file.status.indexOf(Svn.FILE_STATUS.UNTRACKED) === -1 &&
file.status.indexOf(Svn.FILE_STATUS.RENAMED) === -1 &&
file.status.indexOf(Svn.FILE_STATUS.DELETED) === -1;
file.allowDelete = file.status.indexOf(Svn.FILE_STATUS.UNTRACKED) !== -1;
file.allowUndo = !file.allowDelete && file.status.indexOf(Svn.FILE_STATUS.MODIFIED) !== -1;
file.allowUpdate = file.status.indexOf(Svn.FILE_STATUS.OUTOFDATE) !== -1;
file.allowAdd = file.status.indexOf(Svn.FILE_STATUS.UNTRACKED) > -1;
});
$tableContainer.append(Mustache.render(gitPanelResultsTemplate, {
files: files,
Strings: Strings
}));
refreshCurrentFile();
}
$tableContainer.find(".git-edited-list").toggle(visibleBefore);
}
function refresh() {
// set the history panel to false and remove the class that show the button history active when refresh
$gitPanel.find(".git-history-toggle").removeClass("active").attr("title", Strings.TOOLTIP_SHOW_HISTORY);
$gitPanel.find(".git-file-history").removeClass("active").attr("title", Strings.TOOLTIP_SHOW_FILE_HISTORY);
if (gitPanelMode === "not-repo") {
$tableContainer.empty();
return Promise.resolve();
}
$tableContainer.find("#git-history-list").remove();
$tableContainer.find(".git-edited-list").show();
var p1 = Svn.status(true);
//- push button
//var $pushBtn = $gitPanel.find(".git-push");
// var p2 = Svn.getCommitsAhead().then(function (commits) {
// $pushBtn.children("span").remove();
// if (commits.length > 0) {
// $pushBtn.append($("<span/>").text(" (" + commits.length + ")"));
// }
// }).catch(function () {
// $pushBtn.children("span").remove();
// });
// FUTURE: who listens for this?
return Promise.all([p1]);
}
function toggle(bool) {
if (gitPanelDisabled === true) {
return;
}
if (typeof bool !== "boolean") {
bool = !gitPanel.isVisible();
}
Preferences.persist("panelEnabled", bool);
Main.$icon.toggleClass("on", bool);
gitPanel.setVisible(bool);
// Mark menu item as enabled/disabled.
CommandManager.get(PANEL_COMMAND_ID).setChecked(bool);
if (bool) {
refresh();
}
}
function handleToggleUntracked() {
showingUntracked = !showingUntracked;
$gitPanel
.find(".git-toggle-untracked")
.text(showingUntracked ? Strings.HIDE_UNTRACKED : Strings.SHOW_UNTRACKED);
refresh();
}
function commitCurrentFile() {
return Promise.cast(CommandManager.execute("file.save"))
.then(function () {
return Svn.resetIndex();
})
.then(function () {
var currentProjectRoot = Utils.getProjectRoot();
var currentDoc = DocumentManager.getCurrentDocument();
if (currentDoc) {
var relativePath = currentDoc.file.fullPath.substring(currentProjectRoot.length);
return Svn.stage(relativePath).then(function () {
return handleGitCommit();
});
}
});
}
function commitAllFiles() {
return Promise.cast(CommandManager.execute("file.saveAll"))
.then(function () {
return Svn.resetIndex();
})
.then(function () {
return Svn.stageAll().then(function () {
return handleGitCommit();
});
});
}
// Disable "commit" button if there aren't staged files to commit
function _toggleCommitButton(files) {
var anyStaged = _.any(files, function (file) { return file.status.indexOf(Svn.FILE_STATUS.STAGED) !== -1; });
$gitPanel.find(".git-commit").prop("disabled", !anyStaged);
}
EventEmitter.on(Events.GIT_STATUS_RESULTS, function (results) {
_refreshTableContainer(results);
_toggleCommitButton(results);
});
function undoLastLocalCommit() {
Svn.undoLastLocalCommit()
.catch(function (err) {
ErrorHandler.showError(err, "Impossible to undo last commit");
})
.finally(function () {
refresh();
});
}
var lastCheckOneClicked = null;
function attachDefaultTableHandlers() {
$tableContainer = $gitPanel.find(".table-container")
.off()
.on("click", ".check-one", function (e) {
e.stopPropagation();
var $tr = $(this).closest("tr"),
file = $tr.attr("x-file"),
status = $tr.attr("x-status"),
isChecked = $(this).is(":checked");
if (e.shiftKey) {
// do something if we press shift. Right now? Nothing.
}
lastCheckOneClicked = file;
})
.on("dblclick", ".check-one", function (e) {
e.stopPropagation();
})
.on("click", ".btn-git-diff", function (e) {
e.stopPropagation();
handleGitDiff($(e.target).closest("tr").attr("x-file"));
})
.on("click", ".btn-git-undo", function (e) {
e.stopPropagation();
handleGitUndo($(e.target).closest("tr").attr("x-file"));
})
.on("click", ".btn-git-delete", function (e) {
e.stopPropagation();
handleGitDelete($(e.target).closest("tr").attr("x-file"));
})
.on("click", ".btn-svn-add", function(e) {
e.stopPropagation();
handleSvnAdd($(e.target).closest("tr").attr("x-file"));
})
.on("click", ".btn-svn-update", function (e) {
e.stopPropagation();
handleSvnUpdate([$(e.target).closest("tr").attr("x-file")]);
})
.on("click", ".modified-file", function (e) {
var $this = $(e.currentTarget);
if ($this.attr("x-status") === Svn.FILE_STATUS.DELETED) {
return;
}
CommandManager.execute(Commands.FILE_OPEN, {
fullPath: Utils.getProjectRoot() + $this.attr("x-file")
});
})
.on("dblclick", ".modified-file", function (e) {
var $this = $(e.currentTarget);
if ($this.attr("x-status") === Svn.FILE_STATUS.DELETED) {
return;
}
FileViewController.addToWorkingSetAndSelect(Utils.getProjectRoot() + $this.attr("x-file"));
});
}
function discardAllChanges() {
return Utils.askQuestion(Strings.RESET_LOCAL_REPO, Strings.RESET_LOCAL_REPO_CONFIRM, { booleanResponse: true })
.then(function (response) {
if (response) {
return Svn.discardAllChanges().catch(function (err) {
ErrorHandler.showError(err, "Reset of local repository failed");
}).then(function () {
refresh();
});
}
});
}
function init() {
// Add panel
var panelHtml = Mustache.render(svnPanelTemplate, {
enableAdvancedFeatures: Preferences.get("enableAdvancedFeatures"),
showBashButton: Preferences.get("showBashButton"),
showReportBugButton: Preferences.get("showReportBugButton"),
S: Strings
});
var $panelHtml = $(panelHtml);
$panelHtml.find(".git-available, .git-not-available").hide();
gitPanel = PanelManager.createBottomPanel("brackets-git.panel", $panelHtml, 100);
$gitPanel = gitPanel.$panel;
$gitPanel
.on("click", ".close", toggle)
.on("click", ".check-all", function () {
$('.check-one').attr('checked',true);
})
.on("click", ".git-refresh", EventEmitter.emitFactory(Events.REFRESH_ALL))
.on("click", ".git-commit", EventEmitter.emitFactory(Events.HANDLE_GIT_COMMIT))
.on("click", ".git-commit-merge", commitMerge)
.on("click", ".svn-update", handleGlobalUpdate)
.on("click", ".git-find-conflicts", findConflicts)
.on("click", ".git-prev-gutter", GutterManager.goToPrev)
.on("click", ".git-next-gutter", GutterManager.goToNext)
.on("click", ".git-toggle-untracked", handleToggleUntracked)
.on("click", ".authors-selection", handleAuthorsSelection)
.on("click", ".authors-file", handleAuthorsFile)
.on("click", ".git-file-history", EventEmitter.emitFactory(Events.HISTORY_SHOW, "FILE"))
.on("click", ".git-history-toggle", EventEmitter.emitFactory(Events.HISTORY_SHOW, "GLOBAL"))
.on("click", ".git-bug", ErrorHandler.reportBug)
.on("click", ".git-settings", SettingsDialog.show)
.on("contextmenu", "tr", function (e) {
var $this = $(this);
if ($this.hasClass("history-commit")) { return; }
$this.click();
setTimeout(function () {
Menus.getContextMenu("git-panel-context-menu").open(e);
}, 1);
})
.on("click", ".git-bash", EventEmitter.emitFactory(Events.TERMINAL_OPEN))
.on("click", ".reset-all", discardAllChanges);
// Attaching table handlers
attachDefaultTableHandlers();
// Commit current and all shortcuts
var COMMIT_CURRENT_CMD = "brackets-git.commitCurrent",
COMMIT_ALL_CMD = "brackets-git.commitAll",
BASH_CMD = "brackets-git.launchBash",
PUSH_CMD = "brackets-git.push",
PULL_CMD = "brackets-git.pull",
GOTO_PREV_CHANGE = "brackets-git.gotoPrevChange",
GOTO_NEXT_CHANGE = "brackets-git.gotoNextChange";
// Add command to menu.
// Register command for opening bottom panel.
CommandManager.register(Strings.PANEL_COMMAND, PANEL_COMMAND_ID, toggle);
KeyBindingManager.addBinding(PANEL_COMMAND_ID, Preferences.get("panelShortcut"));
CommandManager.register(Strings.COMMIT_CURRENT_SHORTCUT, COMMIT_CURRENT_CMD, commitCurrentFile);
KeyBindingManager.addBinding(COMMIT_CURRENT_CMD, Preferences.get("commitCurrentShortcut"));
CommandManager.register(Strings.COMMIT_ALL_SHORTCUT, COMMIT_ALL_CMD, commitAllFiles);
KeyBindingManager.addBinding(COMMIT_ALL_CMD, Preferences.get("commitAllShortcut"));
CommandManager.register(Strings.LAUNCH_BASH_SHORTCUT, BASH_CMD, EventEmitter.emitFactory(Events.TERMINAL_OPEN));
KeyBindingManager.addBinding(BASH_CMD, Preferences.get("bashShortcut"));
CommandManager.register(Strings.PUSH_SHORTCUT, PUSH_CMD, EventEmitter.emitFactory(Events.HANDLE_PUSH));
KeyBindingManager.addBinding(PUSH_CMD, Preferences.get("pushShortcut"));
CommandManager.register(Strings.PULL_SHORTCUT, PULL_CMD, EventEmitter.emitFactory(Events.HANDLE_PULL));
KeyBindingManager.addBinding(PULL_CMD, Preferences.get("pullShortcut"));
CommandManager.register(Strings.GOTO_PREVIOUS_GIT_CHANGE, GOTO_PREV_CHANGE, GutterManager.goToPrev);
KeyBindingManager.addBinding(GOTO_PREV_CHANGE, Preferences.get("gotoPrevChangeShortcut"));
CommandManager.register(Strings.GOTO_NEXT_GIT_CHANGE, GOTO_NEXT_CHANGE, GutterManager.goToNext);
KeyBindingManager.addBinding(GOTO_NEXT_CHANGE, Preferences.get("gotoNextChangeShortcut"));
// Init moment - use the correct language
moment.lang(brackets.getLocale());
if(Svn.isWorkingCopy()){
enable();
}
// Show gitPanel when appropriate
if (Preferences.get("panelEnabled")) {
toggle(true);
}
}
function enable() {
EventEmitter.emit(Events.SVN_ENABLED);
// this function is called after every Branch.refresh
gitPanelMode = null;
//
$gitPanel.find(".git-available").show();
$gitPanel.find(".git-not-available").hide();
//
Main.$icon.removeClass("warning").removeAttr("title");
gitPanelDisabled = false;
// after all is enabled
refresh();
}
function disable(cause) {
EventEmitter.emit(Events.GIT_DISABLED, cause);
gitPanelMode = cause;
// causes: not-repo
if (gitPanelMode === "not-repo") {
$gitPanel.find(".git-available").hide();
$gitPanel.find(".git-not-available").show();
} else {
Main.$icon.addClass("warning").attr("title", cause);
toggle(false);
gitPanelDisabled = true;
}
refresh();
}
// Event listeners
EventEmitter.on(Events.BRACKETS_CURRENT_DOCUMENT_CHANGE, function () {
if (!gitPanel) { return; }
refreshCurrentFile();
});
EventEmitter.on(Events.BRACKETS_DOCUMENT_SAVED, function () {
if (!gitPanel) { return; }
refresh();
});
EventEmitter.on(Events.REBASE_MERGE_MODE, function (rebaseEnabled, mergeEnabled) {
$gitPanel.find(".git-rebase").toggle(rebaseEnabled);
$gitPanel.find(".git-merge").toggle(mergeEnabled);
$gitPanel.find("button.git-commit").toggle(!rebaseEnabled && !mergeEnabled);
});
EventEmitter.on(Events.HANDLE_GIT_COMMIT, function () {
handleGitCommit();
});
exports.init = init;
exports.refresh = refresh;
exports.toggle = toggle;
exports.enable = enable;
exports.disable = disable;
exports.getPanel = function () { return $gitPanel; };
});
|
Java
|
#!/bin/bash
source ../common.sh
subsection "oh-my-zsh"
sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"
chsh -s /bin/zsh
mv "${HOME}/.zshrc.pre-oh-my-zsh" "${HOME}/.zshrc"
|
Java
|
<article id="post-<?php print $ID ?>" <?php post_class(); ?>>
<div class="tb-short-img">
<?php
toebox\inc\ToeBox::HandleFeaturedImage();
?>
</div>
<?php
print \toebox\inc\ToeBox::FormatListTitle($post_title, get_the_permalink());
?>
<div class="entry-metadata">
<!-- TODO: allow setting for turning author and date off on posts -->
<span class="tb-date"><?php the_time(get_option('date_format')); ?></span>
|
<span class="tb-author"><?php print get_the_author(); ?></span>
|
<span class="tb-category"><?php the_category(', ') ?></span>
|
<span class="tb-tags"><?php the_tags( 'Tags: ', ', ', '' ); ?></span>
</div>
<div class="entry-excerpt">
<?php print $body ?>
</div>
</article>
|
Java
|
<!DOCTYPE html>
<html lang="en">
<head>
<title>ABNFImportError Enumeration Reference</title>
<link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
<link rel="stylesheet" type="text/css" href="../css/highlight.css" />
<meta charset="utf-8">
<script src="../js/jquery.min.js" defer></script>
<script src="../js/jazzy.js" defer></script>
<script src="../js/lunr.min.js" defer></script>
<script src="../js/typeahead.jquery.js" defer></script>
<script src="../js/jazzy.search.js" defer></script>
</head>
<body>
<a name="//apple_ref/swift/Enum/ABNFImportError" class="dashAnchor"></a>
<a title="ABNFImportError Enumeration Reference"></a>
<header class="header">
<p class="header-col header-col--primary">
<a class="header-link" href="../index.html">
Covfefe 0.6.1 Docs
</a>
(99% documented)
</p>
<p class="header-col--secondary">
<form role="search" action="../search.json">
<input type="text" placeholder="Search documentation" data-typeahead>
</form>
</p>
<p class="header-col header-col--secondary">
<a class="header-link" href="https://github.com/palle-k/Covfefe">
<img class="header-icon" src="../img/gh.png"/>
View on GitHub
</a>
</p>
</header>
<p class="breadcrumbs">
<a class="breadcrumb" href="../index.html">Covfefe Reference</a>
<img class="carat" src="../img/carat.png" />
ABNFImportError Enumeration Reference
</p>
<div class="content-wrapper">
<nav class="navigation">
<ul class="nav-groups">
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Guides.html">Guides</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../bnf.html">BNF</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Enums.html">Enumerations</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Enums/ABNFImportError.html">ABNFImportError</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Enums/Symbol.html">Symbol</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Enums/SyntaxTree.html">SyntaxTree</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Enums/Terminal.html">Terminal</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Extensions.html">Extensions</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions/Character.html">Character</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions/ClosedRange.html">ClosedRange</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Extensions/String.html">String</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Functions.html">Functions</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3ssgoiyAA10ProductionVAA11NonTerminalV_AA0C6StringVtF">-->(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3ssgoiyAA10ProductionVAA11NonTerminalV_AA6SymbolOtF">-->(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3ssgoiySayAA10ProductionVGAA11NonTerminalV_AA0C6ResultVtF">-->(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3lpgoiyAA16ProductionResultVAA0C6StringV_ADtF"><+>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3lpgoiyAA16ProductionResultVAD_AA0C6StringVtF"><+>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3lpgoiyAA16ProductionResultVAD_ADtF"><+>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3lpgoiyAA16ProductionStringVAA6SymbolO_ADtF"><+>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3lpgoiyAA16ProductionStringVAA6SymbolO_AFtF"><+>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3lpgoiyAA16ProductionStringVAD_AA6SymbolOtF"><+>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3lpgoiyAA16ProductionStringVAD_ADtF"><+>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3logoiyAA16ProductionResultVAA0C6StringV_AA6SymbolOtF"><|>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3logoiyAA16ProductionResultVAA0C6StringV_ADtF"><|>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3logoiyAA16ProductionResultVAA0C6StringV_AFtF"><|>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3logoiyAA16ProductionResultVAA6SymbolO_AA0C6StringVtF"><|>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3logoiyAA16ProductionResultVAA6SymbolO_ADtF"><|>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3logoiyAA16ProductionResultVAA6SymbolO_AFtF"><|>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3logoiyAA16ProductionResultVAD_AA0C6StringVtF"><|>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3logoiyAA16ProductionResultVAD_AA6SymbolOtF"><|>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe3logoiyAA16ProductionResultVAD_ADtF"><|>(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe2eeoiySbAA10SyntaxTreeOyxq_G_AEtSQRzSQR_r0_lF">==(_:_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe1nyAA6SymbolOSSF">n(_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe2rtyAA6SymbolOSSKF">rt(_:)</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Functions.html#/s:7Covfefe1tyAA6SymbolOSSF">t(_:)</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Protocols.html">Protocols</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/AmbiguousGrammarParser.html">AmbiguousGrammarParser</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/Parser.html">Parser</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Protocols/Tokenizer.html">Tokenizer</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Structs.html">Structures</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/CYKParser.html">CYKParser</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/DefaultTokenizer.html">DefaultTokenizer</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/EarleyParser.html">EarleyParser</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/Grammar.html">Grammar</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/NonTerminal.html">NonTerminal</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/NonTerminalString.html">NonTerminalString</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/Production.html">Production</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/ProductionResult.html">ProductionResult</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/ProductionString.html">ProductionString</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/SymbolSet.html">SymbolSet</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/SyntaxError.html">SyntaxError</a>
</li>
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Structs/SyntaxError/Reason.html">– Reason</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a class="nav-group-name-link" href="../Typealiases.html">Type Aliases</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a class="nav-group-task-link" href="../Typealiases.html#/s:7Covfefe9ParseTreea">ParseTree</a>
</li>
</ul>
</li>
</ul>
</nav>
<article class="main-content">
<section class="section">
<div class="section-content top-matter">
<h1>ABNFImportError</h1>
<div class="declaration">
<div class="language">
<pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">enum</span> <span class="kt">ABNFImportError</span> <span class="p">:</span> <span class="kt">Error</span></code></pre>
</div>
</div>
<p>Errors specific to the import of ABNF grammars</p>
</div>
</section>
<section class="section">
<div class="section-content">
<div class="task-group">
<ul class="item-container">
<li class="item">
<div>
<code>
<a name="/s:7Covfefe15ABNFImportErrorO12invalidRangeyACSi_SitcACmF"></a>
<a name="//apple_ref/swift/Element/invalidRange(line:column:)" class="dashAnchor"></a>
<a class="token" href="#/s:7Covfefe15ABNFImportErrorO12invalidRangeyACSi_SitcACmF">invalidRange(line:<wbr>column:<wbr>)</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>The grammar contains a range expression with a lower bound higher than the upper bound</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight swift"><code><span class="k">case</span> <span class="nf">invalidRange</span><span class="p">(</span><span class="nv">line</span><span class="p">:</span> <span class="kt">Int</span><span class="p">,</span> <span class="nv">column</span><span class="p">:</span> <span class="kt">Int</span><span class="p">)</span></code></pre>
</div>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:7Covfefe15ABNFImportErrorO15invalidCharcodeyACSi_SitcACmF"></a>
<a name="//apple_ref/swift/Element/invalidCharcode(line:column:)" class="dashAnchor"></a>
<a class="token" href="#/s:7Covfefe15ABNFImportErrorO15invalidCharcodeyACSi_SitcACmF">invalidCharcode(line:<wbr>column:<wbr>)</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>The grammar contains a charcode that is not a valid unicode scalar</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight swift"><code><span class="k">case</span> <span class="nf">invalidCharcode</span><span class="p">(</span><span class="nv">line</span><span class="p">:</span> <span class="kt">Int</span><span class="p">,</span> <span class="nv">column</span><span class="p">:</span> <span class="kt">Int</span><span class="p">)</span></code></pre>
</div>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:7Covfefe15ABNFImportErrorO21invalidCharacterRangeyACSi_SitcACmF"></a>
<a name="//apple_ref/swift/Element/invalidCharacterRange(line:column:)" class="dashAnchor"></a>
<a class="token" href="#/s:7Covfefe15ABNFImportErrorO21invalidCharacterRangeyACSi_SitcACmF">invalidCharacterRange(line:<wbr>column:<wbr>)</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>The grammar contains a charcode range with a lower bound higher than the upper bound</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight swift"><code><span class="k">case</span> <span class="nf">invalidCharacterRange</span><span class="p">(</span><span class="nv">line</span><span class="p">:</span> <span class="kt">Int</span><span class="p">,</span> <span class="nv">column</span><span class="p">:</span> <span class="kt">Int</span><span class="p">)</span></code></pre>
</div>
</div>
</section>
</div>
</li>
</ul>
</div>
</div>
</section>
</article>
</div>
<section class="footer">
<p>© 2020 <a class="link" href="https://github.com/palle-k" target="_blank" rel="external">palle-k</a>. All rights reserved. (Last updated: 2020-05-24)</p>
<p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy ♪♫ v0.13.3</a>, a <a class="link" href="https://realm.io" target="_blank" rel="external">Realm</a> project.</p>
</section>
</body>
</div>
</html>
|
Java
|
#include "stdafx.h"
#include "light.h"
using namespace graphic;
cLight::cLight()
{
}
cLight::~cLight()
{
}
void cLight::Init(TYPE type,
const Vector4 &ambient, // Vector4(1, 1, 1, 1),
const Vector4 &diffuse, // Vector4(0.2, 0.2, 0.2, 1)
const Vector4 &specular, // Vector4(1,1,1,1)
const Vector3 &direction) // Vector3(0,-1,0)
{
ZeroMemory(&m_light, sizeof(m_light));
m_light.Type = (D3DLIGHTTYPE)type;
m_light.Ambient = *(D3DCOLORVALUE*)&ambient;
m_light.Diffuse = *(D3DCOLORVALUE*)&diffuse;
m_light.Specular = *(D3DCOLORVALUE*)&specular;
m_light.Direction = *(D3DXVECTOR3*)&direction;
}
void cLight::SetDirection( const Vector3 &direction )
{
m_light.Direction = *(D3DXVECTOR3*)&direction;
}
void cLight::SetPosition( const Vector3 &pos )
{
m_light.Position = *(D3DXVECTOR3*)&pos;
}
// ±×¸²ÀÚ¸¦ Ãâ·ÂÇϱâ À§ÇÑ Á¤º¸¸¦ ¸®ÅÏÇÑ´Ù.
// modelPos : ±×¸²ÀÚ¸¦ Ãâ·ÂÇÒ ¸ðµ¨ÀÇ À§Ä¡ (¿ùµå»óÀÇ)
// lightPos : ±¤¿øÀÇ À§Ä¡°¡ ÀúÀåµÇ¾î ¸®ÅÏ.
// view : ±¤¿ø¿¡¼ ¸ðµ¨À» ¹Ù¶óº¸´Â ºä Çà·Ä
// proj : ±¤¿ø¿¡¼ ¸ðµ¨À» ¹Ù¶óº¸´Â Åõ¿µ Çà·Ä
// tt : Åõ¿µ ÁÂÇ¥¿¡¼ ÅØ½ºÃÄ ÁÂÇ¥·Î º¯È¯ÇÏ´Â Çà·Ä.
void cLight::GetShadowMatrix( const Vector3 &modelPos,
OUT Vector3 &lightPos, OUT Matrix44 &view, OUT Matrix44 &proj,
OUT Matrix44 &tt )
{
if (D3DLIGHT_DIRECTIONAL == m_light.Type)
{
// ¹æÇ⼺ Á¶¸íÀ̸é Direction º¤Å͸¦ ÅëÇØ À§Ä¡¸¦ °è»êÇÏ°Ô ÇÑ´Ù.
Vector3 pos = *(Vector3*)&m_light.Position;
Vector3 dir = *(Vector3*)&m_light.Direction;
lightPos = -dir * pos.Length();
}
else
{
lightPos = *(Vector3*)&m_light.Position;
}
view.SetView2( lightPos, modelPos, Vector3(0,1,0));
proj.SetProjection( D3DX_PI/8.f, 1, 0.1f, 10000);
D3DXMATRIX mTT= D3DXMATRIX(0.5f, 0.0f, 0.0f, 0.0f
, 0.0f,-0.5f, 0.0f, 0.0f
, 0.0f, 0.0f, 1.0f, 0.0f
, 0.5f, 0.5f, 0.0f, 1.0f);
tt = *(Matrix44*)&mTT;
}
void cLight::Bind(cRenderer &renderer, int lightIndex) const
{
renderer.GetDevice()->SetLight(lightIndex, &m_light); // ±¤¿ø ¼³Á¤.
}
// ¼ÎÀÌ´õ º¯¼ö¿¡ ¶óÀÌÆÃ¿¡ °ü·ÃµÈ º¯¼ö¸¦ ÃʱâÈ ÇÑ´Ù.
void cLight::Bind(cShader &shader) const
{
static cShader *oldPtr = NULL;
static D3DXHANDLE hDir = NULL;
static D3DXHANDLE hPos = NULL;
static D3DXHANDLE hAmbient = NULL;
static D3DXHANDLE hDiffuse = NULL;
static D3DXHANDLE hSpecular = NULL;
static D3DXHANDLE hTheta = NULL;
static D3DXHANDLE hPhi = NULL;
if (oldPtr != &shader)
{
hDir = shader.GetValueHandle("light.dir");
hPos = shader.GetValueHandle("light.pos");
hAmbient = shader.GetValueHandle("light.ambient");
hDiffuse = shader.GetValueHandle("light.diffuse");
hSpecular = shader.GetValueHandle("light.specular");
hTheta = shader.GetValueHandle("light.spotInnerCone");
hPhi = shader.GetValueHandle("light.spotOuterCone");
oldPtr = &shader;
}
shader.SetVector( hDir, *(Vector3*)&m_light.Direction);
shader.SetVector( hPos, *(Vector3*)&m_light.Position);
shader.SetVector( hAmbient, *(Vector4*)&m_light.Ambient);
shader.SetVector( hDiffuse, *(Vector4*)&m_light.Diffuse);
shader.SetVector( hSpecular, *(Vector4*)&m_light.Specular);
shader.SetFloat( hTheta, m_light.Theta);
shader.SetFloat( hPhi, m_light.Phi);
//shader.SetFloat( "light.radius", m_light.r);
}
|
Java
|
/**
* \file
*
* \brief Autogenerated API include file for the Atmel Software Framework (ASF)
*
* Copyright (c) 2012 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
#ifndef ASF_H
#define ASF_H
/*
* This file includes all API header files for the selected drivers from ASF.
* Note: There might be duplicate includes required by more than one driver.
*
* The file is automatically generated and will be re-written when
* running the ASF driver selector tool. Any changes will be discarded.
*/
// From module: Common SAM compiler driver
#include <compiler.h>
#include <status_codes.h>
// From module: GPIO - General purpose Input/Output
#include <gpio.h>
// From module: Generic board support
#include <board.h>
// From module: Generic components of unit test framework
#include <unit_test/suite.h>
// From module: IOPORT - General purpose I/O service
#include <ioport.h>
// From module: Interrupt management - SAM implementation
#include <interrupt.h>
// From module: PIO - Parallel Input/Output Controller
#include <pio.h>
// From module: PMC - Power Management Controller
#include <pmc.h>
#include <sleep.h>
// From module: Part identification macros
#include <parts.h>
// From module: SAM3S EK LED support enabled
#include <led.h>
// From module: SAM3S startup code
#include <exceptions.h>
// From module: SSC - Synchronous Serial Controller
#include <ssc.h>
// From module: Standard serial I/O (stdio) - SAM implementation
#include <stdio_serial.h>
// From module: System Clock Control - SAM3S implementation
#include <sysclk.h>
// From module: UART - Univ. Async Rec/Trans
#include <uart.h>
// From module: USART - Serial interface - SAM implementation for devices with both UART and USART
#include <serial.h>
// From module: USART - Univ. Syn Async Rec/Trans
#include <usart.h>
// From module: pio_handler support enabled
#include <pio_handler.h>
#endif // ASF_H
|
Java
|
<?php
declare(strict_types=1);
/*
* This file is part of eelly package.
*
* (c) eelly.com
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eelly\SDK\Order\Api;
use Eelly\SDK\EellyClient;
use Eelly\SDK\Order\Service\LikeInterface;
/**
* 订单点赞记录表
*
* @author zhangyingdi<zhangyingdi@eelly.net>
*/
class Like
{
/**
* 新增订单点赞记录
*
* @param array $data 订单点赞记录数据
* @param int $orderData["orderId"] 订单id
* @param int $orderData["userId"] 用户id
*
* @throws \Eelly\SDK\Order\Exception\OrderException
*
* @return bool 新增结果
* @requestExample({
* "data":{
* "orderId":123,
* "userId":148086
* }
* })
* @returnExample(true)
*
* @author zhangyingdi<zhangyingdi@eelly.net>
* @since 2018.04.28
*/
public function addOrderLike(array $data): bool
{
return EellyClient::request('order/like', 'addOrderLike', true, $data);
}
/**
* 新增订单点赞记录
*
* @param array $data 订单点赞记录数据
* @param int $orderData["orderId"] 订单id
* @param int $orderData["userId"] 用户id
*
* @throws \Eelly\SDK\Order\Exception\OrderException
*
* @return bool 新增结果
* @requestExample({
* "data":{
* "orderId":123,
* "userId":148086
* }
* })
* @returnExample(true)
*
* @author zhangyingdi<zhangyingdi@eelly.net>
* @since 2018.04.28
*/
public function addOrderLikeAsync(array $data)
{
return EellyClient::request('order/like', 'addOrderLike', false, $data);
}
/**
* 获取订单点赞信息
*
* @param $orderId 订单id
* @return array
*
* @requestExample({"orderId":162})
* @returnExample([{"oliId":"4","orderId":"161","userId":"148086","createdTime":"1524899508","updateTime":"2018-04-28 15:11:31"},{"oliId":"5","orderId":"161","userId":"11","createdTime":"1524899533","updateTime":"2018-04-28 15:11:55"}])
*
* @author wechan
* @since 2018年05月02日
*/
public function getOrderLikeInfo(int $orderId): array
{
return EellyClient::request('order/like', 'getOrderLikeInfo', true, $orderId);
}
/**
* 获取订单点赞信息
*
* @param $orderId 订单id
* @return array
*
* @requestExample({"orderId":162})
* @returnExample([{"oliId":"4","orderId":"161","userId":"148086","createdTime":"1524899508","updateTime":"2018-04-28 15:11:31"},{"oliId":"5","orderId":"161","userId":"11","createdTime":"1524899533","updateTime":"2018-04-28 15:11:55"}])
*
* @author wechan
* @since 2018年05月02日
*/
public function getOrderLikeInfoAsync(int $orderId)
{
return EellyClient::request('order/like', 'getOrderLikeInfo', false, $orderId);
}
/**
* 新增订单点赞记录 (新版--自定义商品点赞数控制).
*
* @param array $data 订单点赞记录数据
* @param int $orderData["orderId"] 订单id
* @param int $orderData["userId"] 用户id
* @param int $orderData["goodsId"] 商品id
* @param \Eelly\DTO\UidDTO $user 登录用户信息
*
* @throws \Eelly\SDK\Order\Exception\OrderException
*
* @return bool 新增结果
* @requestExample({
* "data":{
* "orderId":123,
* "userId":148086,
* "goodsId":123
* }
* })
* @returnExample(true)
*
* @author zhangyingdi<zhangyingdi@eelly.net>
*
* @since 2018.06.28
*/
public function addOrderLikeNew(array $data, UidDTO $user = null): bool
{
return EellyClient::request('order/like', 'addOrderLikeNew', true, $data, $user);
}
/**
* 新增订单点赞记录 (新版--自定义商品点赞数控制).
*
* @param array $data 订单点赞记录数据
* @param int $orderData["orderId"] 订单id
* @param int $orderData["userId"] 用户id
* @param int $orderData["goodsId"] 商品id
* @param \Eelly\DTO\UidDTO $user 登录用户信息
*
* @throws \Eelly\SDK\Order\Exception\OrderException
*
* @return bool 新增结果
* @requestExample({
* "data":{
* "orderId":123,
* "userId":148086,
* "goodsId":123
* }
* })
* @returnExample(true)
*
* @author zhangyingdi<zhangyingdi@eelly.net>
*
* @since 2018.06.28
*/
public function addOrderLikeNewAsync(array $data, UidDTO $user = null)
{
return EellyClient::request('order/like', 'addOrderLikeNew', false, $data, $user);
}
/**
* @return self
*/
public static function getInstance(): self
{
static $instance;
if (null === $instance) {
$instance = new self();
}
return $instance;
}
}
|
Java
|
#region "Copyright"
/*
FOR FURTHER DETAILS ABOUT LICENSING, PLEASE VISIT "LICENSE.txt" INSIDE THE SAGEFRAME FOLDER
*/
#endregion
#region "References"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using SageFrame.Web.Utilities;
#endregion
namespace SageFrame.Core.TemplateManagement
{
/// <summary>
/// Manipulates the data needed for template.
/// </summary>
public class TemplateDataProvider
{
/// <summary>
/// Connects to database and returns list of template list.
/// </summary>
/// <param name="PortalID">Portal ID.</param>
/// <param name="UserName">User's name.</param>
/// <returns>List of template.</returns>
public static List<TemplateInfo> GetTemplateList(int PortalID, string UserName)
{
string sp = "[dbo].[sp_TemplateGetList]";
SQLHandler sagesql = new SQLHandler();
List<KeyValuePair<string, object>> ParamCollInput = new List<KeyValuePair<string, object>>();
ParamCollInput.Add(new KeyValuePair<string, object>("@PortalID", PortalID));
ParamCollInput.Add(new KeyValuePair<string, object>("@UserName", UserName));
List<TemplateInfo> lstTemplate = new List<TemplateInfo>();
SqlDataReader reader = null;
try
{
reader = sagesql.ExecuteAsDataReader(sp, ParamCollInput);
while (reader.Read())
{
TemplateInfo obj = new TemplateInfo();
obj.TemplateID = int.Parse(reader["TemplateID"].ToString());
obj.TemplateTitle = reader["TemplateTitle"].ToString();
obj.PortalID = int.Parse(reader["PortalID"].ToString());
obj.Author = reader["Author"].ToString();
obj.AuthorURL = reader["AuthorURL"].ToString();
obj.Description = reader["Description"].ToString();
lstTemplate.Add(obj);
}
reader.Close();
return lstTemplate;
}
catch (Exception ex)
{
throw (ex);
}
finally
{
if (reader != null)
{
reader.Close();
}
}
}
/// <summary>
/// Connects to database and adds template.
/// </summary>
/// <param name="obj">TemplateInfo object containing the template details.</param>
/// <returns>True if the template is added successfully.</returns>
public static bool AddTemplate(TemplateInfo obj)
{
string sp = "[dbo].[sp_TemplateAdd]";
SQLHandler sagesql = new SQLHandler();
List<KeyValuePair<string, object>> ParamCollInput = new List<KeyValuePair<string, object>>();
ParamCollInput.Add(new KeyValuePair<string, object>("@TemplateTitle", obj.TemplateTitle));
ParamCollInput.Add(new KeyValuePair<string, object>("@Author",obj.Author));
ParamCollInput.Add(new KeyValuePair<string, object>("@Description", obj.Description));
ParamCollInput.Add(new KeyValuePair<string, object>("@AuthorURL", obj.AuthorURL));
ParamCollInput.Add(new KeyValuePair<string, object>("@PortalID", obj.PortalID));
ParamCollInput.Add(new KeyValuePair<string, object>("@UserName", obj.AddedBy));
try
{
sagesql.ExecuteNonQuery(sp, ParamCollInput);
return true;
}
catch (Exception ex)
{
throw (ex);
}
}
}
}
|
Java
|
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
# import frappe
from frappe.model.document import Document
class WebPageBlock(Document):
pass
|
Java
|
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package cn.sharesdk.demo.utils;
import android.annotation.TargetApi;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore.Images.Media;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
@TargetApi(17)
public class ScreenShotListenManager {
private static final String TAG = "ScreenShotListenManager";
private static final String[] MEDIA_PROJECTIONS = new String[]{"_data", "datetaken"};
private static final String[] MEDIA_PROJECTIONS_API_16 = new String[]{"_data", "datetaken", "width", "height"};
private static final String[] KEYWORDS = new String[]{"screenshot", "screen_shot", "screen-shot", "screen shot", "screencapture",
"screen_capture", "screen-capture", "screen capture", "screencap", "screen_cap", "screen-cap", "screen cap"};
private static Point sScreenRealSize;
private final List<String> sHasCallbackPaths = new ArrayList();
private Context context;
private OnScreenShotListener listener;
private long startListenTime;
private MediaContentObserver internalObserver;
private MediaContentObserver externalObserver;
private final Handler uiHandler = new Handler(Looper.getMainLooper());
private ScreenShotListenManager(Context context) {
if(context == null) {
throw new IllegalArgumentException("The context must not be null.");
} else {
this.context = context;
if(sScreenRealSize == null) {
sScreenRealSize = this.getRealScreenSize();
if(sScreenRealSize != null) {
Log.d("ScreenShotListenManager", "Screen Real Size: " + sScreenRealSize.x + " * " + sScreenRealSize.y);
} else {
Log.w("ScreenShotListenManager", "Get screen real size failed.");
}
}
}
}
public static ScreenShotListenManager newInstance(Context context) {
assertInMainThread();
return new ScreenShotListenManager(context);
}
public void startListen() {
assertInMainThread();
this.sHasCallbackPaths.clear();
this.startListenTime = System.currentTimeMillis();
this.internalObserver = new MediaContentObserver(Media.INTERNAL_CONTENT_URI, this.uiHandler);
this.externalObserver = new MediaContentObserver(Media.EXTERNAL_CONTENT_URI, this.uiHandler);
this.context.getContentResolver().registerContentObserver(Media.INTERNAL_CONTENT_URI, false, this.internalObserver);
this.context.getContentResolver().registerContentObserver(Media.EXTERNAL_CONTENT_URI, false, this.externalObserver);
}
public void stopListen() {
assertInMainThread();
if(this.internalObserver != null) {
try {
this.context.getContentResolver().unregisterContentObserver(this.internalObserver);
} catch (Exception var3) {
var3.printStackTrace();
}
this.internalObserver = null;
}
if(this.externalObserver != null) {
try {
this.context.getContentResolver().unregisterContentObserver(this.externalObserver);
} catch (Exception var2) {
var2.printStackTrace();
}
this.externalObserver = null;
}
this.startListenTime = 0L;
this.sHasCallbackPaths.clear();
}
private void handleMediaContentChange(Uri contentUri) {
Cursor cursor = null;
try {
cursor = this.context.getContentResolver().query(contentUri, VERSION.SDK_INT < 16 ? MEDIA_PROJECTIONS : MEDIA_PROJECTIONS_API_16,
(String)null, (String[])null, "date_added desc limit 1");
if(cursor == null) {
Log.e("ScreenShotListenManager", "Deviant logic.");
return;
}
if(cursor.moveToFirst()) {
int e = cursor.getColumnIndex("_data");
int dateTakenIndex = cursor.getColumnIndex("datetaken");
int widthIndex = -1;
int heightIndex = -1;
if(VERSION.SDK_INT >= 16) {
widthIndex = cursor.getColumnIndex("width");
heightIndex = cursor.getColumnIndex("height");
}
String data = cursor.getString(e);
long dateTaken = cursor.getLong(dateTakenIndex);
boolean width = false;
boolean height = false;
int width1;
int height1;
if(widthIndex >= 0 && heightIndex >= 0) {
width1 = cursor.getInt(widthIndex);
height1 = cursor.getInt(heightIndex);
} else {
Point size = this.getImageSize(data);
width1 = size.x;
height1 = size.y;
}
this.handleMediaRowData(data, dateTaken, width1, height1);
return;
}
Log.d("ScreenShotListenManager", "Cursor no data.");
} catch (Exception var16) {
var16.printStackTrace();
return;
} finally {
if(cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
}
private Point getImageSize(String imagePath) {
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, options);
return new Point(options.outWidth, options.outHeight);
}
private void handleMediaRowData(String data, long dateTaken, int width, int height) {
if(this.checkScreenShot(data, dateTaken, width, height)) {
Log.d("ScreenShotListenManager", "ScreenShot: path = " + data + "; size = " + width + " * " + height + "; date = " + dateTaken);
if(this.listener != null && !this.checkCallback(data)) {
this.listener.onShot(data);
}
} else {
Log.w("ScreenShotListenManager", "Media content changed, but not screenshot: path = " + data + "; size = " + width + " * "
+ height + "; date = " + dateTaken);
}
}
private boolean checkScreenShot(String data, long dateTaken, int width, int height) {
long currentTime = System.currentTimeMillis() - dateTaken;
if(dateTaken >= this.startListenTime && currentTime <= 20000L) {
if(sScreenRealSize == null || width <= sScreenRealSize.x && height <= sScreenRealSize.y || height <= sScreenRealSize.x
&& width <= sScreenRealSize.y) {
if(TextUtils.isEmpty(data)) {
return false;
} else {
data = data.toLowerCase();
String[] var11 = KEYWORDS;
int var10 = KEYWORDS.length;
for(int var9 = 0; var9 < var10; var9++) {
String keyWork = var11[var9];
if(data.contains(keyWork)) {
return true;
}
}
return false;
}
} else {
return false;
}
} else {
return false;
}
}
private boolean checkCallback(String imagePath) {
if(this.sHasCallbackPaths.contains(imagePath)) {
return true;
} else {
if(this.sHasCallbackPaths.size() >= 20) {
for(int i = 0; i < 5; i++) {
this.sHasCallbackPaths.remove(0);
}
}
this.sHasCallbackPaths.add(imagePath);
return false;
}
}
private Point getRealScreenSize() {
Point screenSize = null;
try {
screenSize = new Point();
WindowManager e = (WindowManager)this.context.getSystemService("window");
Display defaultDisplay = e.getDefaultDisplay();
if(VERSION.SDK_INT >= 17) {
defaultDisplay.getRealSize(screenSize);
} else {
try {
Method e1 = Display.class.getMethod("getRawWidth", new Class[0]);
Method getRawH = Display.class.getMethod("getRawHeight", new Class[0]);
screenSize.set(((Integer)e1.invoke(defaultDisplay, new Object[0])).intValue(),
((Integer)getRawH.invoke(defaultDisplay, new Object[0])).intValue());
} catch (Exception var6) {
screenSize.set(defaultDisplay.getWidth(), defaultDisplay.getHeight());
var6.printStackTrace();
}
}
} catch (Exception var7) {
var7.printStackTrace();
}
return screenSize;
}
public void setListener(ScreenShotListenManager.OnScreenShotListener listener) {
this.listener = listener;
}
private static void assertInMainThread() {
if(Looper.myLooper() != Looper.getMainLooper()) {
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
String methodMsg = null;
if(elements != null && elements.length >= 4) {
methodMsg = elements[3].toString();
}
throw new IllegalStateException("Call the method must be in main thread: " + methodMsg);
}
}
private class MediaContentObserver extends ContentObserver {
private Uri contentUri;
public MediaContentObserver(Uri contentUri, Handler handler) {
super(handler);
this.contentUri = contentUri;
}
public void onChange(boolean selfChange) {
super.onChange(selfChange);
handleMediaContentChange(this.contentUri);
}
}
public interface OnScreenShotListener {
void onShot(String var1);
}
}
|
Java
|
var Path = require('path');
var Hapi = require('hapi');
var server = new Hapi.Server();
var port = process.env.PORT || 5000;
server.connection({ port: port });
server.views({
engines: {
html: require('handlebars')
},
path: Path.join(__dirname, 'views')
});
server.route([
{ path: '/',
method: 'GET',
config: {
auth: false,
handler: function(request, reply) {
reply.view("index");
}
}
},
{
method: 'GET',
path: '/public/{param*}',
handler: {
directory: {
path: Path.normalize(__dirname + '/public')
}
}
}
]);
server.start(function(){
console.log('Static Server Listening on : http://127.0.0.1:' +port);
});
module.exports = server;
|
Java
|
//
// Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include <Atomic/Atomic3D/StaticModel.h>
#include <Atomic/Atomic3D/CustomGeometry.h>
#include <Atomic/Atomic3D/BillboardSet.h>
#include "JSAtomic3D.h"
namespace Atomic
{
static int StaticModel_SetMaterialIndex(duk_context* ctx) {
unsigned index = (unsigned) duk_require_number(ctx, 0);
Material* material = js_to_class_instance<Material>(ctx, 1, 0);
duk_push_this(ctx);
// event receiver
StaticModel* model = js_to_class_instance<StaticModel>(ctx, -1, 0);
model->SetMaterial(index, material);
return 0;
}
static int CustomGeometry_SetMaterialIndex(duk_context* ctx) {
unsigned index = (unsigned)duk_require_number(ctx, 0);
Material* material = js_to_class_instance<Material>(ctx, 1, 0);
duk_push_this(ctx);
// event receiver
CustomGeometry* geometry = js_to_class_instance<CustomGeometry>(ctx, -1, 0);
geometry->SetMaterial(index, material);
return 0;
}
static int BillboardSet_GetBillboard(duk_context* ctx)
{
duk_push_this(ctx);
BillboardSet* billboardSet = js_to_class_instance<BillboardSet>(ctx, -1, 0);
unsigned index = (unsigned)duk_to_number(ctx, 0);
Billboard* billboard = billboardSet->GetBillboard(index);
js_push_class_object_instance(ctx, billboard, "Billboard");
return 1;
}
void jsapi_init_atomic3d(JSVM* vm)
{
duk_context* ctx = vm->GetJSContext();
js_class_get_prototype(ctx, "Atomic", "StaticModel");
duk_push_c_function(ctx, StaticModel_SetMaterialIndex, 2);
duk_put_prop_string(ctx, -2, "setMaterialIndex");
duk_pop(ctx); // pop AObject prototype
js_class_get_prototype(ctx, "Atomic", "CustomGeometry");
duk_push_c_function(ctx, CustomGeometry_SetMaterialIndex, 2);
duk_put_prop_string(ctx, -2, "setMaterialIndex");
duk_pop(ctx); // pop AObject prototype
js_class_get_prototype(ctx, "Atomic", "BillboardSet");
duk_push_c_function(ctx, BillboardSet_GetBillboard, 1);
duk_put_prop_string(ctx, -2, "getBillboard");
duk_pop(ctx); // pop AObject prototype
}
}
|
Java
|
//-----------------------------------------------------------------------------
// Verve
// Copyright (C) - Violent Tulip
//-----------------------------------------------------------------------------
function VControllerPropertyList::CreateInspectorGroup( %this, %targetStack )
{
%baseGroup = Parent::CreateInspectorGroup( %this, %targetStack );
if ( %baseGroup.getClassName() !$= "ScriptGroup" )
{
// Temp Store.
%temp = %baseGroup;
// Create SimSet.
%baseGroup = new SimSet();
// Add Original Control.
%baseGroup.add( %temp );
}
// Create Data Table Group.
%groupRollout = %targetStack.CreatePropertyRollout( "VController DataTable" );
%propertyStack = %groupRollout.Stack;
// Reference.
%propertyStack.InternalName = "DataTableStack";
// Store.
%baseGroup.add( %groupRollout );
// Return.
return %baseGroup;
}
function VControllerPropertyList::InspectObject( %this, %object )
{
if ( !%object.isMemberOfClass( "VController" ) )
{
// Invalid Object.
return;
}
// Default Inspect.
Parent::InspectObject( %this, %object );
// Update Data Table.
%dataTableStack = %this.ControlCache.findObjectByInternalName( "DataTableStack", true );
if ( !isObject( %dataTableStack ) )
{
// Invalid Table.
return;
}
// Clear Stack.
while ( %dataTableStack.getCount() > 1 )
{
// Delete Object.
%dataTableStack.getObject( 1 ).delete();
}
%dataFieldCount = %object.getDataFieldCount();
for ( %i = 0; %i < %dataFieldCount; %i++ )
{
// Add To List.
%dataFieldList = trim( %dataFieldList SPC %object.getDataFieldName( %i ) );
}
// Sort Word List.
%dataFieldList = sortWordList( %dataFieldList );
for ( %i = 0; %i < %dataFieldCount; %i++ )
{
// Fetch Field Name.
%dataFieldName = getWord( %dataFieldList, %i );
// Create Field.
VerveEditor::CreateField( %dataTableStack, %dataFieldName, "Data" );
}
// Create Add Field.
VerveEditor::CreateAddDataField( %dataTableStack );
// Update.
%dataTableStack.InspectObject( %object );
}
function VController::DisplayContextMenu( %this, %x, %y )
{
%contextMenu = $VerveEditor::VController::ContextMenu;
if ( !isObject( %contextMenu ) )
{
%contextMenu = new PopupMenu()
{
SuperClass = "VerveWindowMenu";
IsPopup = true;
Label = "VControllerContextMenu";
Position = 0;
Item[0] = "Add Group" TAB "";
Item[1] = "" TAB "";
Item[2] = "Cu&t" TAB "" TAB "";
Item[3] = "&Copy" TAB "" TAB "";
Item[4] = "&Paste" TAB "" TAB "VerveEditor::Paste();";
Item[5] = "" TAB "";
Item[6] = "&Delete" TAB "" TAB "";
PasteIndex = 4;
};
%contextMenu.Init();
// Disable Cut, Copy & Delete.
%contextMenu.enableItem( 2, false );
%contextMenu.enableItem( 3, false );
%contextMenu.enableItem( 6, false );
// Cache.
$VerveEditor::VController::ContextMenu = %contextMenu;
}
// Remove Add Menu.
%contextMenu.removeItem( %contextMenu.AddIndex );
// Insert Menu.
%contextMenu.insertSubMenu( %contextMenu.AddIndex, getField( %contextMenu.Item[0], 0 ), %this.GetAddGroupMenu() );
// Enable/Disable Pasting.
%contextMenu.enableItem( %contextMenu.PasteIndex, VerveEditor::CanPaste() );
if ( %x $= "" || %y $= "" )
{
%position = %this.getGlobalPosition();
%extent = %this.getExtent();
%x = getWord( %position, 0 ) + getWord( %extent, 0 );
%y = getWord( %position, 1 );
}
// Display.
%contextMenu.showPopup( VerveEditorWindow, %x, %y );
}
function VController::GetAddGroupMenu( %this )
{
%contextMenu = $VerveEditor::VController::ContextMenu[%this.getClassName()];
if ( !isObject( %contextMenu ) )
{
%customTemplateMenu = new PopupMenu()
{
Class = "VerveCustomTemplateMenu";
SuperClass = "VerveWindowMenu";
IsPopup = true;
Label = "VGroupAddGroupMenu";
Position = 0;
};
%customTemplateMenu.Init();
%contextMenu = new PopupMenu()
{
SuperClass = "VerveWindowMenu";
IsPopup = true;
Label = "VGroupAddGroupMenu";
Position = 0;
Item[0] = "Add Camera Group" TAB "" TAB "VerveEditor::AddGroup(\"VCameraGroup\");";
Item[1] = "Add Director Group" TAB "" TAB "VerveEditor::AddGroup(\"VDirectorGroup\");";
Item[2] = "Add Light Object Group" TAB "" TAB "VerveEditor::AddGroup(\"VLightObjectGroup\");";
Item[3] = "Add Particle Effect Group" TAB "" TAB "VerveEditor::AddGroup(\"VParticleEffectGroup\");";
Item[4] = "Add Scene Object Group" TAB "" TAB "VerveEditor::AddGroup(\"VSceneObjectGroup\");";
Item[5] = "Add Spawn Sphere Group" TAB "" TAB "VerveEditor::AddGroup(\"VSpawnSphereGroup\");";
Item[6] = "" TAB "";
Item[7] = "Add Custom Group" TAB %customTemplateMenu;
DirectorIndex = 1;
CustomIndex = 7;
CustomMenu = %customTemplateMenu;
};
%contextMenu.Init();
// Refresh Menu.
%customTemplateMenu = %contextMenu.CustomMenu;
if ( %customTemplateMenu.getItemCount() == 0 )
{
// Remove Item.
%contextMenu.removeItem( %contextMenu.CustomIndex );
// Add Dummy.
%contextMenu.insertItem( %contextMenu.CustomIndex, getField( %contextMenu.Item[%contextMenu.CustomIndex], 0 ) );
// Disable Custom Menu.
%contextMenu.enableItem( %contextMenu.CustomIndex, false );
}
// Cache.
$VerveEditor::VController::ContextMenu[%this.getClassName()] = %contextMenu;
}
// Enable / Disable Director Group.
%contextMenu.enableItem( %contextMenu.DirectorIndex, %this.CanAdd( "VDirectorGroup" ) );
// Return Menu.
return %contextMenu;
}
|
Java
|
module Cms::PublicFilter
extend ActiveSupport::Concern
include Cms::PublicFilter::Node
include Cms::PublicFilter::Page
include Mobile::PublicFilter
include Kana::PublicFilter
included do
rescue_from StandardError, with: :rescue_action
before_action :set_site
before_action :set_request_path
#before_action :redirect_slash, if: ->{ request.env["REQUEST_PATH"] =~ /\/[^\.]+[^\/]$/ }
before_action :deny_path
before_action :parse_path
before_action :compile_scss
before_action :x_sendfile, if: ->{ filters.blank? }
end
public
def index
if @cur_path =~ /\.p[1-9]\d*\.html$/
page = @cur_path.sub(/.*\.p(\d+)\.html$/, '\\1')
params[:page] = page.to_i
@cur_path.sub!(/\.p\d+\.html$/, ".html")
end
if @html =~ /\.part\.html$/
part = find_part(@html)
raise "404" unless part
@cur_path = params[:ref] || "/"
send_part render_part(part)
elsif page = find_page(@cur_path)
self.response = render_page(page)
send_page page
elsif node = find_node(@cur_path)
self.response = render_node(node)
send_page node
else
raise "404"
end
end
private
def set_site
host = request.env["HTTP_X_FORWARDED_HOST"] || request.env["HTTP_HOST"]
@cur_site ||= SS::Site.find_by_domain host
raise "404" if !@cur_site
end
def set_request_path
@cur_path ||= request.env["REQUEST_PATH"]
cur_path = @cur_path.dup
filter_methods = self.class.private_instance_methods.select { |m| m =~ /^set_request_path_with_/ }
filter_methods.each do |name|
send(name)
break if cur_path != @cur_path
end
end
def redirect_slash
return unless request.get?
redirect_to "#{request.path}/"
end
def deny_path
raise "404" if @cur_path =~ /^\/sites\/.\//
end
def parse_path
@cur_path.sub!(/\/$/, "/index.html")
@html = @cur_path.sub(/\.\w+$/, ".html")
@file = File.join(@cur_site.path, @cur_path)
end
def compile_scss
return if @cur_path !~ /\.css$/
return if @cur_path =~ /\/_[^\/]*$/
return unless Fs.exists? @scss = @file.sub(/\.css$/, ".scss")
css_mtime = Fs.exists?(@file) ? Fs.stat(@file).mtime : 0
return if Fs.stat(@scss).mtime.to_i <= css_mtime.to_i
css = ""
begin
opts = Rails.application.config.sass
sass = Sass::Engine.new Fs.read(@scss), filename: @scss, syntax: :scss, cache: false,
load_paths: opts.load_paths[1..-1],
style: :compressed,
debug_info: false
css = sass.render
rescue Sass::SyntaxError => e
msg = e.backtrace[0].sub(/.*?\/_\//, "")
msg = "[#{msg}]\\A #{e}".gsub('"', '\\"')
css = "body:before { position: absolute; top: 8px; right: 8px; display: block;"
css << " padding: 4px 8px; border: 1px solid #b88; background-color: #fff;"
css << " color: #822; font-size: 85%; font-family: tahoma, sans-serif; line-height: 1.6;"
css << " white-space: pre; z-index: 9; content: \"#{msg}\"; }"
end
Fs.write @file, css
end
def x_sendfile(file = @file)
return unless Fs.file?(file)
response.headers["Expires"] = 1.days.from_now.httpdate if file =~ /\.(css|js|gif|jpg|png)$/
response.headers["Last-Modified"] = CGI::rfc1123_date(Fs.stat(file).mtime)
if Fs.mode == :file
send_file file, disposition: :inline, x_sendfile: true
else
send_data Fs.binread(file), type: Fs.content_type(file)
end
end
def send_part(body)
respond_to do |format|
format.html { render inline: body, layout: false }
format.json { render json: body.to_json }
end
end
def send_page(page)
raise "404" unless response
if response.content_type == "text/html" && page.layout
render inline: render_layout(page.layout), layout: (request.xhr? ? false : "cms/page")
else
@_response_body = response.body
end
end
def rescue_action(e = nil)
return render_error(e, status: e.to_s.to_i) if e.to_s =~ /^\d+$/
return render_error(e, status: 404) if e.is_a? Mongoid::Errors::DocumentNotFound
return render_error(e, status: 404) if e.is_a? ActionController::RoutingError
raise e
end
def render_error(e, opts = {})
# for development
raise e if Rails.application.config.consider_all_requests_local
self.response = ActionDispatch::Response.new
status = opts[:status].presence || 500
render status: status, file: error_template(status), layout: false
end
def error_template(status)
if @cur_site
file = "#{@cur_site.path}/#{status}.html"
return file if Fs.exists?(file)
end
file = "#{Rails.public_path}/#{status}.html"
Fs.exists?(file) ? file : "#{Rails.public_path}/500.html"
end
end
|
Java
|
<h1>Home</h1>
<p>You're logged in!!</p>
<p><a href="#/login">Logout</a></a></p>
|
Java
|
// Copyright 2019 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package queue
import (
"errors"
"strings"
"code.gitea.io/gitea/modules/log"
"github.com/go-redis/redis"
)
// RedisQueueType is the type for redis queue
const RedisQueueType Type = "redis"
// RedisQueueConfiguration is the configuration for the redis queue
type RedisQueueConfiguration struct {
ByteFIFOQueueConfiguration
RedisByteFIFOConfiguration
}
// RedisQueue redis queue
type RedisQueue struct {
*ByteFIFOQueue
}
// NewRedisQueue creates single redis or cluster redis queue
func NewRedisQueue(handle HandlerFunc, cfg, exemplar interface{}) (Queue, error) {
configInterface, err := toConfig(RedisQueueConfiguration{}, cfg)
if err != nil {
return nil, err
}
config := configInterface.(RedisQueueConfiguration)
byteFIFO, err := NewRedisByteFIFO(config.RedisByteFIFOConfiguration)
if err != nil {
return nil, err
}
byteFIFOQueue, err := NewByteFIFOQueue(RedisQueueType, byteFIFO, handle, config.ByteFIFOQueueConfiguration, exemplar)
if err != nil {
return nil, err
}
queue := &RedisQueue{
ByteFIFOQueue: byteFIFOQueue,
}
queue.qid = GetManager().Add(queue, RedisQueueType, config, exemplar)
return queue, nil
}
type redisClient interface {
RPush(key string, args ...interface{}) *redis.IntCmd
LPop(key string) *redis.StringCmd
LLen(key string) *redis.IntCmd
SAdd(key string, members ...interface{}) *redis.IntCmd
SRem(key string, members ...interface{}) *redis.IntCmd
SIsMember(key string, member interface{}) *redis.BoolCmd
Ping() *redis.StatusCmd
Close() error
}
var _ (ByteFIFO) = &RedisByteFIFO{}
// RedisByteFIFO represents a ByteFIFO formed from a redisClient
type RedisByteFIFO struct {
client redisClient
queueName string
}
// RedisByteFIFOConfiguration is the configuration for the RedisByteFIFO
type RedisByteFIFOConfiguration struct {
Network string
Addresses string
Password string
DBIndex int
QueueName string
}
// NewRedisByteFIFO creates a ByteFIFO formed from a redisClient
func NewRedisByteFIFO(config RedisByteFIFOConfiguration) (*RedisByteFIFO, error) {
fifo := &RedisByteFIFO{
queueName: config.QueueName,
}
dbs := strings.Split(config.Addresses, ",")
if len(dbs) == 0 {
return nil, errors.New("no redis host specified")
} else if len(dbs) == 1 {
fifo.client = redis.NewClient(&redis.Options{
Network: config.Network,
Addr: strings.TrimSpace(dbs[0]), // use default Addr
Password: config.Password, // no password set
DB: config.DBIndex, // use default DB
})
} else {
fifo.client = redis.NewClusterClient(&redis.ClusterOptions{
Addrs: dbs,
})
}
if err := fifo.client.Ping().Err(); err != nil {
return nil, err
}
return fifo, nil
}
// PushFunc pushes data to the end of the fifo and calls the callback if it is added
func (fifo *RedisByteFIFO) PushFunc(data []byte, fn func() error) error {
if fn != nil {
if err := fn(); err != nil {
return err
}
}
return fifo.client.RPush(fifo.queueName, data).Err()
}
// Pop pops data from the start of the fifo
func (fifo *RedisByteFIFO) Pop() ([]byte, error) {
data, err := fifo.client.LPop(fifo.queueName).Bytes()
if err == nil || err == redis.Nil {
return data, nil
}
return data, err
}
// Close this fifo
func (fifo *RedisByteFIFO) Close() error {
return fifo.client.Close()
}
// Len returns the length of the fifo
func (fifo *RedisByteFIFO) Len() int64 {
val, err := fifo.client.LLen(fifo.queueName).Result()
if err != nil {
log.Error("Error whilst getting length of redis queue %s: Error: %v", fifo.queueName, err)
return -1
}
return val
}
func init() {
queuesMap[RedisQueueType] = NewRedisQueue
}
|
Java
|
/**
* @file fly_id3.h
*
* Declaration of the pianobarfly ID3 helper functions. These are helper
* functions to assist with creating an ID3 tag using the libid3tag library.
*/
/*
* Copyright (c) 2011
* Author: Ted Jordan
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef _FLY_ID3_H
#define _FLY_ID3_H
#if defined ENABLE_MAD && defined ENABLE_ID3TAG
#include <id3tag.h>
#include <stdint.h>
/**
* Creates and attaches an image frame with the cover art to the given tag.
*
* @param tag A pointer to the tag.
* @param cover_art A buffer containing the cover art image.
* @param cover_size The size of the buffer.
* @param settings A pointer to the application settings structure.
* @return If successful 0 is returned otherwise -1 is returned.
*/
int BarFlyID3AddCover(struct id3_tag* tag, uint8_t const* cover_art,
size_t cover_size, BarSettings_t const* settings);
/**
* Creates and attaches a frame of the given type to the tag with the given
* string value. All values are written to the string list field of the frame.
*
* @param tag A pointer to the tag.
* @param type A string containing the frame type, ex. TIT2.
* @param value A string containing the value.
* @param settings A pointer to the application settings structure.
* @return If the frame was successfully added 0 is returned, otherwise -1 is
* returned.
*/
int BarFlyID3AddFrame(struct id3_tag* tag, char const* type,
char const* value, BarSettings_t const* settings);
/**
* Physically writes the ID3 tag to the audio file. A temproary file is create
* into which the tag is written. After which the contents of the audio file is
* copied into it. Once the temporary file is complete the audio file is
* overwritten with it.
*
* @param file_path A pointer to a string containing the path to the audio file.
* @param tag A pointer to the tag structure to be written to the file.
* @param settings A pointer to the application settings structure.
* @return If successful 0 is returned otherwise -1 is returned.
*/
int BarFlyID3WriteFile(char const* file_path, struct id3_tag const* tag,
BarSettings_t const* settings);
#endif
#endif
// vim: set noexpandtab:
|
Java
|
package velir.intellij.cq5.util;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import java.util.ArrayList;
import java.util.List;
/**
* Utility class for helping work with Repository objects.
*/
public class RepositoryUtils {
/**
* Hide default constructor for true static class.
*/
private RepositoryUtils() {
}
public static List<String> getAllNodeTypeNames(Session session) throws RepositoryException {
//get our child nodeTypes from our root
NodeIterator nodeTypes = getAllNodeTypes(session);
//go through each node type and pull out the name
List<String> nodeTypeNames = new ArrayList<String>();
while (nodeTypes.hasNext()) {
Node node = nodeTypes.nextNode();
nodeTypeNames.add(node.getName());
}
//return our node type names
return nodeTypeNames;
}
/**
* Will get all the nodes that represent the different node types.
*
* @param session Repository session to use for pulling out this information.
* @return
* @throws RepositoryException
*/
public static NodeIterator getAllNodeTypes(Session session) throws RepositoryException {
//get our node types root
Node nodeTypesRoot = session.getNode("/jcr:system/jcr:nodeTypes");
//get our child nodeTypes from our root
return nodeTypesRoot.getNodes();
}
}
|
Java
|
<html>
<META HTTP-EQUIV=Content-Type Content="text/html; charset=utf8">
<!-- Mirrored from lis.ly.gov.tw/lghtml/lawstat/version2/02409/0240996011200.htm by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 24 Mar 2013 09:19:03 GMT -->
<head><title>法編號:02409 版本:096011200</title>
<link rel="stylesheet" type="text/css" href="../../version.css" >
</HEAD>
<body><left>
<table><tr><td><FONT COLOR=blue SIZE=5>有線廣播電視法(02409)</font>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td>
<tr><td align=left valign=top>
<a href=0240982071600.html target=law02409><nobr><font size=2>中華民國 82 年 7 月 16 日</font></nobr></a>
</td>
<td valign=top><font size=2>制定71條</font></td>
<tr><td align=left valign=top><nobr><font size=2>中華民國 82 年 8 月 11 日公布</font></nobr></td>
<tr><td align=left valign=top>
<a href=0240988011500.html target=law02409><nobr><font size=2>中華民國 88 年 1 月 15 日</font></nobr></a>
</td>
<td valign=top><font size=2>修正前[有線電視法]為本法<br>
並修正全文76條</font></td>
<tr><td align=left valign=top><nobr><font size=2>中華民國 88 年 2 月 3 日公布</font></nobr></td>
<tr><td align=left valign=top>
<a href=0240988123000.html target=law02409><nobr><font size=2>中華民國 88 年 12 月 30 日</font></nobr></a>
</td>
<td valign=top><font size=2>修正第3條</font></td>
<tr><td align=left valign=top><nobr><font size=2>中華民國 89 年 1 月 19 日公布</font></nobr></td>
<tr><td align=left valign=top>
<a href=0240990051800.html target=law02409><nobr><font size=2>中華民國 90 年 5 月 18 日</font></nobr></a>
</td>
<td valign=top><font size=2>修正第19, 51, 63條</font></td>
<tr><td align=left valign=top><nobr><font size=2>中華民國 90 年 5 月 30 日公布</font></nobr></td>
<tr><td align=left valign=top>
<a href=0240991122700.html target=law02409><nobr><font size=2>中華民國 91 年 12 月 27 日</font></nobr></a>
</td>
<td valign=top><font size=2>修正第16, 19, 23, 39條</font></td>
<tr><td align=left valign=top><nobr><font size=2>中華民國 92 年 1 月 15 日公布</font></nobr></td>
<tr><td align=left valign=top>
<a href=0240992120900.html target=law02409><nobr><font size=2>中華民國 92 年 12 月 9 日</font></nobr></a>
</td>
<td valign=top><font size=2>修正第19, 20, 24, 68條<br>
增訂第37之1條</font></td>
<tr><td align=left valign=top><nobr><font size=2>中華民國 92 年 12 月 24 日公布</font></nobr></td>
<tr><td align=left valign=top>
<a href=0240996011200.html target=law02409><nobr><font size=2>中華民國 96 年 1 月 12 日</font></nobr></a>
</td>
<td valign=top><font size=2>增訂第35之1條</font></td>
<tr><td align=left valign=top><nobr><font size=2>中華民國 96 年 1 月 29 日公布</font></nobr></td>
</table></table></table></table>
<p><table><tr><td><font color=blue size=4>民國96年1月12日</font></td>
<td><a href=http://lis.ly.gov.tw/lghtml/lawstat/reason2/0240996011200.htm target=reason><font size=2>立法理由</font></a></td>
<td><a href=http://lis.ly.gov.tw/lgcgi/lglawproc?0240996011200 target=proc><font size=2>立法紀錄</font></a></td>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第一章 總則</font>
<table><tr><td> </td><td><font color=8000ff>第一條</font>
<font size=2>(立法目的)</font>
<table><tr><td> </td>
<td>
為促進有線廣播電視事業之健全發展,保障公眾視聽之權益,增進社會福祉,特制定本法。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二條</font>
<font size=2>(用辭定義)</font>
<table><tr><td> </td>
<td>
本法用辭定義如下:<br>
一、有線廣播電視:指以設置纜線方式傳播影像、聲音供公眾直接視、聽。<br>
二、有線廣播電視系統(以下簡稱系統):指有線廣播電視之傳輸網路及包括纜線、微波、衛星地面接收等設備。<br>
三、有線廣播電視系統經營者(以下簡稱系統經營者):指依法核准經營有線廣播電視者。<br>
四、頻道供應者:指以節目及廣告為內容,將之以一定名稱授權予有線電視系統經營者播送之供應事業,其以自己或代理名義為之者,亦屬之。<br>
五、基本頻道:指訂戶定期繳交基本費用,始可視、聽之頻道。<br>
六、付費頻道:指基本頻道以外,須額外付費,始可視、聽之頻道。<br>
七、計次付費節目:指按次付費,始可視、聽之節目。<br>
八、鎖碼:指需經特殊解碼程序始得視、聽節目之技術。<br>
九、頭端:指接收、處理、傳送有線廣播、電視信號,並將其播送至分配線網路之設備及其所在之場所。<br>
十、幹線網路:指連接系統經營者之頭端至頭端間傳輸有線廣播、電視信號之網路。<br>
十一、分配線網路:指連接頭端至訂戶間之纜線網路及設備。<br>
十二、插播式字幕:指另經編輯製作而在電視螢幕上展現,且非屬於原有播出內容之文字或圖形。<br>
十三、有線廣播電視節目(以下簡稱節目):指系統經營者播送之影像、聲音,內容不涉及廣告者。<br>
十四、有線廣播電視廣告(以下簡稱廣告):指系統經營者播送之影像、聲音,內容為推廣商品、觀念、服務或形象者。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三條</font>
<font size=2>(主管機關)</font>
<table><tr><td> </td>
<td>
本法所稱主管機關:在中央為行政院新聞局(以下簡稱新聞局);在直轄市為直轄市政府;在縣(市)為縣(市)政府。<br>
有線廣播電視系統工程技術管理之主管機關為交通部。<br>
前項有關工程技術管理之規則,由交通部定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四條</font>
<font size=2>(經營電信業務之規定)</font>
<table><tr><td> </td>
<td>
系統經營者經營電信業務,應依電信法相關規定辦理。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五條</font>
<font size=2>(幹線網路之鋪設)</font>
<table><tr><td> </td>
<td>
系統經營者自行設置之網路,其屬鋪設者,向路權管理機關申請;其屬附掛者,向電信、電業等機構申請。經許可籌設有線廣播電視者,亦同。<br>
系統經營者前項網路之鋪設,得承租現有之地下管溝及終端設備;其鋪設網路及附掛網路應依有關法令規定辦理。<br>
中央主管機關應會同交通部協助解決偏遠地區幹線網路之設置。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六條</font>
<font size=2>(網路通過他人土地或建物之鋪設方法、通知及變更鋪設)</font>
<table><tr><td> </td>
<td>
前條第一項網路非通過他人土地或建築物不能鋪設,或雖能鋪設需費過鉅者,得通過他人土地或建築物鋪設之。但應擇其損害最少之處所及方法為之,並應為相當之補償。<br>
前項網路之鋪設,應於施工三十日前以書面通知土地、建築物所有人或占有人。<br>
依第一項規定鋪設網路後,如情事變更時,土地、建築物所有人或占有人得請求變更其鋪設。<br>
對於前三項情形有異議者,得申請轄區內調解委員會調解之或逕行提起民事訴訟。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第七條</font>
<font size=2>(天然災害或緊急事故之應變)</font>
<table><tr><td> </td>
<td>
遇有天然災害或緊急事故時,主管機關為維護公共安全與公眾福利,得通知系統經營者停止播送節目,或指定其播送特定之節目或訊息。<br>
前項原因消滅後,主管機關應即通知該系統經營者回復原狀繼續播送。<br>
第一項之天然災害及緊急事故應變辦理,由中央主管機關定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第二章 有線廣播電視審議委員會</font>
<table><tr><td> </td><td><font color=8000ff>第八條</font>
<font size=2>(審議委員會及審議事項)</font>
<table><tr><td> </td>
<td>
中央主管機關設有線廣播電視審議委員會(以下簡稱審議委員會),審議下列事項:<br>
一、有線廣播電視籌設之許可或撤銷許可。<br>
二、有線廣播電視營運之許可或撤銷許可。<br>
三、執行營運計畫之評鑑。<br>
四、系統經營者與頻道供應者間節目使用費用及其他爭議之調處。<br>
五、系統經營者間爭議之調處。<br>
六、其他依本法規定或經中央主管機關提請審議之事項。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第九條</font>
<font size=2>(審議委員會之組成)</font>
<table><tr><td> </td>
<td>
審議委員會置委員十三人至十五人,由下列人員組成之:<br>
一、專家學者十人至十二人。<br>
二、交通部、新聞局、行政院消費者保護委員會代表各一人。<br>
審議委員會審議相關地區議案時,應邀請各該直轄市或縣(市)政府代表一人出席。出席代表之職權與審議委員相同。<br>
審議委員中,同一政黨者不得超過二分之一;其擔任委員期間不得參加政黨活動。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十條</font>
<font size=2>(審議委員之產生及任期)</font>
<table><tr><td> </td>
<td>
前條第一項第一款之委員由行政院院長遴聘,並報請立法院備查,聘期三年,期滿得續聘之,但續聘以一次為限。聘期未滿之委員因辭職、死亡或因故無法執行職務時,應予解聘,並得另聘其他人選繼任,至原聘期任滿時為止。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十一條</font>
<font size=2>(審議會之主席)</font>
<table><tr><td> </td>
<td>
審議委員會開會時由委員互推一人為主席,主持會議之進行。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十二條</font>
<font size=2>(開議及決議人數)</font>
<table><tr><td> </td>
<td>
審議委員會應有五分之三以上委員出席,始得開議,以出席委員過半數之同意,始得決議。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十三條</font>
<font size=2>(決議方式)</font>
<table><tr><td> </td>
<td>
審議委員會之決議方式,由審議委員會討論後決定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十四條</font>
<font size=2>(審議委員之自行迴避)</font>
<table><tr><td> </td>
<td>
審議委員會委員應本公正客觀之立場行使職權,有下列各款情形之一者,應自行迴避:<br>
一、審議委員會委員或其配偶、前配偶或未婚配偶,為申請經營有線廣播電視之董事、監察人或經理人者。<br>
二、審議委員會委員與申請經營有線廣播電視者之董事、監察人或經理人為五親等內之血親、三親等內之姻親或曾有此親屬關係者。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十五條</font>
<font size=2>(申請迴避及裁決)</font>
<table><tr><td> </td>
<td>
申請經營有線廣播電視者對於審議委員會委員,認為有偏頗之虞或其他不適格之原因,得申請迴避。<br>
前項申請由主席裁決之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十六條</font>
<font size=2>(未自行迴避時所為決議之撤銷)</font>
<table><tr><td> </td>
<td>
審議委員會委員應自行迴避而不迴避時,中央主管機關於會議決議後一個月內,得逕行或應利害關係人之申請,撤銷該會議所為之決議。其經籌設許可或營運許可者,中央主管機關應撤銷其許可,並註銷其許可證。<br>
審議委員會對前項撤銷之事項,應重行審議及決議。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十七條</font>
<font size=2>(審議規則之訂定)</font>
<table><tr><td> </td>
<td>
審議委員會之審議規則,由中央主管機關定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第三章 營運管理</font>
<table><tr><td> </td><td><font color=8000ff>第十八條</font>
<font size=2>(申請許可)</font>
<table><tr><td> </td>
<td>
有線廣播電視之籌設、營運,應申請中央主管機關許可。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十九條</font>
<font size=2>(經營者身分之限制)</font>
<table><tr><td> </td>
<td>
系統經營者之組織,以股份有限公司為限。<br>
外國人直接及間接持有系統經營者之股份,合計應低於該系統經營者已發行股份總數百分之六十,外國人直接持有者,以法人為限,且合計應低於該系統經營者已發行股份總數百分之二十。<br>
系統經營者最低實收資本額,由中央主管機關定之。<br>
政府、政黨、其捐助成立之財團法人及其受託人不得直接、間接投資系統經營者。<br>
本法修正施行前,政府、政黨、其捐助成立之財團法人及其受託人有不符前項所定情形者,應自本法修正施行之日起二年內改正。<br>
系統經營者不得播送有候選人參加,且由政府出資或製作之節目、短片及廣告;政府出資或製作以候選人為題材之節目、短片及廣告,亦同。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十條</font>
<font size=2>(本國籍董事、政黨公職人員之限制)</font>
<table><tr><td> </td>
<td>
系統經營者具有中華民國國籍之董事,不得少於董事人數三分之二;監察人,亦同。<br>
董事長應具有中華民國國籍。<br>
政黨黨務工作人員、政務人員及選任公職人員不得投資系統經營者;其配偶、二親等血親、直系姻親投資同一系統經營者,其持有之股份,合計不得逾該事業已發行股份總數百分之一。本法修正施行前,系統經營者有不符規定者,應自本法修正施行之日起二年內改正。<br>
政府、政黨、政黨黨務工作人員及選任公職人員不得擔任系統經營者之發起人、董事、監察人或經理人。本法修正施行前已擔任者,系統經營者應自本法修正施行之日起六個月內解除其職務。<br>
前二項所稱政黨黨務工作人員、政務人員及選任公職人員之範圍,於本法施行細則定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十一條</font>
<font size=2>(系統經營者與其關係企業及直接間接控制者間之限制)</font>
<table><tr><td> </td>
<td>
系統經營者與其關係企業及直接、間接控制之系統經營者不得有下列情形之一:<br>
一、訂戶數合計超過全國總訂戶數三分之一。<br>
二、超過同一行政區域系統經營者總家數二分之一。但同一行政區域只有一系統經營者,不在此限。<br>
三、超過全國系統經營者總家數三分之一。<br>
前項全國總訂戶數、同一行政區域系統經營者總家數及全國系統經營者總家數,由中央主管機關公告之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十二條</font>
<font size=2>(營運計畫之載明及提出)</font>
<table><tr><td> </td>
<td>
申請有線廣播電視之籌設,應填具申請書連同營運計畫,於公告期間內向中央主管機關提出。<br>
營運計畫應載明下列事項:<br>
一、有線廣播電視經營地區。<br>
二、系統設置時程及預定開播時間。<br>
三、財務結構。<br>
四、組織架構。<br>
五、頻道之規劃及其類型。<br>
六、自製節目製播計畫。<br>
七、收費標準及計算方式。<br>
八、訂戶服務。<br>
九、服務滿意度及頻道收視意願調查計畫。<br>
十、工程技術及設備說明。<br>
十一、業務推展計畫。<br>
十二、人材培訓計畫。<br>
十三、技術發展計畫。<br>
十四、董事、監察人、經理人,或發起人之姓名(名稱)及相關資料。<br>
十五、其他中央主管機關指定之事項。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十三條</font>
<font size=2>(外國人投資之限制)</font>
<table><tr><td> </td>
<td>
對於有外國人投資之申請籌設、營運有線廣播電視案件,中央主管機關認該外國人投資對國家安全、公共秩序或善良風俗有不利影響者,得不經審議委員會之決議,予以駁回。<br>
外國人申請投資有線廣播電視,有前項或違反第十九條第二項規定情形者,應駁回其投資之申請。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十四條</font>
<font size=2>(不予許可申請籌設、營運之情形)</font>
<table><tr><td> </td>
<td>
申請籌設、營運有線廣播電視之案件有下列情形之一者,審議委員會應為不予許可之決議:<br>
一、違反第十九條或第二十條規定者。<br>
二、違反第二十一條規定者。<br>
三、工程技術管理不符合交通部依第三條第三項所定之規則者。<br>
四、申請人因違反本法規定經撤銷籌設或營運許可未逾二年者。<br>
五、申請人之董事、監察人或經理人有公司法第三十條各款情事之一者。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十五條</font>
<font size=2>(許可之情形)</font>
<table><tr><td> </td>
<td>
申請籌設、營運有線廣播電視案件符合下列規定者,審議委員會得為許可之決議:<br>
一、申請人之財務規劃及技術,足以實現其營運計畫者。<br>
二、免費提供專用頻道供政府機關、學校、團體及當地民眾播送公益性、藝文性、社教性等節目者。<br>
三、提供之服務及自製節目符合當地民眾利益及需求者。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十六條</font>
<font size=2>(申請書及營運計畫之變更)</font>
<table><tr><td> </td>
<td>
申請書及營運計畫內容於獲得籌設許可後有變更時,應向中央主管機關為變更之申請。但第二十二條第二項第四款、第十一款、第十二款內容變更者,不在此限。<br>
前項變更內容屬設立登記事項者,應於中央主管機關許可變更後,始得辦理設立或變更登記。<br>
系統經營者之董事、監察人或經理人變更時,準用前二項規定。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十七條</font>
<font size=2>(申請之准駁及覆議)</font>
<table><tr><td> </td>
<td>
對於申請籌設有線廣播電視案件,審議委員會決議不予許可者,中央主管機關應附具理由駁回其申請;其決議許可者,中央主管機關應發給申請人籌設許可證。<br>
不服前項駁回之處分,申請人得於駁回通知書送達之日起三十日內,附具理由提出覆議;審議委員會應於接獲覆議申請之日起三十日內,附具理由為准駁之決定。申請覆議以一次為限。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十八條</font>
<font size=2>(許可證之內容變更及遺失)</font>
<table><tr><td> </td>
<td>
籌設許可證所載內容變更時,應於變更後十五日內向中央主管機關申請換發;遺失時,應於登報聲明作廢後十五日內申請補發。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十九條</font>
<font size=2>(設立登記及補正)</font>
<table><tr><td> </td>
<td>
申請人經許可籌設有線廣播電視後,應於中央主管機關指定之地區與期間完成設立登記並繳交必要文件。文件不全得補正者,中央主管機關應通知限期補正。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十條</font>
<font size=2>(設置時程及展期)</font>
<table><tr><td> </td>
<td>
系統之設置得分期實施,全部設置時程不得逾三年;其無法於設置時程內完成者,得於設置時程屆滿前二個月內附具正當理由,向中央主管機關申請展期。展期不得逾六個月,並以一次為限。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十一條</font>
<font size=2>(查驗)</font>
<table><tr><td> </td>
<td>
系統之籌設應於營運計畫所載系統設置時程內完成,並於設置時程內向中央主管機關提出系統工程查驗申請。<br>
前項查驗由中央主管機關會同交通部及地方主管機關,自受理申請之日起六個月內為之。<br>
系統經查驗合格後二個月內,申請人應向中央主管機關申請營運許可。非經中央主管機關發給營運許可證者,不得營運。<br>
系統經營者除有正當理由,經中央主管機關核可者外,應於取得營運許可證後一個月內開播。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十二條</font>
<font size=2>(經營地區之劃分及調整)</font>
<table><tr><td> </td>
<td>
有線廣播電視經營地區之劃分及調整,由中央主管機關會商當地直轄市或縣(市)政府審酌下列事項後公告之:<br>
一、行政區域。<br>
二、自然地理環境。<br>
三、人文分布。<br>
四、經濟效益。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十三條</font>
<font size=2>(重新受理申請之情形及處理)</font>
<table><tr><td> </td>
<td>
有下列情形之一者,中央主管機關應另行公告重新受理申請:<br>
一、在公告期間內,該地區無人申請。<br>
二、該地區無人獲得籌設許可或營運許可。<br>
三、該地區任一系統經營者終止經營,經審議委員會決議,須重新受理申請。<br>
四、該地區系統經營者係獨占、結合、聯合、違反第二十一條規定而有妨害或限制公平競爭之情事,中央主管機關為促進公平競爭,經附具理由,送請審議委員會決議,須重新受理申請。<br>
重新辦理公告,仍有前項情形者,中央主管機關得視事實需要,依下列方式擇一處理之:<br>
一、會同當地直轄市或縣(市)政府重新劃分及調整經營地區。<br>
二、獎勵或輔導其他行政區域之系統經營者經營。<br>
三、其他經審議委員會決議之方式。<br>
前項第二款獎勵之輔導及方式,由中央主管機關定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十四條</font>
<font size=2>(不得委託他人經營)</font>
<table><tr><td> </td>
<td>
系統經營者不得委託他人經營。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十五條</font>
<font size=2>(營運許可之換發及補發)</font>
<table><tr><td> </td>
<td>
系統經營者之營運許可,有效期間為九年。系統經營者於營運許可期限屆滿,仍欲經營時,應於營運許可期限滿八年後六個月內,向中央主管機關申請換發。<br>
前項營運許可所載內容變更時,應於變更後十五日內向中央主管機關申准換發;遺失時,應於登報聲明作廢後十五日內申請補發。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十五條之一</font>
<font size=2>(申請換發之審查標準及程序)</font>
<table><tr><td> </td>
<td>
中央主管機關審查申請換發系統經營者之營運許可案件時,應審酌下列事項:<br>
一、營運計畫執行情形之評鑑結果及改正情形。<br>
二、未來之營運計畫。<br>
三、財務狀況。<br>
四、營運是否符合經營地區民眾利益及需求。<br>
五、系統經營者之獎懲紀錄及其他影響營運之事項。<br>
前項審查結果,中央主管機關認該系統經營者營運不善或未來之營運計畫有改善之必要時,應以書面通知其限期改善。屆期無正當理由而未改善者,經審議委員會審議,並經中央主管機關決議不予換發營運許可者,駁回其申請。<br>
前項審查期間及改善期間,中央主管機關得發給臨時執照,其有效期間為一年,並以一次為限。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十六條</font>
<font size=2>(營運計畫執行之評鑑)</font>
<table><tr><td> </td>
<td>
審議委員會應就系統經營者所提出之營運計畫執行情形,每三年評鑑一次。<br>
前項評鑑結果未達營運計畫且得改正者,中央主管機關應依審議委員會決議,通知限期改正;其無法改正,經審議委員會決議撤銷營運許可者,中央主管機關應註銷營運許可證。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十七條</font>
<font size=2>(基本頻道之提供)</font>
<table><tr><td> </td>
<td>
系統經營者應同時轉播依法設立無線電視電台之節目及廣告,不得變更其形式、內容及頻道,並應列為基本頻道。但經中央主管機關許可者,得變更頻道。<br>
系統經營者為前項轉播,免付費用,不構成侵害著作權。<br>
系統經營者不得播送未經中央主管機關許可之境外衛星廣播電視事業之節目或廣告。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十七條之一</font>
<font size=2>(免費播送客語原住民語言節目)</font>
<table><tr><td> </td>
<td>
為保障客家、原住民語言、文化,中央主管機關得視情形,指定系統經營者,免費提供固定頻道,播送客家語言、原住民語言之節目。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十八條</font>
<font size=2>(最大電波洩露量之規定)</font>
<table><tr><td> </td>
<td>
系統經營者在系統傳輸及處理過程中,其電波洩漏不得超過交通部所定之最大電波洩漏量限值。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十九條</font>
<font size=2>(暫停或終止經營之核備及通知)</font>
<table><tr><td> </td>
<td>
系統經營者擬暫停或終止經營時,除應於三個月前書面報請中央主管機關備查,副知地方主管機關外,並應於一個月前通知訂戶。<br>
前項所稱暫停經營之期間,最長為六個月。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第四章 節目管理</font>
<table><tr><td> </td><td><font color=8000ff>第四十條</font>
<font size=2>(節目內容之限制)</font>
<table><tr><td> </td>
<td>
節目內容不得有下列情形之一:<br>
一、違反法律強制或禁止規定。<br>
二、妨害兒童或少年身心健康。<br>
三、妨害公共秩序或善良風俗。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四十一條</font>
<font size=2>(節目分級之處理)</font>
<table><tr><td> </td>
<td>
中央主管機關應訂定節目分級處理辦法。系統經營者應依處理辦法規定播送節目。<br>
中央主管機關得指定時段,鎖碼播送特定節目。<br>
系統經營者應將鎖碼方式報請交通部會商中央主管機關核定。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四十二條</font>
<font size=2>(節目與廣告之區分)</font>
<table><tr><td> </td>
<td>
節目應維持完整性,並與廣告區分。<br>
非經約定,系統經營者不得擅自合併或停止播送頻道。<br>
節目由系統經營者及其關係企業供應者,不得超過可利用頻道之四分之一。<br>
系統經營者應於播送之節目畫面標示其識別標識。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四十三條</font>
<font size=2>(本國自製節目之最低佔有率)</font>
<table><tr><td> </td>
<td>
有線廣播電視節目中之本國自製節目,不得少於百分之二十。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四十四條</font>
<font size=2>(主管機關得索取資料)</font>
<table><tr><td> </td>
<td>
主管機關認為有必要時,得於節目播送後十五日內向系統經營者索取該節目及相關資料。<br>
主管機關於必要時,得要求系統經營者將提供訂戶之節目,以不變更內容及形式方式裝接於主管機關指定之處所。該節目係以鎖碼方式播出者,應將解碼設備一併裝接。<br>
前項指定之處所,以二處為限。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第五章 廣告管理</font>
<table><tr><td> </td><td><font color=8000ff>第四十五條</font>
<font size=2>(廣告插播頻率)</font>
<table><tr><td> </td>
<td>
系統經營者應同時轉播頻道供應者之廣告,除經事前書面協議外不得變更其形式與內容。<br>
廣告時間不得超過每一節目播送總時間六分之一。<br>
單則廣告時間超過三分鐘或廣告以節目型態播送者,應於播送畫面上標示廣告二字。<br>
計次付費節目或付費頻道不得播送廣告。但同頻道節目之預告不在此限。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四十六條</font>
<font size=2>(廣告播送之協議)</font>
<table><tr><td> </td>
<td>
頻道供應者應每年定期向審議委員會申報預計協議分配之廣告時間、時段、播送內容、播送方式或其他條件。頻道供應者如無正當理由拒絕依其申報內容與系統經營者協議,系統經營者得向審議委員會申請調處。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四十七條</font>
<font size=2>(廣告專用頻道)</font>
<table><tr><td> </td>
<td>
系統經營者得設立廣告專用頻道,不受第四十五條第二項之限制。<br>
廣告專用頻道之數量限制,由中央主管機關定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四十八條</font>
<font size=2>(插播式字幕的使用)</font>
<table><tr><td> </td>
<td>
系統經營者非有下列情形之一者,不得使用插播式字幕:<br>
一、天然災害、緊急事故訊息之播送。<br>
二、公共服務資訊之播送。<br>
三、頻道或節目異動之通知。<br>
四、與該播送節目相關,且非屬廣告性質之內容。<br>
五、依其他法令之規定。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四十九條</font>
<font size=2>(廣告內容之核准)</font>
<table><tr><td> </td>
<td>
廣告內容涉及依法應經各該目的事業主管機關核准之業務者,應先取得核准證明文件,始得播送。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十條</font>
<font size=2>(廣告內容之限制及製播標準)</font>
<table><tr><td> </td>
<td>
第四十條、第四十一條第二項、第三項、第四十二條第四項及第四十四條之規定,於廣告準用之。<br>
廣告製播標準由中央主管機關定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第六章 費用</font>
<table><tr><td> </td><td><font color=8000ff>第五十一條</font>
<font size=2>(收費標準)</font>
<table><tr><td> </td>
<td>
系統經營者應於每年八月一日起一個月內向直轄市、縣(市)政府申報收視費用,由直轄市、縣(市)政府依審議委員會所訂收費標準,核准後公告之。<br>
直轄市及縣(市)政府得設費率委員會,核准前項收視費用。直轄市及縣(市)政府未設費率委員會時,應由中央主管機關行使之。<br>
系統經營者之會計制度及其標準程式,由中央主管機關定之。<br>
系統經營者應於每年一月、四月、七月及十月,向中央主管機關申報前三個月訂戶數。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十二條</font>
<font size=2>(訂戶不按期繳交費用之處置)</font>
<table><tr><td> </td>
<td>
訂戶不按期繳交費用,經定期催告仍未繳交時,系統經營者得停止對該訂戶節目之傳送。但應同時恢復訂戶原有無線電視節目之視、聽。<br>
系統經營者依前項但書規定辦理時,得向訂戶請求支付必要之器材費用。<br>
第一項但書及前項規定,於視聽法律關係終止之情形,適用之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十三條</font>
<font size=2>(特種基金之成立運用及管理)</font>
<table><tr><td> </td>
<td>
系統經營者應每年提撥當年營業額百分之一之金額,提繳中央主管機關成立特種基金。<br>
前項系統經營者提撥之金額,由中央主管機關依下列目的運用:<br>
一、百分之三十由中央主管機關統籌用於有線廣播電視之普及發展。<br>
二、百分之四十撥付當地直轄市、縣(市)政府,從事與本法有關地方文化及公共建設使用。<br>
三、百分之三十捐贈財團法人公共電視文化事業基金會。<br>
第一項特種基金之成立、運用及管理辦法,由中央主管機關定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十四條</font>
<font size=2>(審查費各項費用之繳納)</font>
<table><tr><td> </td>
<td>
主管機關依本法受理申請審核、查驗、核發、換發證照,應向申請者收取審查費、證照費;其收費標準由中央主管機關定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第七章 權利保護</font>
<table><tr><td> </td><td><font color=8000ff>第五十五條</font>
<font size=2>(有線電視契約)</font>
<table><tr><td> </td>
<td>
系統經營者應與訂戶訂立書面契約。<br>
前項書面契約應於給付訂戶之收據背面製作發給之。<br>
中央主管機關應公告規定定型化契約應記載或不得記載之事項。<br>
違反前項公告之定型化契約之一般條款無效。該定型化契約之效力依消費者保護法第十六條規定定之。<br>
契約內容應包括下列事項:<br>
一、各項收費標準及調整費用之限制。<br>
二、頻道數、名稱及頻道契約到期日。<br>
三、訂戶基本資料使用之限制。<br>
四、系統經營者受停播、撤銷營運許可、沒入等處分時,恢復訂戶原有無線電視節目之視、聽,及對其視、聽權益產生損害之賠償條件。<br>
五、無正當理由中斷約定之頻道信號,致訂戶視、聽權益有損害之虞時之賠償條件。<br>
六、契約之有效期間。<br>
七、訂戶申訴專線。<br>
八、其他經中央主管機關指定之項目。<br>
系統經營者對訂戶申訴案件應即妥適處理,並建檔保存三個月;主管機關得要求系統經營者以書面或於相關節目答覆訂戶。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十六條</font>
<font size=2>(系統經營者之識別標識許可證字號等資料之播出)</font>
<table><tr><td> </td>
<td>
系統經營者應設置專用頻道,載明系統經營者名稱、識別標識、許可證字號、訂戶申訴專線、營業處所地址、頻道總表、頻道授權期限及各頻道播出節目之名稱。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十七條</font>
<font size=2>(節目及廣告之合法授權播送)</font>
<table><tr><td> </td>
<td>
有線廣播電視播送之節目及廣告涉及他人權利者,應經合法授權,始得播送。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十八條</font>
<font size=2>(強制締約及提供必要之協助)</font>
<table><tr><td> </td>
<td>
系統經營者無正當理由不得拒絕該地區民眾請求付費視、聽有線廣播電視。<br>
系統經營者有正當理由無法提供民眾經由有線電視收視無線電視時,地方主管機關得提請審議委員會決議以其他方式提供收視無線電視。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十九條</font>
<font size=2>(相關線路之拆除義務)</font>
<table><tr><td> </td>
<td>
視、聽法律關係終止後,系統經營者應於一個月內將相關線路拆除。逾期不為拆除時,該土地或建築物之所有人或占有人得自行拆除,並得向系統經營者請求償還其所支出之拆除及其他必要費用。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十條</font>
<font size=2>(主管機關通知限期改善)</font>
<table><tr><td> </td>
<td>
主管機關認為有線廣播電視營運不當,有損害訂戶權益情事或有損害之虞者,應通知系統經營者限期改正或為其他必要措施。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十一條</font>
<font size=2>(利害關係人要求更正之處置)</font>
<table><tr><td> </td>
<td>
對於有線廣播電視之節目或廣告,利害關係人認有錯誤,得於播送之日起,十五日內要求更正,系統經營者應於接到要求後十五日內,在同一時間之節目或廣告中,加以更正,如認為節目或廣告無誤時,應附具理由書面答覆請求人。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十二條</font>
<font size=2>(被評論者權益受損時之答辯)</font>
<table><tr><td> </td>
<td>
有線廣播電視之節目評論涉及他人或機關、團體,致損害其權益時,被評論者,如要求給予相當答辯之機會,不得拒絕。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第八章 罰則</font>
<table><tr><td> </td><td><font color=8000ff>第六十三條</font>
<font size=2>(處罰機關)</font>
<table><tr><td> </td>
<td>
依本法所為之處罰,由中央主管機關為之。但違反依第三條第三項所定之規則及第三十八條規定者,由交通部為之;違反節目管理、廣告管理、費用及權利保護各章規定者,由直轄市或縣(市)政府為之。直轄市或縣(市)政府未能行使職權時,得由中央主管機關為之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十四條</font>
<font size=2>(警告)</font>
<table><tr><td> </td>
<td>
經許可籌設有線廣播電視者或系統經營者有下列情形之一時,予以警告:<br>
一、工程技術管理違反依第三條第三項所定之規則者。<br>
二、未依第二十八條或第三十五條第二項規定辦理換發或補發許可證者。<br>
三、未於第三十一條第三項規定期限內,向中央主管機關申請營運許可者。<br>
四、違反第三十七條第一項、第四十一條第一項、第三項、第四十二條第一項、第二項、第四項、第四十三條、第四十五條、第四十八條或第五十條第一項準用第四十一條第三項、第四十二條第四項規定者。<br>
五、違反第五十一條第一項、第四項、第五十二條第一項但書或第三項規定者。<br>
六、違反第五十五條、第五十六條、第五十八條、第六十一條或第六十二條規定者。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十五條</font>
<font size=2>(罰則)</font>
<table><tr><td> </td>
<td>
系統經營者違反第三十八條規定者,處新臺幣二萬元以上二十萬元以下罰鍰,並通知立即改正,未改正者,按次連續處罰。<br>
前項電波洩漏嚴重致影響飛航安全、重要通訊系統者,中央主管機關得依交通部之通知令其停播至改正為止。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十六條</font>
<font size=2>(罰則)</font>
<table><tr><td> </td>
<td>
經許可籌設有線廣播電視者或系統經營者,有下列情形之一時,處新臺幣五萬元以上五十萬元以下罰鍰,並通知限期改正:<br>
一、經依第六十四條規定警告後,仍不改正者。<br>
二、未依第五條第一項規定申准,擅自鋪設或附掛網路者。<br>
三、違反主管機關依第七條第一項、第二項所為停止、指定或繼續播送之通知者。<br>
四、經中央主管機關依第三十六條第二項規定通知限期改正,逾期不改正者。<br>
五、違反第三十七條第三項或第三十九條規定者。<br>
六、違反第四十條、第四十九條或第五十條第一項準用第四十條規定者。<br>
七、未依第四十一條第二項或第五十條第一項準用第四十一條第二項指定之時段、方式播送者。<br>
八、拒絕依第四十四條第二項或第五十條第一項準用第四十四條第二項主管機關指定之處所裝接者。<br>
九、違反第五十七條規定者。<br>
十、未依第六十條規定改正或為其他必要措施者。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十七條</font>
<font size=2>(罰則)</font>
<table><tr><td> </td>
<td>
經許可籌設有線廣播電視者或系統經營者,有下列情形之一時,處新臺幣十萬元以上一百萬元以下罰鍰,並通知限期改正,逾期不改正者,得按次連續處罰:<br>
一、一年內經依本法處罰二次,再有第六十四條或第六十六條情形之一者。<br>
二、拒絕依第四十四條第一項或第五十條第一項準用第四十四條第一項規定提供資料或提供不實資料者。<br>
三、違反第七十三條第二項規定者。<br>
系統經營者有前項第一款情形者,並得對其頻道處以三日以上三個月以下之停播處分。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十八條</font>
<font size=2>(罰則)</font>
<table><tr><td> </td>
<td>
經許可籌設有線廣播電視者或系統經營者,有下列情形之一時,處新臺幣十萬元以上一百萬元以下罰鍰,並通知限期改正,逾期不改正者,得按次連續處罰;情節重大者,得撤銷籌設許可或營運許可,並註銷籌設許可證或營運許可證:<br>
一、有第二十一條第一項各款情形之一者。<br>
二、有第二十四條第一款、第四款或第五款情形者。<br>
三、未依第二十六條第一項規定申准,擅自變更申請書內容或營運計畫者。<br>
四、未依第二十六條第二項或第三項規定,經中央主管機關許可變更,擅自辦理設立或變更登記者。<br>
五、未經中央主管機關依第三十一條第三項規定發給營運許可證,擅自營運者。<br>
六、違反第三十一條第四項規定者。<br>
七、未依第三十七條之一中央主管機關之指定提供頻道,播送節目者。<br>
八、違反第四十二條第三項規定者。<br>
九、違反第五十三條第一項規定者。<br>
十、於受停播處分期間,播送節目或廣告者。<br>
前項限期改正方式如下:<br>
一、處分全部或部分股份。<br>
二、轉讓全部或部分營業。<br>
三、免除擔任職務。<br>
四、其他必要方式。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十九條</font>
<font size=2>(罰則)</font>
<table><tr><td> </td>
<td>
經許可籌設有線廣播電視者或系統經營者,有下列情形之一時,撤銷籌設許可或營運許可,並註銷籌設許可證或營運許可證:<br>
一、以不法手段取得籌設許可或營運許可者。<br>
二、一年內經受停播處分三次,再違反本法規定者。<br>
三、設立登記經該管主管機關撤銷者。<br>
四、違反第二十九條規定者。<br>
五、違反第三十條規定未於設置時程內完成系統設置者。<br>
六、違反第三十四條規定者。<br>
七、經依第六十五條第二項規定勒令停播,拒不遵行者。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第七十條</font>
<font size=2>(罰則)</font>
<table><tr><td> </td>
<td>
未依本法規定獲得籌設許可或經撤銷籌設、營運許可,擅自經營有線廣播電視業務者,處新臺幣二十萬元以上二百萬元以下罰鍰,並得按次連續處罰。<br>
前項經營有線廣播電視業務之設備,不問屬於何人所有,沒入之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第七十一條</font>
<font size=2>(強制執行)</font>
<table><tr><td> </td>
<td>
依本法所處罰鍰,經通知限期繳納,逾期仍不繳納者,移送法院強制執行。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第九章 附則</font>
<table><tr><td> </td><td><font color=8000ff>第七十二條</font>
<font size=2>(管理辦法之訂定及營業登記效力)</font>
<table><tr><td> </td>
<td>
本法施行前,未依法定程序架設之有線電視節目播送系統,於本法施行後,經中央主管機關發給登記證者,得繼續營業。<br>
系統經營者自開始播送節目之日起十五日內,該地區內前項有線電視節目播送系統應停止播送,原登記證所載該地區失其效力;仍繼續播送者,依第七十條規定處罰。但經中央主管機關許可得繼續經營者,不在此限。<br>
有線電視節目播送系統登記證之發給、註銷、營運及依前項但書許可繼續經營之條件及期限等事項,由中央主管機關另定辦法管理之。<br>
有線電視節目播送系統之節目管理、廣告管理、費用及權利保護準用本法各有關之規定。違反者,依本法處罰之。<br>
系統經營者於其播送節目區域內,有有線電視節目播送系統依第二項但書規定繼續營業時,不適用第二十五條第二款及第五十三條規定。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第七十三條</font>
<font size=2>(主管機關得派員檢查)</font>
<table><tr><td> </td>
<td>
主管機關得派員攜帶證明文件,對系統實施檢查,要求經許可籌設有線廣播電視者或系統經營者,就其設施及本法規定事項提出報告、資料或為其他配合措施,並得扣押違反本法規定之資料或物品。<br>
對於前項之要求、檢查或扣押,不得規避、妨礙或拒絕。<br>
第一項扣押資料或物品之處理方式由中央主管機關定之,其涉及刑事責任者,依有關法律規定處理。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第七十四條</font>
<font size=2>(私接戶之責任及賠償)</font>
<table><tr><td> </td>
<td>
未經系統經營者同意,截取或接收系統播送之內容者,應補繳基本費用。其造成系統損害時,應負民事損害賠償責任。<br>
前項收視費用,如不能證明期間者,以二年之基本費用計算。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第七十五條</font>
<font size=2>(施行細則)</font>
<table><tr><td> </td>
<td>
本法施行細則,由中央主管機關定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第七十六條</font>
<font size=2>(施行日)</font>
<table><tr><td> </td>
<td>
本法自公布日施行。<br>
</td>
</table>
</table>
</table>
</left>
</body>
<!-- Mirrored from lis.ly.gov.tw/lghtml/lawstat/version2/02409/0240996011200.htm by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 24 Mar 2013 09:19:03 GMT -->
</html>
|
Java
|
/****************************************************************************
Copyright (c) 2011-2013,WebJet Business Division,CYOU
http://www.genesis-3d.com.cn
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "stdneb.h"
#include "exceptionbase.h"
namespace Exceptions
{
Exception::~Exception() throw()
{
}
Exception::Exception(const String& description_, const String& source_)
:line(0)
,type(EXT_UNDEF_TYPE)
,title("Exception")
,description(description_)
,source(source_)
{
// Log this error - not any more, allow catchers to do it
//LogManager::getSingleton().logMessage(this->getFullDescription());
}
Exception::Exception(const String& description_, const String& source_, const char* file_, long line_)
:type(EXT_UNDEF_TYPE)
,title("Exception")
,description(description_)
,source(source_)
,file(file_)
,line(line_)
{
// Log this error - not any more, allow catchers to do it
//LogManager::getSingleton().logMessage(this->getFullDescription());
}
Exception::Exception(int type_, const String& description_, const String& source_, const char* tile_, const char* file_, long line_)
:line(line_)
,type(type_)
,title(tile_)
,description(description_)
,source(source_)
,file(file_)
{
}
Exception::Exception(const Exception& rhs)
: line(rhs.line),
type(rhs.type),
title(rhs.title),
description(rhs.description),
source(rhs.source),
file(rhs.file)
{
}
void Exception::operator = (const Exception& rhs)
{
description = rhs.description;
type = rhs.type;
source = rhs.source;
file = rhs.file;
line = rhs.line;
title = rhs.title;
}
const String& Exception::GetFullDescription() const
{
if (0 == fullDesc.Length())
{
if( line > 0 )
{
fullDesc.Format("GENESIS EXCEPTION(%d:%s): \"%s\" in %s at %s(line, %d)",
type, title.AsCharPtr(), description.AsCharPtr(), source.AsCharPtr(), file.AsCharPtr(), line);
}
else
{
fullDesc.Format("GENESIS EXCEPTION(%d:%s): \"%s\" in %s", type, title.AsCharPtr(), description.AsCharPtr(), source.AsCharPtr());
}
}
return fullDesc;
}
int Exception::GetType(void) const throw()
{
return type;
}
const String &Exception::GetSource() const
{
return source;
}
const String &Exception::GetFile() const
{
return file;
}
long Exception::GetLine() const
{
return line;
}
const String &Exception::GetDescription(void) const
{
return description;
}
const char* Exception::what() const throw()
{
return GetFullDescription().AsCharPtr();
}
}
|
Java
|
#include "GlobalSystems.h"
namespace globalSystem {
WindowManagerGL window;
TimeData time;
MouseData mouse;
KeyPressData keys;
TextureManager textures;
ModelManager models;
DynamicFloatMap runtimeData;
RandomNumberGenerator rng;
Font gameFont;
Font gameFontLarge;
Font gameFontHuge;
}
|
Java
|
/* Define to 1 if you have the <stdlib.h> header file. */
/*#define HAVE_STDLIB_H 1*/
|
Java
|
/**
* Module dependencies.
*/
var api = require('lib/db-api');
var config = require('lib/config');
var express = require('express');
var jwt = require('lib/jwt');
var passport = require('passport');
var log = require('debug')('democracyos:auth:facebook:routes');
var User = require('lib/models').User;
var fbSignedParser = require('fb-signed-parser');
/**
* Expose auth app
*/
var app = module.exports = express();
/*
* Facebook Auth routes
*/
app.get('/auth/facebook',
passport.authenticate('facebook', {
scope: config.auth.facebook.permissions
})
);
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { failureRedirect: '/' }),
function(req, res) {
// After successful authentication
// redirect to homepage.
log('Log in user %s', req.user.id);
var token = jwt.encodeToken(api.user.expose.confidential(req.user), config.jwtSecret);
return res.cookie('token', token.token, { expires: new Date(token.expires), httpOnly: true }).redirect('/');
}
);
app.post('/auth/facebook/deauthorize', function(req, res) {
log('Parsing call to "/auth/facebook/deauthorize".');
res.send(200);
var signedRequest = req.params.signed_request;
if (!signedRequest) return log('"signed_request" param not found.');
var data = fbSignedParser.parse(signedRequest, config.auth.facebook.clientSecret);
if (!data || !data.user || !data.user.id) {
return log('Invalid "signed_request" data: ', data);
}
setTimeout(function(){
deauthorizeUser(data.user.id)
}, 0);
});
function deauthorizeUser(userFacebookId) {
log('Deauthorizing user with facebook id "%s".', userFacebookId);
var profile = {
id: userFacebookId,
provider: 'facebook'
};
User.findByProvider(profile, function (err, user) {
if (err) {
return log('Error looking for user with facebook id "%s".', userFacebookId);
}
if (!user) {
return log('User with facebook id "%s" not found.', userFacebookId);
}
user.set('profiles.facebook.deauthorized', true);
return user.save(function(err){
if (err) return log(err);
log('Facebook login for user "%s" deauthorized.', user.id);
});
});
}
|
Java
|
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.ProjectOxford.Face;
using Microsoft.ProjectOxford.Face.Contract;
namespace Novanet
{
public static class FaceServiceClientExtensions
{
public static async Task CreatePersonGroupIfNotExising(this FaceServiceClient client, string personGroupId, string name)
{
var personGroups = await client.ListPersonGroupsAsync();
if (!personGroups.Any(pg => pg.PersonGroupId.Equals(personGroupId, StringComparison.InvariantCultureIgnoreCase)))
{
await client.CreatePersonGroupAsync(personGroupId, name);
}
}
public static async Task<Guid> CreateUserAsPersonIfNotExising(this FaceServiceClient client, string personGroupId, User user)
{
// Use person UserData property to store external UserId for matching
var persons = await client.GetPersonsAsync(personGroupId);
if (persons.Any(p => p.UserData.Equals(user.Id.ToString(), StringComparison.InvariantCultureIgnoreCase)))
{
return persons.First(p => p.UserData.Equals(user.Id.ToString(), StringComparison.InvariantCultureIgnoreCase)).PersonId;
}
var person = await client.CreatePersonAsync(personGroupId, user.Name, user.Id.ToString());
return person.PersonId;
}
public static async Task WaitForPersonGroupStatusNotRunning(this FaceServiceClient client, string personGroupId, TraceWriter log)
{
// WOW, this is ugly, should probably put back on queue?
try
{
var status = await client.GetPersonGroupTrainingStatusAsync(personGroupId);
while (status.Status == Status.Running)
{
log.Info("Waiting for training...");
await Task.Delay(5000);
}
} catch (FaceAPIException notTrainedException)
{
// Throws if never tained before, and I don't care.
}
}
}
}
|
Java
|
# Latte-lang 规范
# 目录
1. [起步](#p1)
1. [基础语法](#p1-1)
2. [文件结构](#p1-2)
2. [基础](#p2)
1. [字面量](#p2-1)
2. [基本类型](#p2-2)
3. [控制流](#p2-3)
3. [类和对象](#p3)
1. [类与继承](#p3-1)
2. [接口](#p3-2)
3. [字段和方法](#p3-3)
4. [修饰符](#p3-4)
5. [Data Class](#p3-5)
6. [实例化](#p3-6)
7. [Object Class](#p3-7)
8. [隐式转换](#p3-8)
4. [函数类和Lambda](#p4)
1. [函数类](#p4-1)
2. [高阶函数和Lambda](#p4-2)
5. [其他](#p5)
1. [Json 集合](#p5-1)
2. [范围](#p5-2)
3. [类型检查与转换](#p5-3)
4. [运算符绑定](#p5-4)
5. [异常](#p5-5)
6. [注解](#p5-6)
7. [过程(Procedure)](#p5-7)
8. [参数可用性检查](#p5-8)
9. [解构](#p5-9)
10. [模式匹配](#p5-10)
6. [Java 交互](#p6)
1. [在Latte中调用Java代码](#p6-1)
2. [在Java中调用Latte代码](#p6-2)
<h1 id="p1">1. 起步</h1>
`Latte-lang`是一种JVM语言,基于JDK 1.6。它支持Java的所有语义,能够与Java完美互通,并提供比Java更多的函数式特性。
<h2 id="p1-1">1.1 基础语法</h2>
Latte-lang(后文简称Latte)借鉴了主流语言的语法特征。如果您熟悉`Java`,或者了解过`Kotlin`,`Scala`,`Python`,`JavaScript`,`Swift`中的一到两种,那么阅读`Latte-lang`代码是很轻松的。
> 对Latte影响最大的语言应该是Kotlin和Scala
<h3 id="p1-1-1">1.1.1 注释</h3>
单行注释使用`//`开头。例如
```java
// i am a comment
```
多行注释以`/*`开头,以`*/`结尾。例如
```java
/* comment */
/*
multiple line comment
*/
a/* comment */=1
/* the comment splits an expression */
```
<h3 id="p1-1-2">1.1.2 包与导入</h3>
```kotlin
package lt::spec
import java::util::_
```
或者使用`.`分割
```kotlin
package lt.spec
import java.util._
```
代码段由`package`开始。一个latte文件只能包含一个`package`。它定义了其中定义的类、接口所在的“包”。包是一个java概念,可以理解为一个名字空间。
声明了这个文件中定义的所有类和接口都在`lt::spec`包下。子包的名称通过`::`,或者`.`分隔。
文件也可以不声明包,那么包名将被视为空字符串`""`
在导入包时使用`import`关键字,有三种导入方式:
```kotlin
import java::awt::_ /* 导入所有java::awt包中的所有类 */
import java::util::List /* 导入类java::util::List */
import java::util::Collections._ /* 导入Collections类的所有静态字段和方法 */
```
>使用`.`无法在语法上区分包与字段访问,所以在latte中建议使用`::`分割包名。但是考虑到其他JVM语言均使用`.`,所以也提供了`.`以符合使用习惯。
<h3 id="p1-1-3">1.1.3 类</h3>
定义类User
```kotlin
class User(id: int, name: String)
```
定义MyList类,并继承了LinkedList类
```kotlin
class MyList(ls:List):LinkedList(ls)
```
定义抽象类MyList,并实现了List接口
```kotlin
abstract class MyList:List
```
详见[3.1 类与继承](#p3-1)
定义`data class`
```kotlin
data class User(id: int, name: String)
```
定义data class后,编译器会自动生成所有字段的getter/setter,类的toString/hashCode/equals方法,并继承和实现Serializable、Cloneable接口。
详见[3.5 Data Class](#p3-5)
定义`object class`
```kotlin
object Singleton
```
可以直接使用类名获取该对象。
详见[3.7 object class](#p3-7)
<h3 id="p1-1-4">1.1.4 接口</h3>
定义接口Consumer
```kotlin
interface Supplier
def supply
```
详见[3.2 接口](#p3-2)
<h3 id="p1-1-5">1.1.5 函数类</h3>
定义函数类sum
```kotlin
fun sum(a, b)
return a+b
```
详见[4.1 函数类](#p4-1)
<h3 id="p1-1-6">1.1.6 变量</h3>
只读变量
```kotlin
val a:int = 1
val b = 1
```
可变变量
```kotlin
var x = 5
x += 1
```
可变变量的`var`可以省略
```python
y = 6
```
<h3 id="p1-1-7">1.1.7 字符串模板</h3>
```kotlin
main(args : []String)
println("First argument: ${args[0]}")
```
<h3 id="p1-1-8">1.1.8 使用条件表达式</h3>
```python
if a > b
return a
else
return b
```
或者
```kotlin
result = (if a > b {a} else {b})
```
>一个方法需要返回值,那么只要末尾一个值为表达式,Latte就会自动生成方法的return语句
详见[2.3.1 If 语句](#p2-3-1)
<h3 id="p1-1-9">1.1.9 for循环</h3>
```swift
for item in list
println(item)
```
或者
```swift
for i in 0 until list.size
println(list[i])
```
详见[2.3.2 For 语句](#p2-3-2)
<h3 id="p-1-1-10">1.1.10 while循环</h3>
```swift
i = 0
while i < list.size
println(list[i++])
```
详见[2.3.3 While 语句](#p2-3-3)
<h3 id="p-1-1-11">1.1.11 范围</h3>
检查x是否在范围中
```kotlin
if x in 1 to y-1
print("OK")
```
从1到5进行循环
```swift
for x in 1 to 5
print(x)
```
详见[5.2 范围](#p5-2)
<h3 id="p1-1-12">1.1.12 Lambda</h3>
```kotlin
list.stream.
filter{it.startsWith("A")}.
map{it.toUpperCase()}.
forEach{print(it)}
f = a -> 1 + a
f(2) /* 结果为 3 */
```
详见[4.2 高阶函数和Lambda](#p4-2)
<h3 id="p1-1-13">1.1.13 Json语法</h3>
```js
list = [1, 2, 3]
map = [
"a": 1
"b": 2
]
```
详见[5.1 Json 集合](#p5-1)
<h3 id="p1-1-14">1.1.14 返回对象的"或"</h3>
拥有JavaScript的`||`的功能。
```js
a = a || 1
```
<h3 id="p1-1-15">1.1.15 指定生成器</h3>
```
#js
def method(a)
return a+1
```
将会被转换成如下JavaScript代码
```js
function method(a) {
return a + 1;
}
```
<h3 id="p1-1-16">1.1.16 模式匹配</h3>
```scala
val (x,y) = Bean(1,2)
```
详见[5.9 解构](#p5-9)
```scala
o match
case Bean(a,b) => ...
case People(name, age) if age > 20 => ...
case _ => ...
```
详见[5.10 解构](#p5-10)
<h2 id="p1-2">1.2 文件结构</h2>
Latte源文件以`.lt`或者`.lts`为扩展名。不过实际上后缀名并不重要,手动构造编译器时附加特定参数即可。
<h3 id="p1-2-1">1.2.1 定义层次结构</h3>
编译器首先会检查文件的第一行。第一行可以标注该文件 使用缩进定义层次结构,还是 使用大括号定义层次结构。
例如:
```java
/// :scanner-brace
```
表示使用大括号定义层次结构。
```java
/// :scanner-indent
```
表示使用缩进定义层次结构。
**默认为缩进**。提供这个选项是为了满足不同人的编码喜好。这两者的选择在词法上完全一样。
>注意:Latte并不限定缩进数量。比上一行“更大的缩进”均代表一个新层次。
<h3 id="p1-2-2">1.2.2 层次结构</h3>
使用*大括号*定义层次结构时,有如下几个符号会开启一个新层:
```
(
[
{
```
当其对应的符号出现时,这个开启的层将关闭:
```
)
]
}
```
使用*缩进*定义层次结构时,还有两个符号会开启一个新层: `->`、`=>`
由于层将在缩进“变得更小”时关闭。所以,如下代码不加上括号也可以正确的工作:
```java
f = x->x+1
f()
```
>注:使用大括号定义层次结构时,`->`不会开启新层,若要书写多行语句请使用{...}。此时规则和java完全一致。
这里有一个示例,帮助理解“层”的概念:
┌───────────────────────┐
│ ┌─┐ │
│classA(│a│):B │
│ └─┘ │
│ ┌─────────────────┐│
│ │ ┌────────┐││
│ │method(│arg0 │││
│ │ ┌──┘ │││
│ │ │arg1 │││
│ │ │arg2, arg3 │││
│ │ └───────────┘││
│ │):Unit ││
│ │ ┌────┐ ││
│ │ │pass│ ││
│ │ └────┘ ││
│ └─────────────────┘│
└───────────────────────┘
该源码将被解析成如下结构:
-[class]-[A]-[(]-[│]-[)]-[:]-[B]-[│]
└[a]- ┌──────┘
┌──────────────────────────┘
└────[method]-[(]-[│]-[)]-[│]-
┌──────────────────┘ └───────[pass]-
│
└──[arg0]-[EndNode]-[arg1]-[EndNode]-[arg2]-[StrongEndNode]-[arg3]
**注意:** 本文除非注明,否则均使用“缩进”进行描述。在注明为“大括号”时,会在示例代码开头标注`/// :scanner-brace`。
<h3 id="p1-2-4">1.2.4 层次控制字符</h3>
Latte支持直接使用`{`和`}`定义层次结构。不过要注意,如果写为`{}`则表示空Map(映射)
例如:
```kotlin
if a > b {1} else {2}
/* 相当于 */
if a > b
1
else
2
```
```js
var map = {} /* 这是一个map */
```
```js
/* 可以正常编译,定义了一个方法,其中定义一个局部变量,赋值一个map */
def method {
map = [
"a": 1
"b": 2
]
}
```
<h1 id="p2">2. 基础</h1>
<h2 id="p2-1">2.1 字面量</h2>
Latte中有6种字面量:
1. number
2. string
3. bool
4. array
5. map
<h3 id="p2-1-1">2.1.1 number</h3>
数字可以分为整数和浮点数
例如:
1
1.2
`1`是一个整数,`1.2`是一个浮点数。
整数字面量可以赋值给任意数字类型,而浮点数字面量只能赋值给`float`和`double`。详见 [2.2 基本类型](#p2-2)。
<h3 id="p2-1-2">2.1.2 string</h3>
字符串可以以`'`或`"`开头,并以同样的字符结尾。
例如:
'a string'
"a string"
使用`\`作为转义字符
例如:
```
'escape \''
"escape \""
```
字符串字面量分为两种,若字符串长度为1,则它可以赋值给`char`类型或`java.lang.String`类型。否则只能赋值给`java.lang.String`类型。
<h3 id="p2-1-3">2.1.3 bool</h3>
布尔型有下述4种书写形式:
true
false
yes
no
`true`和`yes`表示逻辑真,`false`和`no`表示逻辑假。
布尔值字面量只能赋值给`bool`类型。
<h3 id="p2-1-4">2.1.4 array</h3>
数组以`[`开头,并以`]`结尾,其中包含的元素可以用`,`分隔,也可以通过换行分隔。
例如:
```js
[1,2,3]
[
object1
object2
object3
]
[
object1,
object2,
object3
]
```
<h3 id="p2-1-5">2.1.5 map</h3>
映射(字典)像swift一样,以`[`开头,以`]`结尾。
键值对通过类型符号`:`分隔,不同的entry通过`,`或者换行进行分隔。
例如:
```swift
['a':1, 'b':2, 'c':3]
[
'a':1
'b':2
'c':3
]
[
'a':1,
'b':2,
'c':3
]
```
<h2 id="p2-2">2.2 基本类型</h2>
Latte保留了Java的8种基本类型。由于Latte是动态类型语言,并且可以在编译期和运行时自动装包和拆包,所以基本类型与包装类型可以认为没有差异。
八种基本类型:
```
int
long
float
double
short
byte
char
bool
```
其中`int/long/float/double/short/byte`为数字类型。
注意,与Java不同的是,Latte使用`bool`而非`boolean`。
<h3 id="p2-2-1">2.2.1 基本类型转换</h3>
在转换时,所有基本类型都可以互相转换(除了bool,它可以被任何类型转换到,但不能转换为其他类型,详见[5.8 参数可用性检查](#p5-8))而不会出现任何错误。但是,在高精度向低精度转换时可能会丢失信息。例如:
```scala
i:int = 3.14 /* i == 3 丢失了小数部分 */
b:bool = 10 /* b == true 除了数字不是0外,信息都丢失了 (只有0在转换为bool时才会是false) */
```
<h3 id="p2-2-2">2.2.2 基本类型运算</h3>
Latte支持所有Java的运算符,并在其基础上有所扩展
对于数字的基本运算,其结果均为“精度较高的值”的类型,且最低为`int`型。例如:
```c#
r1 = (1 as long) + (2 as int) /* r1 是 long */
r2 = (1 as byte) + (2 as short) /* r2 是 int */
```
由于Latte可以任意转换基本类型,所以这么写也可以正常编译并运行:
```java
a:short = 1
a+=1 /* a == 2 */
a++ /* a == 3 */
```
>由于Latte支持基本类型的互相转换,你可以直接把`int`的结果赋值给`short`。
Latte支持所有Java运算符,当然也包括位运算。和`java`一样,位运算必须作用于整数上。Latte支持所有整数类型的位运算:`int/long/short/byte`。
此外,Latte还支持乘方运算:
```groovy
a ^^ b
```
结果均为`double`型。
> 本质来说,Latte不存在“运算符”。所有运算符都是方法调用。基本类型的运算是由其包装类型隐式转换后调用方法完成的。
<h2 id="p2-3">2.3 控制流</h2>
<h3 id="p2-3-1">2.3.1 If 语句</h3>
和Java一样,if是一个语句而非像Kotlin,Scala那样作为表达式。
但是,Latte支持`Procedure`,并且可以自动添加返回语句,所以使用起来和作为表达式区别并不大。
```ruby
if a > b
return 1
else
return 2
val result = (if a>b {1} else {2})
```
<h3 id="p2-3-2">2.3.2 For 语句</h3>
for语句格式如下:
```kotlin
for item in iter
...
```
其中`iter`可以是数组、Iterable对象、Iterator对象、Enumerable对象、Map对象。
当`iter`为前4种时,for语句将把其包含的对象依次赋值给`item`并执行循环体。当`iter`为Map对象时,`item`是一个Entry对象,它来自`Map#entrySet()`。
你也可以使用`to`或者`until`,并在循环体内使用下标来访问元素:
```kotlin
for i in 0 until arr.length
val elem = arr[i]
...
```
<h3 id="p2-3-3">2.3.3 While 语句</h3>
while语句格式如下:
```python
while boolExp
...
do
...
while boolExp
```
它的含义和Java完全一致。
<h3 id="p2-3-4">2.3.4 break, continue, return</h3>
在循环中可以使用 `break` 和 `continue` 来控制循环。break将直接跳出循环,continue会跳到循环末尾,然后立即开始下一次循环。它的含义与Java完全一致。
`return`可以用在lambda、方法(包括“内部方法”)、Procedure、脚本、函数类中:
```kotlin
/* lambda */
foo = ()->return 1
/* 方法 */
def bar()
return 2
/* Procedure */
(
return 3
)
/* 函数类 */
fun Fun1
return 4
```
脚本中的return语句表示将这个值返回到外部,在`require`这个脚本时将返回这个值。
如果`return`是这个函数/方法最后的一条语句,或者该函数任意一条逻辑分支的最末尾,那么`return`都可以被省略:
```kotlin
fun add(a, b)
a+b
val result = add(1, 2)
/* result is 3 */
```
转换方式很简单,首先取出这个函数/方法的最后一条语句,如果是表达式,而且这个函数/方法要求返回值,则直接将其包装在`AST.Return`中。
如果最后一条语句是`if`,那么对其每一个逻辑分支进行该算法。
<h1 id="p3">3. 类和对象</h1>
<h2 id="p3-1">3.1 类与继承</h2>
<h3 id="p3-1-1">3.1.1 类</h3>
类通过`class`关键字进行定义
当类内部不需要填充任何内容时,可以非常简单的书写为:
```kotlin
class Empty
```
当需要提供构造函数参数时,写为:
```kotlin
class User(id, name)
```
当然,你也可以为参数指定类型:
```scala
class User(id:int, name:String)
```
如果不指定类型则类型视为`java.lang.Object`
Latte不支持在类内部再定义构造函数,不过,你可以指定参数默认值来创建多个构造函数:
```scala
class Rational(a:int, b:int=1)
```
此时你可以使用`Rational(1)`或者`Rational(1, 2)`来实例化这个类。
--
构造函数内容直接书写在class内:
```kotlin
class Customer(name: String)
logger = Logger.getLogger('')
logger.info("Customer initialized with value ${name}")
```
直接定义在类中的变量,以及构造函数参数,将直接视为字段(Field)。也就是说,上述例子中定义的name和logger都是字段。详见 [3.3 字段和方法](#p3-3) 。
--
使用`private`修饰符来确保类不会被实例化:
```kotlin
private class DontCreateMe
```
在Latte中,所有类都是`public`的,所以,在`class`前的任何“访问关键字”均为该类构造函数的访问关键字。
<h3 id="p3-1-2">3.1.2 继承</h3>
和Java一样:Latte是单继承,并且所有的类都默认继承自`java.lang.Object`。你可以使用类型符号`:`来指定继承的类。继承的规则和Java完全一致。
```kotlin
class Base(p:int)
class Derived(p:int) : Base(p)
```
父类的构造函数参数直接在父类类型后面的括号中指定。
如果使用了父类的无参构造函数,那么可以省略括号:
```kotlin
class Example : Object
```
如果想指定一个类不可被继承,那么需要在它前面加上`val`修饰符:
```kotlin
val class NoInher
```
<h3 id="p3-1-3">3.1.3 抽象类</h3>
使用`abstract`关键字定义抽象类:
```kotlin
abstract class MyAbsClass
abstract f()
```
抽象类规则与Java完全一致。抽象类可以拥有未实现的方法。
继承一个抽象类:
```kotlin
class MyImpl : MyAbsClass
@Override
def f=1
```
<h3 id="p3-1-4">3.1.4 静态成员</h3>
使用`static`定义静态成员。static可以“看作”一个修饰符,也可以“看作”一个结构块的起始。例如:
```js
class TestStatic
static
public val STATIC_FIELD = 'i am a static field'
static func()=1
```
<h2 id="p3-2">3.2 接口</h2>
Latte接口遵循Java的接口定义。使用`interface`关键字:
```kotlin
interface MyInterface
foo()=...
```
定义了`abstract`方法`foo()`。
让一个类实现接口,也使用类型符号`:`。
```kotlin
class Child : MyInterface
foo()=456
child = Child
child.foo /* result is 456 */
child.bar /* result is 123 */
```
接口可以拥有字段,但是和Java规则一样,字段必须是`static public val`(默认也是)。
```kotlin
interface MyInterface
FLAG = 1
```
接口也可以拥有`static`方法(和Java一样)
```js
interface TestStaticMethod
static
method()=111
TestStaticMethod.method() /* result is 111 */
```
<h2 id="p3-3">3.3 字段和方法</h2>
<h3 id="p3-3-1">3.3.1 定义字段</h3>
你可以在类或接口中定义字段:
```kotlin
class Address(name)
public street
public city
public state
public zip
interface MyInterface
FLAG = 1
```
在类中定义的字段默认被`private`修饰,可选的访问修饰符还有`public`, `protected`, `internal`。
字段可以为`static`,只要写在static块中即可(接口默认就是static的,不需要修改)。也可以为不可变的,使用`val`修饰即可。由于构造函数参数也是字段,所以这些修饰符可以直接写在构造函数参数中。例如:
```kotlin
class User(protected val id, public val name)
```
使用字段很简单,直接使用`.`符号访问即可,和Java一致。
```kotlin
val user = User(1, 'latte')
user.name /* result is 'latte' */
val address = Address('home')
address.city = 'hz'
```
Latte提供所谓的`property`支持:使用`getter`和`setter`来定义`property`。详情见 [3.3.3 Accessor](#p3-3-3)
<h3 id="p3-3-2">3.3.2 方法</h3>
Latte支持多种定义方法的语法,先看一个最完整的方法定义:
```scala
def foo(x:int, y:int):int
return x + y
```
如果方法没有参数,那么可以省略里面的内容,甚至省略括号:
```scala
/* 无参数 */
def foo:int
return 1
```
返回类型可以不指定,默认为`java.lang.Object`
```scala
def foo
return 1
```
如果方法体只有一行并返回一个值,可以把在方法定义后直接接`=value`
```scala
def foo = 1
```
如果方法体不存在(即空方法),可以只写一个方法名称(如果有参数再把参数加上)
```scala
def foo
```
上述定义的缩写方式可以混合使用。
此外,如果在定义方法的时候(使用了括号)并且(附带一个修饰符/注解,或者定义了返回值,或者使用了`=`语法),那么可以省略`def`
```
bar():int
foobar()='hello'
fizz():int=1
```
--
如果明确方法不返回值,那么可以附加`Unit`类型。Latte中只能写作`Unit`,代表了Java中的`void`。
但是,在Latte中所有方法都会返回一个值,对于Unit类型的方法,虽然会被编译为void类型,但是依然会返回`Unit`,它是`lt.lang.Unit`类型。
和构造函数参数一样,方法参数也可以设定默认值:
```scala
foo(a, b=1)=a+b
foo(1) /* result is 2 */
```
**注意**,`def`实际上是一个“修饰符”(虽然它什么都不做),并不属于“关键字”。设置`def`是为了和“省略参数的lambda”进行语法上的区分。
例如:
```js
foo(x)
...
```
实际上会被转化为[4.2.2 Lambda](#p4-2-2)中描述的形式:
```js
foo(x)(it->...)
```
所以使用类似于这种方式(`VALID_NAME ( [PARAM [, PARAM, ...]] ) { ... }`)定义的方法,如果没有注解,也没有其他修饰符,会造成歧义,所以不可省略`def`。
方法返回类型为`Unit`时,你依然可以书写`return value`,这个value会被求值,但是不会被返回。
方法非`Unit`时,你也可以直接书写`return`,这时默认返回一个`Unit`。当然,如果返回类型不匹配,编译期依然会报错。
#### 内部方法
Latte支持“内部方法”。所谓内部方法是指在方法内部再定义一个方法。
```
def outer
def inner
```
内部方法可以访问外部的所有变量,并且可以修改它们。
>实际上,Lambda、Procedure都基于“内部方法”特性。所以它们也可以修改捕获到的所有变量。
<h3 id="p3-3-3">3.3.3 Accessor</h3>
accessor分为两种,一种是取值:getter,一种是赋值:setter。
对于getter有两种定义方式:
1. 定义为`get{Name}()`
2. 定义为`{name}()`
对于setter只有一种定义方式:定义为`set{Name}(name)`
```scala
class User(id, name)
def getId=id
setId(id)
this.id = id
def name=name /* 放心,这么写是正确的 */
setName(name)
this.name = name
```
如此定义就可以像直接访问field一样来调用这几个方法了。
```kotlin
user = User(1, 'latte')
println("user_id is ${user.id} and user_name is ${user.name}")
user.id = 2
user.name = 'jvm'
```
不过要注意的是:如果字段暴露给访问者,那么还是优先直接取字段或者对字段赋值。
此外,还有一对特殊的accessor:
* `set(String, ?)` 方法签名要求方法名为"set",第一个参数接受一个String,第二个参数接受一个值,类型没有限制。(只不过使用时只能赋值为该类型的子类型)。
* `get(String)` 方法签名要求方法名为"get",第一个参数接受一个String。
定义有上述accessor的类的实例,在取`o.field`时,将转换为`o.get('field')`。在设置`o1.field = o2`时,将转换为`o1.set('field', o2)`。
<h2 id="p3-4">3.4 修饰符</h2>
<h3 id="p3-4-1">3.4.1 访问修饰符</h3>
Latte有4种访问修饰符:
* public 公有,所有实例均可访问
* protected 受保护,包名相同的类型,或者子类可访问
* internal 包内可访问,包名相同的类型可以访问
* private 私有,只有本类型可访问
访问修饰符可以用来修饰:
* 类
* 接口
* 字段
* 方法
* 构造函数的参数
其中,类访问修饰符并不是规定给类用的。Latte中,类的访问修饰符永远为`public`,这个修饰符是作为构造函数而存在的。
| 位置 | public | protected | internal | private |
|-------|--------|-----------|----------|--------|
| 类 | √ | √ | √ | √ |
| 接口 | √ | | | |
| 字段 | √ | √ | √ | √ |
| 方法 | √ | √ | √ | √ |
| 构造函数参数 | √ | √ | √ | √ |
<h3 id="p3-4-2">3.4.2 其他修饰符</h3>
Latte支持所有Java的修饰符,但是名称可能有改动:
* var 表示可变变量(可省略,默认即为可变)
* val 表示不可变变量,或者不可被重载的方法,或者不可被继承的类
* abstract 抽象类/方法
* native 本地方法
* synchronized 同步方法
* transient 不持久化的字段
* volatile 原子性的字段
* strictfp 方法内的符点计算完全遵循标准
* data 类是一个data class:详见 [3.5 data class](#p3-5)
>`val` 其实就是Java的 `final`
<h2 id="p3-5">3.5 Data Class</h2>
编译器会为data class的每一个字段生成一个getter和setter。并生成无参构造函数,`toString()`, `hashCode()`, `equals(Object)`方法。此外,还会实现Serializable和Cloneable接口。
```kotlin
data class User(val name: String, val age: int)
user = User('cass', 22)
user.toString() /* result is User(name='cass', age=22) */
```
你也可以定义自己的getter/setter/toString/hashCode/equals,编译器将跳过对应方法的生成。
<h2 id="p3-6">3.6 实例化</h2>
Latte不需要`new`关键字就可以实例化一个类。对于无参数的实例化,甚至不需要附加括号:
```kotlin
class Empty
empty = Empty
class User(id, name)
user = User(1, 'latte')
```
当然,Latte也允许你加上`new`:
```scala
empty = new Empty
user = new User(1, "latte")
```
不过,Latte中的`new`的“优先级”非常低,java中的`new X().doSth()`的写法在Latte中必须写为`(new X).doSth`这样的写法。
> Latte中建议不要写new
此外,Latte提供另外一种特殊的实例化方式
调用无参构造函数,并依次赋值:
```python
class open(file, mode)
public encoding
f = open('/User/a', "r", encoding='utf-8')
```
这是一个语法糖,相当于如下Latte代码:
```kotlin
f = open('/User/a', "r")
f.encoding = 'utf-8'
```
即:首先使用不带`=`的参数进行类型的实例化,然后把剩余“参数”看作对accessor的赋值操作。
这个语法糖不光适用于Latte定义的data class,还可以支持任意具有无参构造函数,并有可访问的field或者[accessor](#p3-3-3)的对象。例如标准Java Bean就可以使用这个语法。
```java
class User {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
```
<h2 id="p3-7">3.7 Object Class</h2>
```scala
object DataProviderManager
def registerDataProvider(provider: DataProvider)
...
val allDataProviders: Collection = ...
```
本质上,`object class`定义了一个类,但是这个类不能拥有构造函数的参数,构造函数为private,并拥有一个`static public val`的字段来存放单例。
object class可以继承父类、实现接口,其规则与普通的class完全相同
```scala
object DefaultListener : MouseAdapter()
def mouseClicked(e: MouseEvent):Unit
...
def mouseEntered(e: MouseEvent):Unit
...
```
你可以直接使用类名来获取这个单例对象:
```
val o = DataProviderManager
```
<h2 id="p3-8">3.8 隐式转换</h2>
隐式转换可以帮助你为对象扩展方法,从而更灵活的进行编程。
使用隐式转换分为四步
### 1. 定义一个类用来表示隐式转换后的类型
这一步是可选的,您可以直接隐式转换到已有的类型。这里为了说明方便,单独定义一个:
```scala
class RichInteger(i:Integer)
minutes() = i + " minute" + ( if i != 1 { "s" } else { "" } )
```
### 2. 定义一个隐式对象:
隐式对象是一个普通的`object class`,不过需要用`implicit`修饰它。
在其中定义一些"隐式方法",用来进行隐式类型转换。
“隐式方法”就是普通的方法,不过需要用`implicit`修饰它。
隐式方法有一些要求:参数只能有一个,其类型为隐式转换的源类型(或源类型的父类型);返回类型为目标类型。
例如:我们想要将`Integer`转换为`RichInteger`
```scala
implicit object TestImplicitCast
implicit def cast(i:Integer):RichInteger = RichInteger(i)
```
### 3. 启用隐式类
```scala
import implicit TestImplicitCast
```
使用`import implicit`引入隐式类。这里注意,隐式类必须使用类名引入,而且,即使隐式类与使用者定义在同一个包下,也必须显式引入。这样错用几率会比较小。
### 4. 使用
```
val x = 30 minutes
```
此时,`x`的值即为`"30 minutes"`。运行时会寻找可用的隐式转换,并判断转换后是否能够调用指定方法:发现`Integer => RichInteger`可用,且RichInteger可以调用`minutes()`方法;那么最终执行时的代码相当于`val x = TestImplicitCast.cast(30).minutes()`
<h1 id="p4">4. 函数类和Lambda</h1>
<h2 id="p4-1">4.1 函数类</h2>
<h3 id="p4-1-1">4.1.1 函数式接口 和 函数式抽象类</h3>
Java8中规定了:只有一个未实现方法的接口为“函数式接口”。例如:
```java
interface Consumer {
void consume(Object o);
}
```
只有一个`consume`方法没有被实现,所以它是函数式接口。
类似的,Latte中除了支持Java的函数式接口外,还支持定义“函数式抽象类”。
如果一个类有无参的`public`构造函数,且只有一个未被实现的方法,那么这个类是一个函数式抽象类。例如:
```kotlin
abstract class F
abstract apply()=...
```
<h3 id="p4-1-2">4.1.2 定义函数类</h3>
要使用函数式接口/抽象类,必须有特定的实现。Latte提供一种简便的方式来书写其实现类:
```kotlin
fun Impl(x, y)
return x + y
```
使用`fun`关键字定义“函数类”,参数即为函数式类型未实现方法的参数,内部语句即为实现的方法的语句。
函数类默认可以不附加类型,它在编译期将被视为`FunctionX`,其中X为参数个数。在运行时,`FunctionX`可以转化为任何参数个数相同的类型。
如果确定其实现的类型,可以使用类型符号`:`定义:
```kotlin
fun MyTask : Runnable
println('hello world')
```
<h3 id="p4-1-3">4.1.3 使用函数类</h3>
函数类会被编译为Java的类(`class`),所以,Latte中,它既有函数的特征,又有类的特征:
* 函数类可以被import(就像类一样)
* 可以直接调用这个类,例如:`Impl(1, 2)`。这条语句将实例化`Impl`并执行它实现的方法(这个用法就像lambda一样)
* 可以将它作为值赋值给变量(实际上是调用了无参数构造函数,就像类一样)
总之,对于函数类,你完全可以把它当做一个变量来考虑。
```kotlin
Thread(MyTask).start()
```
同时由于它是正常的类,所以也具有父类型的所有字段/方法:
```kotlin
task = MyTask
task.run()
```
<h3 id="p4-1-4">4.1.4 函数式对象</h3>
在Latte中,对于所有的函数式对象,都可以使用“像调用方法那样的语法”。
```js
task()
```
一个对象是“函数式对象”,有三种情形:
1. 它的类(`.getClass`)的直接父类为函数式抽象类
2. 它的类(`.getClass`)只实现了一个接口,且这个接口是函数式接口
3. 这个对象具有`apply(...)`方法
所以,在Latte中,函数式对象就是函数。
<h2 id="p4-2">4.2 高阶函数和Lambda</h2>
<h3 id="p4-2-1">4.2.1 高阶函数</h3>
如果一个函数可以接受另一个函数作为参数,或者返回一个函数,那么这个函数就是高阶函数。
[4.1.3 使用函数类](#p4.1.3) 中提到过“函数式对象”就是“函数”,所以,任何能够接收(并处理)函数式对象,或者返回函数式对象的函数/方法,就是高阶函数。
如下代码是Java使用stream api的做法:
```java
List<String> strList = ...;
strList.stream().
map(s->Integer.parseInt(s)).
filter(n->n>10).
collect(Collectors.toList())
```
可以看到,map,filter都接受一个函数作为参数,所以它们也可以看作高阶函数。
在Latte中,上述代码可以用Latte的`lambda`语法来表达:
```kotlin
/// :scanner-brace
strList = ...
strList.stream.
map { Integer.parseInt(it) }.
filter { it > 10 }.
collect(Collectors.toList())
```
<h3 id="p4-2-2">4.2.2 Lambda</h3>
Latte支持和Java完全一样的Lambda语法:
```java
strList.stream().
map(s->Integer.parseInt(s)).
filter(n->n>10).
collect(Collectors.toList())
```
从外观上看不出任何差别?没错,语法上完全一致(特别是使用大括号区分层次的时候)。
使用缩进的情况下,多行lambda可以这么写:
```coffee
strList.stream.map(
s-> s = s.subString(1)
Integer.parseInt(s)
)
```
>注:可以不写return,因为Latte会帮你把需要的return补上。这个特性适用于任何“编译为JVM方法”的语法。
如果lambda只有一个参数(例如上述代码),那么名称和`->`可以被省略。其中,名称会被标记为`it`。
```js
strList.stream.map
it = it.subString(1)
Integer.parseInt(it)
```
这个特性可以让代码更简洁,同时也可以构造更灵活的内部DSL
```python
latteIsWrittenInJava
if it is great
star the repo
```
>做一丁点处理后,这是可以正常编译的代码!(不需要hack编译器)
可以写成一行
```coffee
latteIsWrittenInJava { if it is great { star the repo }}
```
此外Lambda的变量捕捉机制和Java不同。Latte可以在Lambda中的任何地方修改被捕获的变量。
```coffee
var count = 0
(1 to 10).forEach { count+=it }
println(count)
```
<h1 id="p5">5. 其他</h1>
<h2 id="p5-1">5.1 Json 集合</h2>
Latte支持Json格式的字面量。
Json数组:
```js
var list = [1, 2, 3, 4]
```
使用Json的数组语法,可以创建一个`java.util.LinkedList`实例,也可以创建一个数组。这取决于你将它赋值给什么类型的变量,或者使用`as`符号把它转换为什么类型。
int数组:
```c#
[1, 2, 3, 4] as []int
```
Object数组:
```c#
[1, 2, 3, 4] as []Object
```
在Latte中,你可以将一个`java.util.List`类型的对象转换为其它种类的Object。该特性将尝试使用无参构造函数构造目标类型对象,然后对每一个List中的元素,调用add方法。
```kotlin
class JsonArray
list = []
def add(o)=list.add(o)
res = [1,2,3] as JsonArray
/*
same as:
res = JsonArray()
for item in [1,2,3]
res.add(item)
*/
```
--
Json对象:
```swift
var map = [
'one': 1,
'two': 2,
'three', 3
]
```
其中`,`是不必须的。“换行”和`,`都可以用来来分割list的元素,以及map的entry
在Latte中,你还可以把一个"所有键都是string"的map转换为指定类型的对象。
```kotlin
data class Bean(hello, foo)
res = [
"hello" : "world"
"foo" : "bar
] as Bean
/* res will be Bean(hello=world, foo=bar) */
```
该转换将首先用无参构造函数构造指定类型,然后对map中每一个键,进行Latte的赋值操作。
不光可以显式的转换,还可以作为方法参数隐式转换过去。
<h2 id="p5-2">5.2 范围</h2>
在Latte中可以使用`to`或者`until`运算符来定义一个“范围”(range)。这两个运算符只接受整数作为参数。它的结果是一个`java.util.List`实例。
使用`to`可以定义一个包含头和尾的范围,使用`until`可以定义一个只包含头,不包含尾的范围:
```scala
oneToTen = 1 to 10 /* [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] */
oneToNine = 1 until 10 /* [1, 2, 3, 4, 5, 6, 7, 8, 9] */
```
range也支持尾比头更小:
```scala
tenToOne = 10 to 1 /* [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] */
tenToTwo = 10 to 1 /* [10, 9, 8, 7, 6, 5, 4, 3, 2] */
```
>范围的实现基于“隐式类型转换”,Latte默认定义的RichInt提供了`to`和`until`方法。
<h2 id="p5-3">5.3 类型检查与转换</h2>
<h3 id="p5-3-1">5.3.1 类型检查</h3>
Latte为静态类型和动态类型混合的语言。总体来说,类型检查比较宽松,并且不一定在编译期检查。
Latte不要求显式转换,在赋值、方法return时,值会自动的尝试转换为需要的类型。
```kotlin
class Base
class Sub:Base
var x:Base = Sub
var y:Sub = x
```
其中在赋值给`y`时,自动增加了一个类型转换。
<h3 id="p5-3-2">5.3.2 类型转换</h3>
在调用方法时,自动转换并不会做,因为并不确定变量的类型,也不确定方法参数需要哪种类型。
如果编译期没有找到方法,则会在运行时再获取参数对象的类型并进行方法的寻找。如果一定要在编译期确定调用何种方法,可以手动转换类型。
```kotlin
class Data
i:int
def setI(i:int) { this.i=i }
fun call(x)
var data:Data = Data
data.setI(x as int)
```
上述例子中,x类型不确定,但是可以显式地转化为int。
<h2 id="p5-4">5.4 运算符绑定</h2>
Latte支持运算符“绑定”。Latte的运算符绑定策略非常简单。每个运算符都看作方法调用。`a+b`看作`a.add(b)`,`a*b`看作`a.multiply(b)`,`!a`看作`a.not()`
这些运算符绑定依照`BigInteger`和`BigDecimal`的命名,所以你可以直接使用运算符来计算大数。
```kotlin
a = BigInteger(3)
b = BigInteger(4)
c = a + b
```
若需要绑定运算符,只需要写出签名相符的方法即可,例如定义一个`Rational`类来表示分数:
```kotlin
class Rational(a, b)
add(that: Rational)=Rational(this.a * that.b + that.a * this.b, this.a * that.b)
toString():String="${a}/${b}"
a = Rational(1, 4) /* 1/4 */
b = Rational(3, 7) /* 3/7 */
c = a + b /* 19/28 */
```
有一些运算符是“复合”的,即:它们可以由多个操作构成。例如`++a`,就可以由`(a = a + 1 , return a)`构成。这类运算符不提供绑定,如果有需要,请绑定它们的展开式用到的运算符。
下表描述了所有提供绑定的运算符,以及一些展开式规则:
| 运算符 | 方法签名 |
|----------|-------------------------|
| a:::b | a.concat(b) |
| a * b | a.multiply(b) |
| a / b | a.divide(b) |
| a % b | a.remainder(b) |
| a + b | a.add(b) |
| a - b | a.subtract(b) |
| a << b | a.shiftLeft(b) |
| a >> b | a.shiftRight(b) |
| a >>> b | a.unsignedShiftRight(b) |
| a > b | a.gt(b) |
| a < b | a.lt(b) |
| a >= b | a.ge(b) |
| a <= b | a.le(b) |
| a == b | a.eq(b) |
| a != b | !a.ne(b) |
| a in b | b.contains(a) |
| a & b | a.`and`(b) |
| a ^ b | a.xor(b) |
| a | b | a.`or`(b) |
| !a | a.logicNot() |
| ~a | a.not() |
| -a | a.negate() |
| a\[0\] | a.get(0) |
| a\[0, 1\] | a.get(0, 1) |
> `+a` 这种用法在Latte中不对`+`做任何处理,当做`a`
> 上面的`a[0, 1]`用法,如果a是一个二维数组,则相当于java的`a[0][1]`
> Latte对所有对象均可隐式转换到`RichObject`,在其中提供了`==`和`!=`的绑定,其中会调用对象的`equals`方法
Latte的运算符优先级和Java完全一致,而Latte特有的运算符优先级如下:
* `in` 和 `==` 优先级相同
* `:::` 优先级最高
由于`==`被绑定到equals方法,所以检查引用相同使用`===`,引用不同使用`!==`。
此外,Latte还提供两个运算符`is`和`not`,它除了可以检查引用、equals,在右侧对象是一个Class实例时还可以检查左侧对象是否为右侧对象的实例。
> 虽然`==`绑定到equals方法,但是如果写为`null==x`,编译器能够知道左侧一定为null,这时会检查null值而不是调用equals
> `!=`同理。
| 运算符 | 展开式 |
|--------|----------------------------------|
| a?=b | a = a ? b |
| a++ | tmp = a , a = a + 1 , return tmp |
| ++a | a = a + 1 , return a |
| a-- | tmp = a , a = a - 1 , return tmp |
| --a | a = a - 1 , return a |
> 其中`?=`的`?`代表任何二元运算符
---
Latte中,和普通的方法调用不同,运算符前不需要附加`.`,也不需要对参数包裹括号。但是因为Latte的运算符和方法调用是一回事,所以为了一致性,普通方法调用也可以将方法名看作运算符来书写:
```scala
list isEmpty // list.isEmpty()
map put "Feb", 2 // map.put("Feb", 2)
.println o // println(o)
```
使用逗号分隔多个参数。使用`.`表示直接调用方法(而不是在某个对象或者某个类上调用)。
<h2 id="p5-5">5.5 异常</h2>
Latte和Java总体上是类似的,但是仍有多处不同:
* Latte没有`checked exception`
* Latte可以`throw`任何类型的对象,比如`throw 'error-message'`
* Latte可以`catch`任何类型的对象
* 由于上一条,Latte不提供`catch(Type e)`这种写法,需使用if-elseif-else来处理
```kotlin
fun isGreaterThanZero(x)
if x <= 0 { throw '${x} is littler than 0' }
var a = -1
try
isGreaterThanZero(a)
catch e
e.toCharArray /* succeed. `e` is a String */
finally
a = 1
```
<h2 id="p5-6">5.6 注解</h2>
Latte使用`annotation`关键字定义注解
```kotlin
annotation Anno
a:int = 1
b:long
```
Latte中的注解默认为运行时可见的(而Java中默认不可见)。
可以使用`java::lang::annotation::Retention`注解重新规定可见性。
同时默认为可以标注在所有地方(和Java一样)。
可以使用`java::lang::annotation::Target`注解重新规定标注位置。
> 因为annotation是一个关键字,所以导入包时需要用 点号 包围 `annotation`这个单词。
---
Latte的注解使用方式和Java一致
```kotlin
class PrintSelf
@Override
toString():String='PrintSelf'
```
不过有一点要注意,Latte的注解不能和其所标注的对象在同一行,除非加一个逗号,比如:
```scala
@Anno1,@Anno2,method()=...
```
和Java一样,注解的value参数可以省略`value`这个键本身。
```java
@Value1('value')
@Value2(value='value')
```
<h2 id="p5-7">5.7 过程(Procedure)</h2>
Latte支持把一组语句当做一个值,这个特性称作“过程”。
过程由小括号开始,小括号结束。
用这个特性可以省略不必要的中间变量声明。
```kotlin
class Rational(a, b)
toString():String = a + (
if b == 1
return ""
else
return "/" + b
)
```
过程最终也是编译为“方法”的,可以省略最后的`return`,所以可以写为:
```kotlin
;; :scanner-brace
class Rational(a, b)
toString():String = a + ( if b==1 {""} else {"/" + b} )
```
<h2 id="p5-8">5.8 参数可用性检查</h2>
Latte支持**参数**上的null值或“空”值检查,分别使用`nonnull`和`nonempty`修饰符。
由于Latte的`Unit`方法也返回一个值(`Unit`),所以在`nonnull`中不光会检查null值,还会检查Unit。
如果出现null则会立即抛出`java.lang.NullPointerException`异常
如果出现Unit则会立即抛出`java.lang.IllegalArgumentException`异常
```scala
def add(nonnull a, nonnull b)= a + b
add(null, 1) /* 抛出NullPointerException */
add(Unit, 2) /* 抛出IllegalArgumentException */
```
对于`nonempty`,检查的范围更广。首先Latte会将这个值转换为`bool`类型(Latte中任何类型都可以转为bool)
如果结果为`false`则会抛出异常`java.lang.IllegalArgumentException`
```scala
def listNotEmpty(nonempty list)
listNotEmpty([]) /* 抛出 IllegalArgumentException */
```
在转换为`bool`时,Latte会尝试
1. 如果是null,则返回false
2. 如果是Unit,则返回false
3. 如果是Boolean类型,则返回其对应的`bool`值
4. 如果是数字类型,则:如果转换为`double`的结果是0,那么返回false,否则返回true
5. 如果是Character类型,则:如果转换为`int`的结果是0,那么返回false,否则返回true
6. 如果这个对象带有`def isEmpty:bool`或者`def isEmpty:Boolean`方法,那么调用之,并返回相应结果
7. 返回true
<h2 id="p5-9">5.9 解构</h2>
<h3 id="p5-9-1">5.9.1 解构用法</h3>
解构指的是将一个对象分解为其组成部分的多个对象。
例如有如下定义和实例化:
```kotlin
data class Bean(a,b)
val bean = Bean(1,2)
```
可以知道,bean是由`1`和`2`组成的,它应当被分解为(1,2)。
Latte提供这样简化的分解:
```scala
val (x,y) = bean
```
定义了x和y,并分别赋值为1、2。
<h3 id="p5-9-2">5.9.2 解构实现方式</h3>
使用解构,首先需要定义一个static方法`unapply`:
```java
class X {
static {
unapply(o)=...
}
}
```
这个方法需要接受一个参数,表示被解构的对象,并返回`null`或一个`java::util::List`实例。
如果返回`null`则说明解构失败,如果返回`List`实例,则表示会被分解为存在于列表中的对象。
如果解构失败,则解构表达式返回`false`,否则返回`true`。
可以指定使用“带有unapply方法的类”来执行解构:
```scala
Bean(x,y) <- bean
```
如果没有指定,则尝试使用右侧对象的类中的unapply方法进行解构。
```scala
(x,y) <- bean /* 相当于 Bean(x,y) <- bean */
```
如果没有指定类型,则可以将`<-`替换为`=`。
解构可以放在`if`中使用:
```scala
if List(a,b,c) <- o
println("result is ${a},${b},${c}")
else
println("destruct failed!")
```
<h2 id="p5-10">5.10 模式匹配</h2>
和`scala`一样,`Latte`不提供`java`的`switch`语句,但是提供更强大的模式匹配。
```scala
def doMatch(o) = o match
case 1 => ... /* 根据值匹配 */
case b:Apple => ... /* 检查类型并定义一个新的变量 */
case _:Banana => ... /* 根据类型匹配 */
case Bean(x,y) => ... /* 根据解构匹配 */
case Bean(1, Bean(x, _:Integer)) => ... /* 多重模式 */
case Bean(x,y) if x > 0 => ... /* 解构后再做判断 */
case _ => ... /* 匹配所有(默认行为) */
```
模式匹配会从上到下依次尝试匹配。如果匹配成功则进入该分支执行语句,最终返回一个值(也可能返回`Unit`)。如果匹配失败,则会抛出`lt::lang::MatchError`。
任何匹配模式都可以添加if语句,仅当if判断成立时才会进入执行。
<h1 id="p6">6. Java交互</h1>
在设计时就考虑了Latte和Java的互操作。所以它们基本是无缝衔接的。
<h2 id="p6-1">6.1 在Latte中调用Java代码</h2>
实际上这里不会出现任何问题。Latte源代码最终是编译到Java字节码的,所以Latte调用Java就像Latte调用自己一样。
而设计时也考虑到了互通性,几乎所有Latte特性都可以通过编写Java源代码来模拟。
这里给出一些Latte与Java相同语义的表达:
### 1. 规定变量和它的类型
在Field操作时会有交互。
java:
```java
Integer integer;
List list;
final int anInt;
Object obj;
```
latte:
```scala
integer : Integer
list : List
val anInt : int
obj
```
Latte可以使用`var`表示可变变量,不过也可以不写,默认即为可变变量。Object类型不需要写,同样也是默认值。
### 2. 定义方法、参数类型和返回类型
在调用方法时会有交互。
java:
```java
void method1() {}
Object method2() { return null; }
int method3(int x) { return x; }
```
latte:
```kotlin
method1():Unit=...
method2()=null
method3(x:int):int = x
```
### 3. 获取java类,判断类型
java:
```java
Class c = Object.class;
if (s instanceof String) {}
```
latte:
```typescript
c = type Object
if s is type String
```
<h2 id="p6-2">6.2 在Java中调用Latte代码</h2>
如果是已编译的Latte二进制文件,那么加载到class-path中,直接在Java中调用即可。Latte在设计时非常小心的不暴露任何“不一致状态”给Java,所以除了反射访问private外,尽管放心的调用吧。
<h3 id="p6-2-1">6.2.1 在Java中编译Latte</h3>
如果是Latte源文件,则需要使用Latte-compiler编译。
```java
import lt.repl.Compiler;
Compiler compiler = new Compiler();
ClassLoader cl = compiler.compile(new HashMap<String, Reader>(){{
put('source-name.lt', new InputStreamReader(...));
}});
Class<?> cls = cl.loadClass('...');
```
<h3 id="p6-2-2">6.2.2 在Java中执行eval</h3>
Latte支持`eval`,在latte代码中`eval('...')`即可。在Java中,你也可以直接调用
```java
lt.lang.Utils.eval("[\"id\":1,\"lang\":\"java\"]");
```
或者使用`Evaluator`获取完整的eval支持:
```java
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
Evaluator evaluator = new Evaluator(new ClassPathLoader(Thread.currentThread().getContextClassLoader()));
evaluator.setScannerType(Evaluator.SCANNER_TYPE_BRACE);
evaluator.put("list", list); // 把list对象放进Evaluator上下文中
Evaluator.Entry entry = evaluator.eval("" +
"import java::util::stream::Collectors._\n" +
"list.stream.filter{it > 0}.collect(toList())");
List newList = (List) entry.result;
// newList is [3, 4, 5]
```
<h3 id="p6-2-3">6.2.3 在Java中执行Latte脚本</h3>
Latte支持脚本,脚本以源代码形式呈现。所以你可以构造一个`ScriptCompiler`来执行并取得脚本结果。
```java
ScriptCompiler.Script script = scriptCompiler.compile("script", "return 1");
script.run().getResult();
// 或者 run(new String[]{...}) 来指定启动参数
```
ScriptCompiler有多个`compile`的重载,各种情况都可以方便的调用。
|
Java
|
<?xml version="1.0" ?><!DOCTYPE TS><TS language="th_TH" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Linkcoin</source>
<translation>เกี่ยวกับ บิตคอย์น</translation>
</message>
<message>
<location line="+39"/>
<source><b>Linkcoin</b> version</source>
<translation><b>บิตคอย์น<b>รุ่น</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The Linkcoin developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>สมุดรายชื่อ</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>ดับเบิลคลิก เพื่อแก้ไขที่อยู่ หรือชื่อ</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>สร้างที่อยู่ใหม่</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>คัดลอกที่อยู่ที่ถูกเลือกไปยัง คลิปบอร์ดของระบบ</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Linkcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Linkcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Linkcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>ลบ</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Linkcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>ส่งออกรายชื่อทั้งหมด</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>ส่งออกผิดพลาด</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>ไม่สามารถเขียนไปยังไฟล์ %1</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>ชื่อ</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>ที่อยู่</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(ไม่มีชื่อ)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>ใส่รหัสผ่าน</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>รหัสผา่นใหม่</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>กรุณากรอกรหัสผ่านใหม่อีกครั้งหนึ่ง</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>กระเป๋าสตางค์ที่เข้ารหัส</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>เปิดกระเป๋าสตางค์</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>ถอดรหัสกระเป๋าสตางค์</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>เปลี่ยนรหัสผ่าน</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>กรอกรหัสผ่านเก่าและรหัสผ่านใหม่สำหรับกระเป๋าสตางค์</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>ยืนยันการเข้ารหัสกระเป๋าสตางค์</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR LITECOINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>กระเป๋าสตางค์ถูกเข้ารหัสเรียบร้อยแล้ว</translation>
</message>
<message>
<location line="-56"/>
<source>Linkcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your linkcoins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>การเข้ารหัสกระเป๋าสตางค์ผิดพลาด</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>รหัสผ่านที่คุณกรอกไม่ตรงกัน</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Show information about Linkcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Linkcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Linkcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Linkcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About Linkcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Linkcoin addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Linkcoin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Linkcoin client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Linkcoin network</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Linkcoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Linkcoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Linkcoin address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Linkcoin-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start Linkcoin after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start Linkcoin on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Linkcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the Linkcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Linkcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show Linkcoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Linkcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Linkcoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start linkcoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the Linkcoin-Qt help message to get a list with possible Linkcoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>Linkcoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Linkcoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the Linkcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Linkcoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Linkcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Linkcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Linkcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Linkcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter Linkcoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Linkcoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>ที่อยู่</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>วันนี้</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>ชื่อ</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>ที่อยู่</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>ส่งออกผิดพลาด</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>ไม่สามารถเขียนไปยังไฟล์ %1</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Linkcoin version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or linkcoind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: linkcoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: linkcoind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9333 or testnet: 19333)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9332 or testnet: 19332)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=linkcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Linkcoin Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Linkcoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Linkcoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Linkcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Linkcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Linkcoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Linkcoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS>
|
Java
|
#region Using directives
using System;
using System.Data;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using Nettiers.AdventureWorks.Entities;
using Nettiers.AdventureWorks.Data;
#endregion
namespace Nettiers.AdventureWorks.Data.Bases
{
///<summary>
/// This class is the base class for any <see cref="SalesOrderHeaderSalesReasonProviderBase"/> implementation.
/// It exposes CRUD methods as well as selecting on index, foreign keys and custom stored procedures.
///</summary>
public abstract partial class SalesOrderHeaderSalesReasonProviderBase : SalesOrderHeaderSalesReasonProviderBaseCore
{
} // end class
} // end namespace
|
Java
|
# Be sure to restart your server when you modify this file.
Hypermedia::Application.config.session_store :cookie_store, key: '_hypermedia_session'
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rails generate session_migration")
# Hypermedia::Application.config.session_store :active_record_store
|
Java
|
#ifndef ANONCOIN_MINER_H
#define ANONCOIN_MINER_H
#include <stdint.h>
typedef long long int64;
typedef unsigned long long uint64;
class CBlock;
class CBlockHeader;
class CBlockIndex;
struct CBlockTemplate;
class CReserveKey;
class CScript;
#ifdef ENABLE_WALLET
class CWallet;
void AnoncoinMiner(CWallet *pwallet);
#endif
/** Run the miner threads */
void GenerateAnoncoins(bool fGenerate, CWallet* pwallet);
/** Generate a new block, without valid proof-of-work */
CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn);
CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey);
/** Modify the extranonce in a block */
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
/** Do mining precalculation */
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
/** Check mined block */
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
/** Base sha256 mining transform */
void SHA256Transform(void* pstate, void* pinput, const void* pinit);
#endif
|
Java
|
<TS language="hi_IN" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Create a new address</source>
<translation>नया पता लिखिए !</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>चुनिन्दा पते को सिस्टम क्लिपबोर्ड पर कापी करे !</translation>
</message>
<message>
<source>&Copy Address</source>
<translation>&पता कॉपी करे</translation>
</message>
<message>
<source>&Delete</source>
<translation>&मिटाए !!</translation>
</message>
<message>
<source>Copy &Label</source>
<translation>&लेबल कॉपी करे </translation>
</message>
<message>
<source>&Edit</source>
<translation>&एडिट</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<source>Label</source>
<translation>लेबल</translation>
</message>
<message>
<source>Address</source>
<translation>पता</translation>
</message>
<message>
<source>(no label)</source>
<translation>(कोई लेबल नही !)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Enter passphrase</source>
<translation>पहचान शब्द/अक्षर डालिए !</translation>
</message>
<message>
<source>New passphrase</source>
<translation>नया पहचान शब्द/अक्षर डालिए !</translation>
</message>
<message>
<source>Repeat new passphrase</source>
<translation>दोबारा नया पहचान शब्द/अक्षर डालिए !</translation>
</message>
<message>
<source>Encrypt wallet</source>
<translation>एनक्रिप्ट वॉलेट !</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>वॉलेट खोलने के आपका वॉलेट पहचान शब्द्/अक्षर चाईए !</translation>
</message>
<message>
<source>Unlock wallet</source>
<translation>वॉलेट खोलिए</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>वॉलेट डीक्रिप्ट( विकोड) करने के लिए आपका वॉलेट पहचान शब्द्/अक्षर चाईए !</translation>
</message>
<message>
<source>Decrypt wallet</source>
<translation> डीक्रिप्ट वॉलेट</translation>
</message>
<message>
<source>Change passphrase</source>
<translation>पहचान शब्द/अक्षर बदलिये !</translation>
</message>
<message>
<source>Confirm wallet encryption</source>
<translation>वॉलेट एनक्रिपशन को प्रमाणित कीजिए !</translation>
</message>
<message>
<source>Wallet encrypted</source>
<translation>वॉलेट एनक्रिप्ट हो गया !</translation>
</message>
<message>
<source>Wallet encryption failed</source>
<translation>वॉलेट एनक्रिप्ट नही हुआ!</translation>
</message>
<message>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>वॉलेट एनक्रिपशन नाकाम हो गया इंटर्नल एरर की वजह से! आपका वॉलेट एनक्रीपत नही हुआ है!</translation>
</message>
<message>
<source>The supplied passphrases do not match.</source>
<translation>आपके द्वारा डाले गये पहचान शब्द/अक्षर मिलते नही है !</translation>
</message>
<message>
<source>Wallet unlock failed</source>
<translation>वॉलेट का लॉक नही खुला !</translation>
</message>
<message>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>वॉलेट डीक्रिप्ट करने के लिए जो पहचान शब्द/अक्षर डाले गये है वो सही नही है!</translation>
</message>
<message>
<source>Wallet decryption failed</source>
<translation>वॉलेट का डीक्रिप्ट-ष्ण असफल !</translation>
</message>
</context>
<context>
<name>BanTableModel</name>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<source>Synchronizing with network...</source>
<translation>नेटवर्क से समकालिक (मिल) रहा है ...</translation>
</message>
<message>
<source>&Overview</source>
<translation>&विवरण</translation>
</message>
<message>
<source>Show general overview of wallet</source>
<translation>वॉलेट का सामानया विवरण दिखाए !</translation>
</message>
<message>
<source>&Transactions</source>
<translation>& लेन-देन
</translation>
</message>
<message>
<source>Browse transaction history</source>
<translation>देखिए पुराने लेन-देन के विवरण !</translation>
</message>
<message>
<source>E&xit</source>
<translation>बाहर जायें</translation>
</message>
<message>
<source>Quit application</source>
<translation>अप्लिकेशन से बाहर निकलना !</translation>
</message>
<message>
<source>&Options...</source>
<translation>&विकल्प</translation>
</message>
<message>
<source>&Backup Wallet...</source>
<translation>&बैकप वॉलेट</translation>
</message>
<message>
<source>Change the passphrase used for wallet encryption</source>
<translation>पहचान शब्द/अक्षर जो वॉलेट एनक्रिपशन के लिए इस्तेमाल किया है उसे बदलिए!</translation>
</message>
<message>
<source>FairCoin</source>
<translation>बीटकोइन</translation>
</message>
<message>
<source>Wallet</source>
<translation>वॉलेट</translation>
</message>
<message>
<source>&File</source>
<translation>&फाइल</translation>
</message>
<message>
<source>&Settings</source>
<translation>&सेट्टिंग्स</translation>
</message>
<message>
<source>&Help</source>
<translation>&मदद</translation>
</message>
<message>
<source>Tabs toolbar</source>
<translation>टैबस टूलबार</translation>
</message>
<message>
<source>%1 behind</source>
<translation>%1 पीछे</translation>
</message>
<message>
<source>Error</source>
<translation>भूल</translation>
</message>
<message>
<source>Warning</source>
<translation>चेतावनी</translation>
</message>
<message>
<source>Information</source>
<translation>जानकारी</translation>
</message>
<message>
<source>Up to date</source>
<translation>नवीनतम</translation>
</message>
<message>
<source>Sent transaction</source>
<translation>भेजी ट्रांजक्शन</translation>
</message>
<message>
<source>Incoming transaction</source>
<translation>प्राप्त हुई ट्रांजक्शन</translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>वॉलेट एन्क्रिप्टेड है तथा अभी लॉक्ड नहीं है</translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>वॉलेट एन्क्रिप्टेड है तथा अभी लॉक्ड है</translation>
</message>
</context>
<context>
<name>ClientModel</name>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Amount:</source>
<translation>राशि :</translation>
</message>
<message>
<source>Amount</source>
<translation>राशि</translation>
</message>
<message>
<source>Date</source>
<translation>taareek</translation>
</message>
<message>
<source>Confirmed</source>
<translation>पक्का</translation>
</message>
<message>
<source>Copy address</source>
<translation>पता कॉपी करे</translation>
</message>
<message>
<source>Copy label</source>
<translation>लेबल कॉपी करे </translation>
</message>
<message>
<source>Copy amount</source>
<translation>कॉपी राशि</translation>
</message>
<message>
<source>(no label)</source>
<translation>(कोई लेबल नही !)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>Edit Address</source>
<translation>पता एडिट करना</translation>
</message>
<message>
<source>&Label</source>
<translation>&लेबल</translation>
</message>
<message>
<source>&Address</source>
<translation>&पता</translation>
</message>
<message>
<source>New receiving address</source>
<translation>नया स्वीकार्य पता</translation>
</message>
<message>
<source>New sending address</source>
<translation>नया भेजने वाला पता</translation>
</message>
<message>
<source>Edit receiving address</source>
<translation>एडिट स्वीकार्य पता </translation>
</message>
<message>
<source>Edit sending address</source>
<translation>एडिट भेजने वाला पता</translation>
</message>
<message>
<source>The entered address "%1" is already in the address book.</source>
<translation>डाला गया पता "%1" एड्रेस बुक में पहले से ही मोजूद है|</translation>
</message>
<message>
<source>Could not unlock wallet.</source>
<translation>वॉलेट को unlock नहीं किया जा सकता|</translation>
</message>
<message>
<source>New key generation failed.</source>
<translation>नयी कुंजी का निर्माण असफल रहा|</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<source>version</source>
<translation>संस्करण</translation>
</message>
<message>
<source>Usage:</source>
<translation>खपत :</translation>
</message>
</context>
<context>
<name>Intro</name>
<message>
<source>Error</source>
<translation>भूल</translation>
</message>
</context>
<context>
<name>OpenURIDialog</name>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>Options</source>
<translation>विकल्प</translation>
</message>
<message>
<source>W&allet</source>
<translation>वॉलेट</translation>
</message>
<message>
<source>&OK</source>
<translation>&ओके</translation>
</message>
<message>
<source>&Cancel</source>
<translation>&कैन्सल</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<source>Form</source>
<translation>फार्म</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
</context>
<context>
<name>PeerTableModel</name>
</context>
<context>
<name>QObject</name>
<message>
<source>Amount</source>
<translation>राशि</translation>
</message>
<message>
<source>N/A</source>
<translation>लागू नही
</translation>
</message>
</context>
<context>
<name>QRImageWidget</name>
</context>
<context>
<name>RPCConsole</name>
<message>
<source>N/A</source>
<translation>लागू नही
</translation>
</message>
<message>
<source>&Information</source>
<translation>जानकारी</translation>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<source>&Amount:</source>
<translation>राशि :</translation>
</message>
<message>
<source>&Label:</source>
<translation>लेबल:</translation>
</message>
<message>
<source>Copy label</source>
<translation>लेबल कॉपी करे </translation>
</message>
<message>
<source>Copy amount</source>
<translation>कॉपी राशि</translation>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>Copy &Address</source>
<translation>&पता कॉपी करे</translation>
</message>
<message>
<source>Address</source>
<translation>पता</translation>
</message>
<message>
<source>Amount</source>
<translation>राशि</translation>
</message>
<message>
<source>Label</source>
<translation>लेबल</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<source>Date</source>
<translation>taareek</translation>
</message>
<message>
<source>Label</source>
<translation>लेबल</translation>
</message>
<message>
<source>Amount</source>
<translation>राशि</translation>
</message>
<message>
<source>(no label)</source>
<translation>(कोई लेबल नही !)</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Send Coins</source>
<translation>सिक्के भेजें|</translation>
</message>
<message>
<source>Amount:</source>
<translation>राशि :</translation>
</message>
<message>
<source>Send to multiple recipients at once</source>
<translation>एक साथ कई प्राप्तकर्ताओं को भेजें</translation>
</message>
<message>
<source>Balance:</source>
<translation>बाकी रकम :</translation>
</message>
<message>
<source>Confirm the send action</source>
<translation>भेजने की पुष्टि करें</translation>
</message>
<message>
<source>Confirm send coins</source>
<translation>सिक्के भेजने की पुष्टि करें</translation>
</message>
<message>
<source>Copy amount</source>
<translation>कॉपी राशि</translation>
</message>
<message>
<source>The amount to pay must be larger than 0.</source>
<translation>भेजा गया अमाउंट शुन्य से अधिक होना चाहिए|</translation>
</message>
<message>
<source>(no label)</source>
<translation>(कोई लेबल नही !)</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<source>A&mount:</source>
<translation>अमाउंट:</translation>
</message>
<message>
<source>Pay &To:</source>
<translation>प्राप्तकर्ता:</translation>
</message>
<message>
<source>Enter a label for this address to add it to your address book</source>
<translation>आपकी एड्रेस बुक में इस एड्रेस के लिए एक लेबल लिखें</translation>
</message>
<message>
<source>&Label:</source>
<translation>लेबल:</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt-A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Clipboard से एड्रेस paste करें</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt-P</translation>
</message>
<message>
<source>Pay To:</source>
<translation>प्राप्तकर्ता:</translation>
</message>
</context>
<context>
<name>ShutdownWindow</name>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<source>Alt+A</source>
<translation>Alt-A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Clipboard से एड्रेस paste करें</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt-P</translation>
</message>
<message>
<source>Signature</source>
<translation>हस्ताक्षर</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<source>[testnet]</source>
<translation>[टेस्टनेट]</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
</context>
<context>
<name>TransactionDesc</name>
<message>
<source>Open until %1</source>
<translation>खुला है जबतक %1</translation>
</message>
<message>
<source>%1/unconfirmed</source>
<translation>%1/अपुष्ट</translation>
</message>
<message>
<source>%1 confirmations</source>
<translation>%1 पुष्टियाँ</translation>
</message>
<message>
<source>Date</source>
<translation>taareek</translation>
</message>
<message>
<source>Transaction ID</source>
<translation>ID</translation>
</message>
<message>
<source>Amount</source>
<translation>राशि</translation>
</message>
<message>
<source>true</source>
<translation>सही</translation>
</message>
<message>
<source>false</source>
<translation>ग़लत</translation>
</message>
<message>
<source>, has not been successfully broadcast yet</source>
<translation>, अभी तक सफलतापूर्वक प्रसारित नहीं किया गया है</translation>
</message>
<message>
<source>unknown</source>
<translation>अज्ञात</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<source>Transaction details</source>
<translation>लेन-देन का विवरण</translation>
</message>
<message>
<source>This pane shows a detailed description of the transaction</source>
<translation> ये खिड़की आपको लेन-देन का विस्तृत विवरण देगी !</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<source>Date</source>
<translation>taareek</translation>
</message>
<message>
<source>Type</source>
<translation>टाइप</translation>
</message>
<message>
<source>Open until %1</source>
<translation>खुला है जबतक %1</translation>
</message>
<message>
<source>Confirmed (%1 confirmations)</source>
<translation>पक्के ( %1 पक्का करना)</translation>
</message>
<message>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>यह ब्लॉक किसी भी और नोड को मिला नही है ! शायद यह ब्लॉक कोई भी नोड स्वीकारे गा नही !</translation>
</message>
<message>
<source>Generated but not accepted</source>
<translation>जेनरेट किया गया किंतु स्वीकारा नही गया !</translation>
</message>
<message>
<source>Label</source>
<translation>लेबल</translation>
</message>
<message>
<source>Received with</source>
<translation>स्वीकार करना</translation>
</message>
<message>
<source>Received from</source>
<translation>स्वीकार्य ओर से</translation>
</message>
<message>
<source>Sent to</source>
<translation>भेजा गया</translation>
</message>
<message>
<source>Payment to yourself</source>
<translation>भेजा खुद को भुगतान</translation>
</message>
<message>
<source>Mined</source>
<translation>माइंड</translation>
</message>
<message>
<source>(n/a)</source>
<translation>(लागू नहीं)</translation>
</message>
<message>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>ट्रांसेक्शन स्तिथि| पुष्टियों की संख्या जानने के लिए इस जगह पर माउस लायें|</translation>
</message>
<message>
<source>Date and time that the transaction was received.</source>
<translation>तारीख तथा समय जब ये ट्रांसेक्शन प्राप्त हुई थी|</translation>
</message>
<message>
<source>Type of transaction.</source>
<translation>ट्रांसेक्शन का प्रकार|</translation>
</message>
<message>
<source>Amount removed from or added to balance.</source>
<translation>अमाउंट बैलेंस से निकला या जमा किया गया |</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<source>All</source>
<translation>सभी</translation>
</message>
<message>
<source>Today</source>
<translation>आज</translation>
</message>
<message>
<source>This week</source>
<translation>इस हफ्ते</translation>
</message>
<message>
<source>This month</source>
<translation>इस महीने</translation>
</message>
<message>
<source>Last month</source>
<translation>पिछले महीने</translation>
</message>
<message>
<source>This year</source>
<translation>इस साल</translation>
</message>
<message>
<source>Range...</source>
<translation>विस्तार...</translation>
</message>
<message>
<source>Received with</source>
<translation>स्वीकार करना</translation>
</message>
<message>
<source>Sent to</source>
<translation>भेजा गया</translation>
</message>
<message>
<source>To yourself</source>
<translation>अपनेआप को</translation>
</message>
<message>
<source>Mined</source>
<translation>माइंड</translation>
</message>
<message>
<source>Other</source>
<translation>अन्य</translation>
</message>
<message>
<source>Enter address or label to search</source>
<translation>ढूँदने के लिए कृपा करके पता या लेबल टाइप करे !</translation>
</message>
<message>
<source>Min amount</source>
<translation>लघुत्तम राशि</translation>
</message>
<message>
<source>Copy address</source>
<translation>पता कॉपी करे</translation>
</message>
<message>
<source>Copy label</source>
<translation>लेबल कॉपी करे </translation>
</message>
<message>
<source>Copy amount</source>
<translation>कॉपी राशि</translation>
</message>
<message>
<source>Edit label</source>
<translation>एडिट लेबल</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
<message>
<source>Confirmed</source>
<translation>पक्का</translation>
</message>
<message>
<source>Date</source>
<translation>taareek</translation>
</message>
<message>
<source>Type</source>
<translation>टाइप</translation>
</message>
<message>
<source>Label</source>
<translation>लेबल</translation>
</message>
<message>
<source>Address</source>
<translation>पता</translation>
</message>
<message>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<source>Range:</source>
<translation>विस्तार:</translation>
</message>
<message>
<source>to</source>
<translation>तक</translation>
</message>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
</context>
<context>
<name>WalletFrame</name>
</context>
<context>
<name>WalletModel</name>
<message>
<source>Send Coins</source>
<translation>सिक्के भेजें|</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<source>Backup Wallet</source>
<translation>बैकप वॉलेट</translation>
</message>
<message>
<source>Wallet Data (*.dat)</source>
<translation>वॉलेट डेटा (*.dat)</translation>
</message>
<message>
<source>Backup Failed</source>
<translation>बैकप असफल</translation>
</message>
<message>
<source>Backup Successful</source>
<translation>बैकप सफल</translation>
</message>
</context>
<context>
<name>FairCoin-core</name>
<message>
<source>Options:</source>
<translation>विकल्प:</translation>
</message>
<message>
<source>Specify data directory</source>
<translation>डेटा डायरेक्टरी बताएं </translation>
</message>
<message>
<source>Run in the background as a daemon and accept commands</source>
<translation>बैकग्राउंड में डेमॉन बन कर रन करे तथा कमांड्स स्वीकार करें </translation>
</message>
<message>
<source>Verifying blocks...</source>
<translation>ब्लॉक्स जाँचे जा रहा है...</translation>
</message>
<message>
<source>Verifying wallet...</source>
<translation>वॉलेट जाँचा जा रहा है...</translation>
</message>
<message>
<source>Information</source>
<translation>जानकारी</translation>
</message>
<message>
<source>Warning</source>
<translation>चेतावनी</translation>
</message>
<message>
<source>Loading addresses...</source>
<translation>पता पुस्तक आ रही है...</translation>
</message>
<message>
<source>Loading block index...</source>
<translation>ब्लॉक इंडेक्स आ रहा है...</translation>
</message>
<message>
<source>Loading wallet...</source>
<translation>वॉलेट आ रहा है...</translation>
</message>
<message>
<source>Rescanning...</source>
<translation>रि-स्केनी-इंग...</translation>
</message>
<message>
<source>Done loading</source>
<translation>लोड हो गया|</translation>
</message>
<message>
<source>Error</source>
<translation>भूल</translation>
</message>
</context>
</TS>
|
Java
|
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Network
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// SecurityRulesOperations operations.
/// </summary>
internal partial class SecurityRulesOperations : IServiceOperations<NetworkManagementClient>, ISecurityRulesOperations
{
/// <summary>
/// Initializes a new instance of the SecurityRulesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal SecurityRulesOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Deletes the specified network security rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get the specified network security rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<SecurityRule>> GetWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkSecurityGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName");
}
if (securityRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "securityRuleName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2020-11-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.Add("securityRuleName", securityRuleName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName));
_url = _url.Replace("{securityRuleName}", System.Uri.EscapeDataString(securityRuleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<SecurityRule>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SecurityRule>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a security rule in the specified network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create or update network security rule
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<SecurityRule>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<SecurityRule> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all security rules in a network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<SecurityRule>>> ListWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkSecurityGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2020-11-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<SecurityRule>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SecurityRule>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified network security rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkSecurityGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName");
}
if (securityRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "securityRuleName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2020-11-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.Add("securityRuleName", securityRuleName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName));
_url = _url.Replace("{securityRuleName}", System.Uri.EscapeDataString(securityRuleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a security rule in the specified network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create or update network security rule
/// operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<SecurityRule>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkSecurityGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName");
}
if (securityRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "securityRuleName");
}
if (securityRuleParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "securityRuleParameters");
}
if (securityRuleParameters != null)
{
securityRuleParameters.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2020-11-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.Add("securityRuleName", securityRuleName);
tracingParameters.Add("securityRuleParameters", securityRuleParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName));
_url = _url.Replace("{securityRuleName}", System.Uri.EscapeDataString(securityRuleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(securityRuleParameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(securityRuleParameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<SecurityRule>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SecurityRule>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SecurityRule>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all security rules in a network security group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<SecurityRule>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<SecurityRule>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SecurityRule>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
|
Java
|
// © 2000 NEOSYS Software Ltd. All Rights Reserved.//**Start Encode**
function form_postinit() {
//enable/disable password changing button
neosyssetexpression('button_password', 'disabled', '!gusers_authorisation_update&&gkey!=gusername')
//force retrieval of own record
if (gro.dictitem('USER_ID').defaultvalue)
window.setTimeout('focuson("USER_NAME")', 100)
gwhatsnew = neosysgetcookie(glogincode, 'NEOSYS2', 'wn').toLowerCase()
if (gwhatsnew) {
if (window.location.href.toString().slice(0, 5) == 'file:') gwhatsnew = 'file:///' + gwhatsnew
else gwhatsnew = '..' + gwhatsnew.slice(gwhatsnew.indexOf('\\data\\'))
neosyssetcookie(glogincode, 'NEOSYS2', '', 'wn')
neosyssetcookie(glogincode, 'NEOSYS2', gwhatsnew, 'wn2')
window.setTimeout('windowopen(gwhatsnew)', 1000)
//windowopen(gwhatsnew)
}
$$('button_password').onclick = user_setpassword
return true
}
//just to avoid confirmation
function form_prewrite() {
return true
}
//in authorisation.js and users.htm
var gtasks_newpassword
function form_postwrite() {
//if change own password then login with the new one
//otherwise cannot continue/unlock document so the lock hangs
if (gtasks_newpassword) db.login(gusername, gtasks_newpassword)
gtasks_newpassword = false
//to avoid need full login to get new font/colors
neosyssetcookie(glogincode, 'NEOSYS2', gds.getx('SCREEN_BODY_COLOR'), 'fc')
neosyssetcookie(glogincode, 'NEOSYS2', gds.getx('SCREEN_FONT'), 'ff')
neosyssetcookie(glogincode, 'NEOSYS2', gds.getx('SCREEN_FONT_SIZE'), 'fs')
return true
}
function users_postdisplay() {
var signatureimageelement = document.getElementById('signature_image')
if (signatureimageelement) {
signatureimageelement.src = ''
signatureimageelement.height = 0
signatureimageelement.width = 0
signatureimageelement.src = '../images/'+gdataset+'SHARP/UPLOAD/USERS/' + gkey.neosysconvert(' ', '') + '_signature.jpg'
}
//show only first five lines
form_filter('refilter', 'LOGIN_DATE', '', 4)
var reminderdays = 6
var passwordexpires = gds.getx('PASSWORD_EXPIRY_DATE')
$passwordexpiryelement = $$('passwordexpiryelement')
$passwordexpiryelement.innerHTML = ''
if (passwordexpires) {
var expirydays = (neosysint(passwordexpires) - neosysdate())
if (expirydays <= reminderdays)
$passwordexpiryelement.innerHTML = '<font color=red> Password expires in ' + expirydays + ' days.</font>'
}
return true
}
function form_postread() {
window.setTimeout('users_postdisplay()', 10)
return true
}
function users_upload_signature() {
//return openwindow('EXECUTE\r\MEDIA\r\OPENMATERIAL',scheduleno+'.'+materialletter)
/*
params=new Object()
params.scheduleno=scheduleno
params.materialletter=materialletter
neosysshowmodaldialog('../NEOSYS/upload.htm',params)
*/
//images are not stored per dataset at the moment so that they can be
//nor are they stored per file or per key so that they can be easily saved into a shared folder instead of going by web upload
params = {}
params.database = gdataset
params.filename = 'USERS'
params.key = gkey.neosysconvert(' ', '') + '_signature'
params.versionno = ''//newarchiveno
params.updateallowed = true
params.deleteallowed = true
//params.allowimages = true
//we only allow one image type merely so that the signature file name
//is always know and doesnt need saving in the user file
//and no possibility of uploading two image files with different extensions
params.allowablefileextensions = 'jpg'
var targetfilename = neosysshowmodaldialog('../NEOSYS/upload.htm', params)
window.setTimeout('users_postdisplay()', 1)
if (!targetfilename)
return false
return true
}
function user_signature_onload(el) {
el.removeAttribute("width")
el.removeAttribute("height")
}
|
Java
|
// MIT License. Copyright (c) 2016 Maxim Kuzmin. Contacts: https://github.com/maxim-kuzmin
// Author: Maxim Kuzmin
using Autofac;
using Autofac.Core;
using Makc2017.Core.App;
using System.Collections.Generic;
using System.Linq;
namespace Makc2017.Modules.Dummy.Caching
{
/// <summary>
/// Модули. Модуль "Dummy". Кэширование. Плагин.
/// </summary>
public class ModuleDummyCachingPlugin : ModuleDummyPlugin
{
#region Properties
/// <summary>
/// Конфигурация кэширования.
/// </summary>
private ModuleDummyCachingConfig CachingConfig { get; set; }
#endregion Properties
#region Public methods
/// <summary>
/// Инициализировать.
/// </summary>
/// <param name="pluginEnvironment">Окружение плагинов.</param>
public sealed override void Init(CoreAppPluginEnvironment pluginEnvironment)
{
base.Init(pluginEnvironment);
CachingConfig.Init(ConfigurationProvider);
}
/// <summary>
/// Распознать зависимости.
/// </summary>
/// <param name="componentContext">Контекст компонентов.</param>
public sealed override void Resolve(IComponentContext componentContext)
{
base.Resolve(componentContext);
CachingConfig = componentContext.Resolve<ModuleDummyCachingConfig>();
}
#endregion Public methods
#region Protected methods
/// <summary>
/// Создать распознаватель зависимостей.
/// </summary>
/// <returns>Распознаватель зависимостей.</returns>
protected sealed override IModule CreateResolver()
{
return new ModuleDummyCachingResolver();
}
/// <summary>
/// Создать пути к файлам конфигурации.
/// </summary>
/// <returns>Пути к файлам конфигурации.</returns>
protected sealed override IEnumerable<string> CreateConfigFilePaths()
{
return base.CreateConfigFilePaths().Concat(new[] { @"Makc2017.Modules.Dummy.Caching\config.json" });
}
#endregion Protected methods
}
}
|
Java
|
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @module
* @description
* Entry point for all public APIs of this package.
*/
export { AnimationDriver, ɵAnimation, ɵAnimationStyleNormalizer, ɵNoopAnimationStyleNormalizer, ɵWebAnimationsStyleNormalizer, ɵAnimationDriver, ɵNoopAnimationDriver, ɵAnimationEngine, ɵCssKeyframesDriver, ɵCssKeyframesPlayer, ɵcontainsElement, ɵinvokeQuery, ɵmatchesElement, ɵvalidateStyleProperty, ɵWebAnimationsDriver, ɵsupportsWebAnimations, ɵWebAnimationsPlayer, ɵallowPreviousPlayerStylesMerge } from './src/browser';
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicHVibGljX2FwaS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uLy4uL3BhY2thZ2VzL2FuaW1hdGlvbnMvYnJvd3Nlci9wdWJsaWNfYXBpLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7QUFhQSx1WkFBYyxlQUFlLENBQUMiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIEBsaWNlbnNlXG4gKiBDb3B5cmlnaHQgR29vZ2xlIEluYy4gQWxsIFJpZ2h0cyBSZXNlcnZlZC5cbiAqXG4gKiBVc2Ugb2YgdGhpcyBzb3VyY2UgY29kZSBpcyBnb3Zlcm5lZCBieSBhbiBNSVQtc3R5bGUgbGljZW5zZSB0aGF0IGNhbiBiZVxuICogZm91bmQgaW4gdGhlIExJQ0VOU0UgZmlsZSBhdCBodHRwczovL2FuZ3VsYXIuaW8vbGljZW5zZVxuICovXG5cbi8qKlxuICogQG1vZHVsZVxuICogQGRlc2NyaXB0aW9uXG4gKiBFbnRyeSBwb2ludCBmb3IgYWxsIHB1YmxpYyBBUElzIG9mIHRoaXMgcGFja2FnZS5cbiAqL1xuZXhwb3J0ICogZnJvbSAnLi9zcmMvYnJvd3Nlcic7XG4iXX0=
|
Java
|
package queue;
/**
* Queue server metadata manager.
*
* @author Thanh Nguyen <btnguyen2k@gmail.com>
* @since 0.1.0
*/
public interface IQsMetadataManager {
}
|
Java
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Routing\Generator;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Exception\InvalidParameterException;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
use Psr\Log\LoggerInterface;
/**
* UrlGenerator can generate a URL or a path for any route in the RouteCollection
* based on the passed parameters.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Tobias Schultze <http://tobion.de>
*/
class UrlGenerator implements UrlGeneratorInterface, ConfigurableRequirementsInterface
{
protected $routes;
protected $context;
/**
* @var bool|null
*/
protected $strictRequirements = true;
protected $logger;
/**
* This array defines the characters (besides alphanumeric ones) that will not be percent-encoded in the path segment of the generated URL.
*
* PHP's rawurlencode() encodes all chars except "a-zA-Z0-9-._~" according to RFC 3986. But we want to allow some chars
* to be used in their literal form (reasons below). Other chars inside the path must of course be encoded, e.g.
* "?" and "#" (would be interpreted wrongly as query and fragment identifier),
* "'" and """ (are used as delimiters in HTML).
*/
protected $decodedChars = array(
// the slash can be used to designate a hierarchical structure and we want allow using it with this meaning
// some webservers don't allow the slash in encoded form in the path for security reasons anyway
// see http://stackoverflow.com/questions/4069002/http-400-if-2f-part-of-get-url-in-jboss
'%2F' => '/',
// the following chars are general delimiters in the URI specification but have only special meaning in the authority component
// so they can safely be used in the path in unencoded form
'%40' => '@',
'%3A' => ':',
// these chars are only sub-delimiters that have no predefined meaning and can therefore be used literally
// so URI producing applications can use these chars to delimit subcomponents in a path segment without being encoded for better readability
'%3B' => ';',
'%2C' => ',',
'%3D' => '=',
'%2B' => '+',
'%21' => '!',
'%2A' => '*',
'%7C' => '|',
);
public function __construct(RouteCollection $routes, RequestContext $context, LoggerInterface $logger = null)
{
$this->routes = $routes;
$this->context = $context;
$this->logger = $logger;
}
/**
* {@inheritdoc}
*/
public function setContext(RequestContext $context)
{
$this->context = $context;
}
/**
* {@inheritdoc}
*/
public function getContext()
{
return $this->context;
}
/**
* {@inheritdoc}
*/
public function setStrictRequirements($enabled)
{
$this->strictRequirements = null === $enabled ? null : (bool) $enabled;
}
/**
* {@inheritdoc}
*/
public function isStrictRequirements()
{
return $this->strictRequirements;
}
/**
* {@inheritdoc}
*/
public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
{
if (null === $route = $this->routes->get($name)) {
throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name));
}
// the Route has a cache of its own and is not recompiled as long as it does not get modified
$compiledRoute = $route->compile();
return $this->doGenerate($compiledRoute->getVariables(), $route->getDefaults(), $route->getRequirements(), $compiledRoute->getTokens(), $parameters, $name, $referenceType, $compiledRoute->getHostTokens(), $route->getSchemes());
}
/**
* @throws MissingMandatoryParametersException When some parameters are missing that are mandatory for the route
* @throws InvalidParameterException When a parameter value for a placeholder is not correct because
* it does not match the requirement
*/
protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, array $requiredSchemes = array())
{
if (is_bool($referenceType) || is_string($referenceType)) {
@trigger_error('The hardcoded value you are using for the $referenceType argument of the '.__CLASS__.'::generate method is deprecated since version 2.8 and will not be supported anymore in 3.0. Use the constants defined in the UrlGeneratorInterface instead.', E_USER_DEPRECATED);
if (true === $referenceType) {
$referenceType = self::ABSOLUTE_URL;
} elseif (false === $referenceType) {
$referenceType = self::ABSOLUTE_PATH;
} elseif ('relative' === $referenceType) {
$referenceType = self::RELATIVE_PATH;
} elseif ('network' === $referenceType) {
$referenceType = self::NETWORK_PATH;
}
}
$variables = array_flip($variables);
$mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters);
// all params must be given
if ($diff = array_diff_key($variables, $mergedParams)) {
throw new MissingMandatoryParametersException(sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route "%s".', implode('", "', array_keys($diff)), $name));
}
$url = '';
$optional = true;
foreach ($tokens as $token) {
if ('variable' === $token[0]) {
if (!$optional || !array_key_exists($token[3], $defaults) || null !== $mergedParams[$token[3]] && (string) $mergedParams[$token[3]] !== (string) $defaults[$token[3]]) {
// check requirement
if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#', $mergedParams[$token[3]])) {
$message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]);
if ($this->strictRequirements) {
throw new InvalidParameterException($message);
}
if ($this->logger) {
$this->logger->error($message);
}
return;
}
$url = $token[1].$mergedParams[$token[3]].$url;
$optional = false;
}
} else {
// static text
$url = $token[1].$url;
$optional = false;
}
}
if ('' === $url) {
$url = '/';
}
// the contexts base URL is already encoded (see Symfony\Component\HttpFoundation\Request)
$url = strtr(rawurlencode($url), $this->decodedChars);
// the path segments "." and ".." are interpreted as relative reference when resolving a URI; see http://tools.ietf.org/html/rfc3986#section-3.3
// so we need to encode them as they are not used for this purpose here
// otherwise we would generate a URI that, when followed by a user agent (e.g. browser), does not match this route
$url = strtr($url, array('/../' => '/%2E%2E/', '/./' => '/%2E/'));
if ('/..' === substr($url, -3)) {
$url = substr($url, 0, -2).'%2E%2E';
} elseif ('/.' === substr($url, -2)) {
$url = substr($url, 0, -1).'%2E';
}
$schemeAuthority = '';
if ($host = $this->context->getHost()) {
$scheme = $this->context->getScheme();
if ($requiredSchemes) {
if (!in_array($scheme, $requiredSchemes, true)) {
$referenceType = self::ABSOLUTE_URL;
$scheme = current($requiredSchemes);
}
} elseif (isset($requirements['_scheme']) && ($req = strtolower($requirements['_scheme'])) && $scheme !== $req) {
// We do this for BC; to be removed if _scheme is not supported anymore
$referenceType = self::ABSOLUTE_URL;
$scheme = $req;
}
if ($hostTokens) {
$routeHost = '';
foreach ($hostTokens as $token) {
if ('variable' === $token[0]) {
if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#i', $mergedParams[$token[3]])) {
$message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]);
if ($this->strictRequirements) {
throw new InvalidParameterException($message);
}
if ($this->logger) {
$this->logger->error($message);
}
return;
}
$routeHost = $token[1].$mergedParams[$token[3]].$routeHost;
} else {
$routeHost = $token[1].$routeHost;
}
}
if ($routeHost !== $host) {
$host = $routeHost;
if (self::ABSOLUTE_URL !== $referenceType) {
$referenceType = self::NETWORK_PATH;
}
}
}
if (self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType) {
$port = '';
if ('http' === $scheme && 80 != $this->context->getHttpPort()) {
$port = ':'.$this->context->getHttpPort();
} elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) {
$port = ':'.$this->context->getHttpsPort();
}
$schemeAuthority = self::NETWORK_PATH === $referenceType ? '//' : "$scheme://";
$schemeAuthority .= $host.$port;
}
}
if (self::RELATIVE_PATH === $referenceType) {
$url = self::getRelativePath($this->context->getPathInfo(), $url);
} else {
$url = $schemeAuthority.$this->context->getBaseUrl().$url;
}
// add a query string if needed
$extra = array_udiff_assoc(array_diff_key($parameters, $variables), $defaults, function ($a, $b) {
return $a == $b ? 0 : 1;
});
if ($extra && $query = http_build_query($extra, '', '&')) {
// "/" and "?" can be left decoded for better user experience, see
// http://tools.ietf.org/html/rfc3986#section-3.4
$url .= '?'.strtr($query, array('%2F' => '/'));
}
return $url;
}
/**
* Returns the target path as relative reference from the base path.
*
* Only the URIs path component (no schema, host etc.) is relevant and must be given, starting with a slash.
* Both paths must be absolute and not contain relative parts.
* Relative URLs from one resource to another are useful when generating self-contained downloadable document archives.
* Furthermore, they can be used to reduce the link size in documents.
*
* Example target paths, given a base path of "/a/b/c/d":
* - "/a/b/c/d" -> ""
* - "/a/b/c/" -> "./"
* - "/a/b/" -> "../"
* - "/a/b/c/other" -> "other"
* - "/a/x/y" -> "../../x/y"
*
* @param string $basePath The base path
* @param string $targetPath The target path
*
* @return string The relative target path
*/
public static function getRelativePath($basePath, $targetPath)
{
if ($basePath === $targetPath) {
return '';
}
$sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath);
$targetDirs = explode('/', isset($targetPath[0]) && '/' === $targetPath[0] ? substr($targetPath, 1) : $targetPath);
array_pop($sourceDirs);
$targetFile = array_pop($targetDirs);
foreach ($sourceDirs as $i => $dir) {
if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) {
unset($sourceDirs[$i], $targetDirs[$i]);
} else {
break;
}
}
$targetDirs[] = $targetFile;
$path = str_repeat('../', count($sourceDirs)).implode('/', $targetDirs);
// A reference to the same base directory or an empty subdirectory must be prefixed with "./".
// This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
// as the first segment of a relative-path reference, as it would be mistaken for a scheme name
// (see http://tools.ietf.org/html/rfc3986#section-4.2).
return '' === $path || '/' === $path[0]
|| false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos)
? "./$path" : $path;
}
}
|
Java
|
'use strict';
const path = require('path'),
mongoose = require('mongoose'),
Promise = require('bluebird'),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
_ = require('lodash');
mongoose.Promise = Promise;
const User = mongoose.model('User');
const Project = mongoose.model('Project');
/**
* Patch Update User Fields
*/
exports.patchUser = (req, res) => {
_.extend(req.model, req.body)
.save()
.then(updatedUser => {
res.jsonp(updatedUser);
})
.catch(err => {
console.error('ERROR on patch update for user `err`:\n', err);
res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
});
};
/**
* Return list of projects by contributor - query param `publishedOnly`, if true, returns only published projects
*
* @param req
* @param req.query.publishedOnly
* @param res
*/
exports.getContributorProjects = (req, res) => {
const projectIdsArray = [];
const projectsArray = [];
req.model.associatedProjects.map(assocProjId => { projectIdsArray.push(assocProjId); });
Project.find({
'_id': { $in: projectIdsArray }
})
.then(projects => {
if (req.query.publishedOnly===true) {
projects.map(project => {
if(project.status[0]==='published') {
projectsArray.push(project);
}
});
projects = projectsArray;
}
res.jsonp(projects);
})
.catch(err => {
console.error('error:\n', err);
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
});
};
|
Java
|
using System.Linq;
using System.Threading.Tasks;
using JSONAPI.Documents;
using Newtonsoft.Json;
namespace JSONAPI.Json
{
/// <summary>
/// Default implementation of ISingleResourceDocumentFormatter
/// </summary>
public class SingleResourceDocumentFormatter : ISingleResourceDocumentFormatter
{
private readonly IResourceObjectFormatter _resourceObjectFormatter;
private readonly IMetadataFormatter _metadataFormatter;
private const string PrimaryDataKeyName = "data";
private const string RelatedDataKeyName = "included";
private const string MetaKeyName = "meta";
/// <summary>
/// Creates a SingleResourceDocumentFormatter
/// </summary>
/// <param name="resourceObjectFormatter"></param>
/// <param name="metadataFormatter"></param>
public SingleResourceDocumentFormatter(IResourceObjectFormatter resourceObjectFormatter, IMetadataFormatter metadataFormatter)
{
_resourceObjectFormatter = resourceObjectFormatter;
_metadataFormatter = metadataFormatter;
}
public Task Serialize(ISingleResourceDocument document, JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName(PrimaryDataKeyName);
_resourceObjectFormatter.Serialize(document.PrimaryData, writer);
if (document.RelatedData != null && document.RelatedData.Any())
{
writer.WritePropertyName(RelatedDataKeyName);
writer.WriteStartArray();
foreach (var resourceObject in document.RelatedData)
{
_resourceObjectFormatter.Serialize(resourceObject, writer);
}
writer.WriteEndArray();
}
if (document.Metadata != null)
{
writer.WritePropertyName(MetaKeyName);
_metadataFormatter.Serialize(document.Metadata, writer);
}
writer.WriteEndObject();
return Task.FromResult(0);
}
public async Task<ISingleResourceDocument> Deserialize(JsonReader reader, string currentPath)
{
if (reader.TokenType != JsonToken.StartObject)
throw new DeserializationException("Invalid document root", "Document root is not an object!", currentPath);
IResourceObject primaryData = null;
IMetadata metadata = null;
while (reader.Read())
{
if (reader.TokenType != JsonToken.PropertyName) break;
// Has to be a property name
var propertyName = (string)reader.Value;
reader.Read();
switch (propertyName)
{
case RelatedDataKeyName:
// TODO: If we want to capture related resources, this would be the place to do it
reader.Skip();
break;
case PrimaryDataKeyName:
primaryData = await DeserializePrimaryData(reader, currentPath + "/" + PrimaryDataKeyName);
break;
case MetaKeyName:
metadata = await _metadataFormatter.Deserialize(reader, currentPath + "/" + MetaKeyName);
break;
default:
reader.Skip();
break;
}
}
return new SingleResourceDocument(primaryData, new IResourceObject[] { }, metadata);
}
private async Task<IResourceObject> DeserializePrimaryData(JsonReader reader, string currentPath)
{
if (reader.TokenType == JsonToken.Null) return null;
var primaryData = await _resourceObjectFormatter.Deserialize(reader, currentPath);
return primaryData;
}
}
}
|
Java
|
/*jshint unused:false*/
var chai = require('chai'),
expect = chai.expect;
var request = require('supertest');
module.exports = function() {
'use strict';
this.Then(/^The JSON is returned by issuing a "GET" at the specified uri:$/, function(json, callback) {
request(this.serverLocation)
.get('/hello')
.expect('Content-Type', /json/)
.expect(200)
.end(function(error, res) {
if(error) {
expect(false).to.equal(true, error);
}
else {
expect(res.body).to.deep.equal(JSON.parse(json));
}
callback();
});
});
};
|
Java
|
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
namespace DotSpatial.Symbology.Forms
{
/// <summary>
/// FontFamilyNameEditor.
/// </summary>
public class FontFamilyNameEditor : UITypeEditor
{
#region Fields
private IWindowsFormsEditorService _dialogProvider;
#endregion
#region Properties
/// <summary>
/// Gets a value indicating whether the drop down is resizeable.
/// </summary>
public override bool IsDropDownResizable => true;
#endregion
#region Methods
/// <summary>
/// Edits a value based on some user input which is collected from a character control.
/// </summary>
/// <param name="context">The type descriptor context.</param>
/// <param name="provider">The service provider.</param>
/// <param name="value">Not used.</param>
/// <returns>The selected font family name.</returns>
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
_dialogProvider = provider?.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
ListBox cmb = new ListBox();
FontFamily[] fams = FontFamily.Families;
cmb.SuspendLayout();
foreach (FontFamily fam in fams)
{
cmb.Items.Add(fam.Name);
}
cmb.SelectedValueChanged += CmbSelectedValueChanged;
cmb.ResumeLayout();
_dialogProvider?.DropDownControl(cmb);
string test = (string)cmb.SelectedItem;
return test;
}
/// <summary>
/// Gets the UITypeEditorEditStyle, which in this case is drop down.
/// </summary>
/// <param name="context">The type descriptor context.</param>
/// <returns>The UITypeEditorEditStyle.</returns>
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.DropDown;
}
private void CmbSelectedValueChanged(object sender, EventArgs e)
{
_dialogProvider.CloseDropDown();
}
#endregion
}
}
|
Java
|
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>deprecation.rb</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="../../../../../../../../../../../../../../../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../../../../../../../../../../../../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../../../../../../../../../../../../../css/github.css" type="text/css" media="screen" />
<script src="../../../../../../../../../../../../../../../../js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../../../../../../../../../../../../../../js/jquery-effect.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../../../../../../../../../../../../../../js/main.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../../../../../../../../../../../../../../js/highlight.pack.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div class="banner">
<span>Ruby on Rails 4.1.6</span><br />
<h1>
deprecation.rb
</h1>
<ul class="files">
<li>
../../.rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/activesupport-4.1.6/lib/active_support/core_ext/module/deprecation.rb
</li>
<li>Last modified: 2014-10-25 21:53:16 +1100</li>
</ul>
</div>
<div id="bodyContent">
<div id="content">
<!-- Namespace -->
<div class="sectiontitle">Namespace</div>
<ul>
<li>
<span class="type">MODULE</span>
<a href="../../../../../../../../../../../../../../../../classes/ActiveSupport.html">ActiveSupport</a>
</li>
<li>
<span class="type">CLASS</span>
<a href="../../../../../../../../../../../../../../../../classes/Module.html">Module</a>
</li>
</ul>
<!-- Methods -->
</div>
</div>
</body>
</html>
|
Java
|
/* global sinon, setup, teardown */
/**
* __init.test.js is run before every test case.
*/
window.debug = true;
var AScene = require('aframe').AScene;
beforeEach(function () {
this.sinon = sinon.sandbox.create();
// Stub to not create a WebGL context since Travis CI runs headless.
this.sinon.stub(AScene.prototype, 'attachedCallback');
});
afterEach(function () {
// Clean up any attached elements.
['canvas', 'a-assets', 'a-scene'].forEach(function (tagName) {
var els = document.querySelectorAll(tagName);
for (var i = 0; i < els.length; i++) {
els[i].parentNode.removeChild(els[i]);
}
});
AScene.scene = null;
this.sinon.restore();
});
|
Java
|
///
/// Copyright (c) 2016 Dropbox, Inc. All rights reserved.
///
/// Auto-generated by Stone, do not modify.
///
#import <Foundation/Foundation.h>
#import "DBSerializableProtocol.h"
@class DBPAPERImportFormat;
@class DBPAPERPaperDocCreateArgs;
NS_ASSUME_NONNULL_BEGIN
#pragma mark - API Object
///
/// The `PaperDocCreateArgs` struct.
///
/// This class implements the `DBSerializable` protocol (serialize and
/// deserialize instance methods), which is required for all Obj-C SDK API route
/// objects.
///
@interface DBPAPERPaperDocCreateArgs : NSObject <DBSerializable, NSCopying>
#pragma mark - Instance fields
/// The Paper folder ID where the Paper document should be created. The API user
/// has to have write access to this folder or error is thrown.
@property (nonatomic, readonly, copy, nullable) NSString *parentFolderId;
/// The format of provided data.
@property (nonatomic, readonly) DBPAPERImportFormat *importFormat;
#pragma mark - Constructors
///
/// Full constructor for the struct (exposes all instance variables).
///
/// @param importFormat The format of provided data.
/// @param parentFolderId The Paper folder ID where the Paper document should be
/// created. The API user has to have write access to this folder or error is
/// thrown.
///
/// @return An initialized instance.
///
- (instancetype)initWithImportFormat:(DBPAPERImportFormat *)importFormat
parentFolderId:(nullable NSString *)parentFolderId;
///
/// Convenience constructor (exposes only non-nullable instance variables with
/// no default value).
///
/// @param importFormat The format of provided data.
///
/// @return An initialized instance.
///
- (instancetype)initWithImportFormat:(DBPAPERImportFormat *)importFormat;
- (instancetype)init NS_UNAVAILABLE;
@end
#pragma mark - Serializer Object
///
/// The serialization class for the `PaperDocCreateArgs` struct.
///
@interface DBPAPERPaperDocCreateArgsSerializer : NSObject
///
/// Serializes `DBPAPERPaperDocCreateArgs` instances.
///
/// @param instance An instance of the `DBPAPERPaperDocCreateArgs` API object.
///
/// @return A json-compatible dictionary representation of the
/// `DBPAPERPaperDocCreateArgs` API object.
///
+ (nullable NSDictionary *)serialize:(DBPAPERPaperDocCreateArgs *)instance;
///
/// Deserializes `DBPAPERPaperDocCreateArgs` instances.
///
/// @param dict A json-compatible dictionary representation of the
/// `DBPAPERPaperDocCreateArgs` API object.
///
/// @return An instantiation of the `DBPAPERPaperDocCreateArgs` object.
///
+ (DBPAPERPaperDocCreateArgs *)deserialize:(NSDictionary *)dict;
@end
NS_ASSUME_NONNULL_END
|
Java
|
#container{
width: 750px;
margin: 0 auto;
text-align: left;
}
#header {
position: relative;
top:2px;
}
#menu{
float: left;
width: 150px;
}
#anchorMenu{
position: fixed;
top: auto;
width: 8em;
left: auto;
margin: -2.5em 0 0 0;
z-index: 5;
overflow: hidden;
padding-top: 20px;
}
#mainArea{
padding-top: 5px;
float: left;
width: 570px
}
#footer{
clear: both;
text-align: center;
font-size: 80%;
padding-left: 33.3%
}
body{
text-align: center;
font-family: arial;
background: #FFF;
padding: 0;
}
a:link, a:visited {
display: block;
color:rgb(41,136,126);
text-decoration:none;
background-color: #EBEBE6;
width: 130px;
text-align: left;
padding: 3px;
}
a:hover, a:active {
color: white;
background-color:#7A991A;
}
a:hover.anchor, a:active.anchor {
color: white;
background-color:brown;
}
a.w3c{
width: 83px;
}
h2, h4{
margin: 8px;
}
ul li{
font-size: 15px;
}
table{
border:0px solid black;
text-align: left;
}
td.padded{
border:0px solid black;
padding: 0px 0px 38px 0px;
width:25%
}
h3.headings{
text-align: left;
}
h4.subHead{
text-align:left;
}
p{
text-align:left;
font-size: 15px;
}
p.profile{
text-align:left;
font-weight: bold;
font-size: 15px;
}
.center{
text-align: center;
}
.padded{
padding-left: 110px;
}
|
Java
|
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Frames — Leap Motion C++ SDK v3.1 documentation</title>
<link rel="stylesheet" href="../../cpp/_static/bootstrap-3.0.0/css/documentation-bundle.1471552333.css" type="text/css" />
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../',
VERSION: '3.1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: false
};
</script>
<script type="text/javascript" src="../../cpp/_static/bootstrap-3.0.0/js/documentation-bundle.1471552333.js"></script>
<link rel="top" title="Leap Motion C++ SDK v3.1 documentation" href="../index.html" />
<link rel="up" title="Using the Tracking API" href="Leap_Guides2.html" />
<link rel="next" title="Hands" href="Leap_Hand.html" />
<link rel="prev" title="Tracking Model" href="Leap_Tracking.html" />
<script type="text/javascript" src="/assets/standalone-header.js?r9"></script>
<link rel="stylesheet" href="/assets/standalone-header.css?r9" type="text/css" />
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-31536531-1']);
_gaq.push(['_setDomainName', 'leapmotion.com']);
_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>
<script>
function getQueryValue(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
var relPath = "../../";
var requestedAPI = getQueryValue("proglang");
if(requestedAPI == "current") requestedAPI = localStorage["currentAPI"];
var pageAPI = 'cpp';
var hasAPI = {};
hasAPI.cpp = true;
hasAPI.objc = true;
hasAPI.java = true;
hasAPI.javascript = true;
hasAPI.python = true;
if(requestedAPI && (requestedAPI != pageAPI))
{
if(pageAPI != 'none'){
var redirectedLocation = relPath + 'cpp/devguide/Leap_Frames.html';
if( requestedAPI == 'cpp' && hasAPI.cpp){
redirectedLocation = relPath + "cpp/devguide/Leap_Frames.html";
}
else if( requestedAPI == 'csharp' && hasAPI.csharp){
redirectedLocation = relPath + "csharp/devguide/Leap_Frames.html";
}
else if( requestedAPI == 'unity' && hasAPI.unity){
redirectedLocation = relPath + "unity/devguide/Leap_Frames.html";
}
else if( requestedAPI == 'objc' && hasAPI.objc){
redirectedLocation = relPath + "objc/devguide/Leap_Frames.html";
}
else if( requestedAPI == 'java' && hasAPI.java) {
redirectedLocation = relPath + "java/devguide/Leap_Frames.html";
}
else if( requestedAPI == 'javascript' && hasAPI.javascript){
redirectedLocation = relPath + "javascript/devguide/Leap_Frames.html";
}
else if( requestedAPI == 'python' && hasAPI.python){
redirectedLocation = relPath + "python/devguide/Leap_Frames.html";
}
else if( requestedAPI == 'unreal' && hasAPI.unreal) {
redirectedLocation = relPath + "unreal/devguide/Leap_Frames.html";
} else {
redirectedLocation ="Leap_Guides2.html";
}
//Guard against redirecting to the same page (infinitely)
if(relPath + 'cpp/devguide/Leap_Frames.html' != redirectedLocation) window.location.replace(redirectedLocation);
}
}
</script>
<script>
window.addEventListener('keyup', handleKeyInput);
function handleKeyInput(e)
{
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
if( character == "J" & e.altKey){
window.location.assign("Leap_Tracking.html"); }
else if( character == "K" & e.altKey){
window.location.assign("Leap_Hand.html");
}
}
</script>
</head>
<body role="document">
<div class="developer-portal-styles">
<header class="navbar navbar-static-top developer-navbar header beta-header">
<nav class="container pr">
<a class="logo-link pull-left" href="/">
<img alt="Leap Motion Developers" class="media-object pull-left white-background" src="../_static/logo.png" />
</a>
<span class="inline-block hidden-phone developer-logo-text">
<div class="text">
<a href="/">
<span class="more-than-1199">Developer Portal</span>
</a>
</div>
</span>
<button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<!-- Everything within here will be hidden at 940px or less, accessible via a button. -->
<div class="nav-collapse">
<ul class="nav header-navigation developer-links">
<li class="external-link"><a href="https://developer.leapmotion.com/features">What's new</a> </li>
<li class="external-link"><a href="https://developer.leapmotion.com/downloads/skeletal-beta" class="">Getting Started</a></li>
<li><a class="active" href="#" class="">Documentation</a></li>
<li class="external-link"> <a href="https://developer.leapmotion.com/gallery" class="">Examples</a> </li>
<li class="external-link"> <a href="https://www.leapmotion.com/blog/category/labs/" class="" target="_blank">Blog <i class='fa fa-external-link'></i></a> </li>
<li class="external-link"> <a href="https://community.leapmotion.com/category/beta" class="" target="_blank">Community <i class='fa fa-external-link'></i></a> </li>
</ul>
</div>
</nav>
</header>
</div>
<section class="main-wrap">
<div data-swiftype-index="true">
<div class="second_navigation">
<div class="container">
<div class="row">
<div class="col-md-8">
<ul>
<li>
<a href="../../javascript/devguide/Leap_Frames.html?proglang=javascript" onclick="localStorage['currentAPI'] = 'javascript'">JavaScript</a>
</li>
<li>
<a href="Leap_Guides2.html?proglang=current" onclick="localStorage['currentAPI'] = 'unity'">Unity</a>
</li>
<li>
<a href="Leap_Guides2.html?proglang=current" onclick="localStorage['currentAPI'] = 'csharp'">C#</a>
</li>
<li>
C++
</li>
<li>
<a href="../../java/devguide/Leap_Frames.html?proglang=java" onclick="localStorage['currentAPI'] = 'java'">Java</a>
</li>
<li>
<a href="../../python/devguide/Leap_Frames.html?proglang=python" onclick="localStorage['currentAPI'] = 'python'">Python</a>
</li>
<li>
<a href="../../objc/devguide/Leap_Frames.html?proglang=objc" onclick="localStorage['currentAPI'] = 'objc'">Objective-C</a>
</li>
<li>
<a href="Leap_Guides2.html?proglang=current" onclick="localStorage['currentAPI'] = 'unreal'">Unreal</a>
</li>
</ul>
</div>
<div class="col-md-4 search">
<script>
function storeThisPage(){
sessionStorage["pageBeforeSearch"] = window.location;
return true;
}
function doneWithSearch(){
var storedPage = sessionStorage["pageBeforeSearch"];
if(storedPage){
window.location = storedPage;
} else {
window.location = "index.html"; //fallback
}
return false;
}
</script>
<div style="margin-top:-4px">
<ul style="display:inline; white-space:nowrap"><li>
<form class="navbar-form" action="../search.html" method="get" onsubmit="storeThisPage()">
<div class="form-group">
<input type="search" results="5" name="q" class="form-control" placeholder="Search" />
</div>
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<script>
//Remove dev portal header and footer when viewing from file system
if(window.location.protocol == 'file:'){
var navNode = document.querySelector(".developer-links");
navNode.parentNode.removeChild(navNode);
}
</script>
<div id="wrap" data-spy="scroll" data-target="#sidebar">
<div class="container">
<div class="row">
<div class="col-md-9 pull-right">
<!--
<span id="breadcrumbs">
<a href="../index.html">Home</a>»
<a href="Leap_Guides2.html" accesskey="U">Using the Tracking API</a>»
Frames
</span> -->
<div class="section" id="frames">
<h1>Frames<a class="headerlink" href="#frames" title="Permalink to this headline">¶</a></h1>
<p>The Leap Motion API presents motion tracking data to your application as a series of snapshots called <em>frames</em>. Each frame of tracking data contains the measured positions and other information about each entity detected in that snapshot. This article discusses the details of getting <a class="reference external" href="../api/Leap.Frame.html"><tt class="docutils literal"><span class="pre">Frame</span></tt></a> objects from the Leap Motion controller.</p>
<div class="section" id="overview">
<h2>Overview<a class="headerlink" href="#overview" title="Permalink to this headline">¶</a></h2>
<p>Each <a class="reference external" href="../api/Leap.Frame.html"><tt class="docutils literal"><span class="pre">Frame</span></tt></a> object contains an instantaneous snapshot of the scene recorded by the Leap Motion controller. Hands, fingers, and tools are the basic physical entities tracked by the Leap Motion system.</p>
<p>Get a <tt class="docutils literal"><span class="pre">Frame</span></tt> object containing tracking data from a connected <a class="reference external" href="../api/Leap.Controller.html"><tt class="docutils literal"><span class="pre">Controller</span></tt></a> object. You can get a frame whenever your application is ready to process it using the <cite>frame()</cite> method of the <tt class="docutils literal"><span class="pre">Controller</span></tt> class:</p>
<div class="highlight-cpp"><div class="highlight"><pre><span class="k">if</span><span class="p">(</span> <span class="n">controller</span><span class="p">.</span><span class="n">isConnected</span><span class="p">())</span> <span class="c1">//controller is a Controller object</span>
<span class="p">{</span>
<span class="n">Leap</span><span class="o">::</span><span class="n">Frame</span> <span class="n">frame</span> <span class="o">=</span> <span class="n">controller</span><span class="p">.</span><span class="n">frame</span><span class="p">();</span> <span class="c1">//The latest frame</span>
<span class="n">Leap</span><span class="o">::</span><span class="n">Frame</span> <span class="n">previous</span> <span class="o">=</span> <span class="n">controller</span><span class="p">.</span><span class="n">frame</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span> <span class="c1">//The previous frame</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">frame()</span></tt> function takes a <tt class="docutils literal"><span class="pre">history</span></tt> parameter that indicates how many frames back to retrieve. The last 60 frames are maintained in the history buffer (but don’t rely on this exact value, it could change in the future).</p>
<p><strong>Note:</strong> Ordinarily consecutive frames have consecutively increasing ID values. However, in some cases, frame IDs are skipped. On resource-constrained computers, the Leap Motion software can drop frames. In addition, when the software enters robust mode to compensate for bright IR lighting conditions, two sensor frames are analyzed for each <tt class="docutils literal"><span class="pre">Frame</span></tt> object produced and the IDs for consecutive Frame objects increase by two. Finally, if you are using a <a class="reference external" href="../api/Leap.Listener.html"><tt class="docutils literal"><span class="pre">Listener</span></tt></a> callback to get frames, the callback function is not invoked a second time until the first invocation returns. Thus, your application will miss frames if the callback function takes too long to process a frame. In this case, the missed frame is inserted in a history buffer.</p>
</div>
<div class="section" id="getting-data-from-a-frame">
<h2>Getting Data from a Frame<a class="headerlink" href="#getting-data-from-a-frame" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference external" href="../api/Leap.Frame.html"><tt class="docutils literal"><span class="pre">Frame</span></tt></a> class defines several functions that provide access to the data in the frame. For example, the following code illustrates how to get the basic objects tracked by the Leap Motion system:</p>
<div class="highlight-cpp"><div class="highlight"><pre><span class="n">Leap</span><span class="o">::</span><span class="n">Controller</span> <span class="n">controller</span><span class="p">;</span>
<span class="c1">// wait until Controller.isConnected() evaluates to true</span>
<span class="c1">//...</span>
<span class="n">Leap</span><span class="o">::</span><span class="n">Frame</span> <span class="n">frame</span> <span class="o">=</span> <span class="n">controller</span><span class="p">.</span><span class="n">frame</span><span class="p">();</span>
<span class="n">Leap</span><span class="o">::</span><span class="n">HandList</span> <span class="n">hands</span> <span class="o">=</span> <span class="n">frame</span><span class="p">.</span><span class="n">hands</span><span class="p">();</span>
<span class="n">Leap</span><span class="o">::</span><span class="n">PointableList</span> <span class="n">pointables</span> <span class="o">=</span> <span class="n">frame</span><span class="p">.</span><span class="n">pointables</span><span class="p">();</span>
<span class="n">Leap</span><span class="o">::</span><span class="n">FingerList</span> <span class="n">fingers</span> <span class="o">=</span> <span class="n">frame</span><span class="p">.</span><span class="n">fingers</span><span class="p">();</span>
<span class="n">Leap</span><span class="o">::</span><span class="n">ToolList</span> <span class="n">tools</span> <span class="o">=</span> <span class="n">frame</span><span class="p">.</span><span class="n">tools</span><span class="p">();</span>
</pre></div>
</div>
<p>The objects returned by the <tt class="docutils literal"><span class="pre">Frame</span></tt> object are all read-only. You can safely store them and use them in the future. They are thread-safe. Internally, the objects use the <a class="reference external" href="http://www.boost.org/doc/libs/1_51_0/libs/smart_ptr/shared_ptr.htm#ThreadSafety">C++ Boost library shared pointer class</a>.</p>
</div>
<div class="section" id="getting-frames-by-polling">
<h2>Getting Frames by Polling<a class="headerlink" href="#getting-frames-by-polling" title="Permalink to this headline">¶</a></h2>
<p>Polling the <a class="reference external" href="../api/Leap.Controller.html"><tt class="docutils literal"><span class="pre">Controller</span></tt></a> object for frames is the simplest and often best strategy when your application has a natural frame rate. You just call the <tt class="docutils literal"><span class="pre">Controller</span></tt> <tt class="docutils literal"><span class="pre">frame()</span></tt> function when your application is ready to process a frame of data.</p>
<p>When you use polling, there is a chance that you will get the same frame twice in a row (if the application frame rate exceeds the Leap frame rate) or skip a frame (if the Leap frame rate exceeds the application frame rate). In many cases, missed or duplicated frames are not important. For example, if you are moving an object on the screen in response to hand movement, the movement should still be smooth (assuming the overall frame rate of your application is high enough). In those cases where it does matter, you can use the <tt class="docutils literal"><span class="pre">history</span></tt> parameter of the <tt class="docutils literal"><span class="pre">frame()</span></tt> function.</p>
<p>To detect whether you have already processed a frame, save the ID value assigned to the last frame processed and compare it to the current frame:</p>
<div class="highlight-cpp"><div class="highlight"><pre><span class="kt">int64_t</span> <span class="n">lastFrameID</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="kt">void</span> <span class="nf">processFrame</span><span class="p">(</span> <span class="n">Leap</span><span class="o">::</span><span class="n">Frame</span> <span class="n">frame</span> <span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span><span class="p">(</span> <span class="n">frame</span><span class="p">.</span><span class="n">id</span><span class="p">()</span> <span class="o">==</span> <span class="n">lastFrameID</span> <span class="p">)</span> <span class="k">return</span><span class="p">;</span>
<span class="c1">//...</span>
<span class="n">lastFrameID</span> <span class="o">=</span> <span class="n">frame</span><span class="p">.</span><span class="n">id</span><span class="p">();</span>
<span class="p">}</span>
</pre></div>
</div>
<p>If your application has skipped frames, use the <cite>history</cite> parameter of the <cite>frame()</cite> function to access the skipped frames (as long as the <tt class="docutils literal"><span class="pre">Frame</span></tt> object is still in the history buffer):</p>
<div class="highlight-cpp"><div class="highlight"><pre><span class="kt">int64_t</span> <span class="n">lastProcessedFrameID</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="kt">void</span> <span class="nf">nextFrame</span><span class="p">(</span> <span class="n">Leap</span><span class="o">::</span><span class="n">Controller</span> <span class="n">controller</span> <span class="p">)</span>
<span class="p">{</span>
<span class="kt">int64_t</span> <span class="n">currentID</span> <span class="o">=</span> <span class="n">controller</span><span class="p">.</span><span class="n">frame</span><span class="p">().</span><span class="n">id</span><span class="p">();</span>
<span class="k">for</span><span class="p">(</span> <span class="kt">int</span> <span class="n">history</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">history</span> <span class="o"><</span> <span class="n">currentID</span> <span class="o">-</span> <span class="n">lastProcessedFrameID</span><span class="p">;</span> <span class="n">history</span><span class="o">++</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">processNextFrame</span><span class="p">(</span> <span class="n">controller</span><span class="p">.</span><span class="n">frame</span><span class="p">(</span><span class="n">history</span><span class="p">)</span> <span class="p">);</span>
<span class="p">}</span>
<span class="n">lastProcessedFrameID</span> <span class="o">=</span> <span class="n">currentID</span><span class="p">;</span>
<span class="p">}</span>
<span class="kt">void</span> <span class="nf">processNextFrame</span><span class="p">(</span> <span class="n">Leap</span><span class="o">::</span><span class="n">Frame</span> <span class="n">frame</span> <span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span><span class="p">(</span> <span class="n">frame</span><span class="p">.</span><span class="n">isValid</span><span class="p">()</span> <span class="p">)</span>
<span class="p">{</span>
<span class="c1">//...</span>
<span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="getting-frames-with-callbacks">
<h2>Getting Frames with Callbacks<a class="headerlink" href="#getting-frames-with-callbacks" title="Permalink to this headline">¶</a></h2>
<p>Alternatively, you can use a <a class="reference external" href="../api/Leap.Listener.html"><tt class="docutils literal"><span class="pre">Listener</span></tt></a> object to get frames at the Leap Motion controller’s frame rate. The <a class="reference external" href="../api/Leap.Controller.html"><tt class="docutils literal"><span class="pre">Controller</span></tt></a> object calls the listener’s <tt class="docutils literal"><span class="pre">onFrame()</span></tt> function when a new frame is available. In the <tt class="docutils literal"><span class="pre">onFrame</span></tt> handler, you can call the <tt class="docutils literal"><span class="pre">Controller</span></tt> <tt class="docutils literal"><span class="pre">frame()</span></tt> function to get the <tt class="docutils literal"><span class="pre">Frame</span></tt> object itself.</p>
<p>Using listener callbacks is more complex because the callbacks are multi-threaded; each callback is invoked on an independent thread. You must ensure that any application data accessed by multiple threads is handled in a thread-safe manner. Even though the tracking data objects you get from the API are thread safe, other parts of your application may not be. A common problem is updating objects owned by a GUI layer that can only be modified by a specific thread. In such cases you must arrange to update the non-thread safe portions of your application from the appropriate thread rather than from the callback thread.</p>
<p>The following example defines a minimal Listener subclass that handles new frames of data:</p>
<div class="highlight-cpp"><div class="highlight"><pre><span class="k">class</span> <span class="nc">FrameListener</span> <span class="o">:</span> <span class="n">Leap</span><span class="o">::</span><span class="n">Listener</span>
<span class="p">{</span>
<span class="kt">void</span> <span class="n">onFrame</span><span class="p">(</span><span class="n">Leap</span><span class="o">::</span><span class="n">Controller</span> <span class="o">&</span><span class="n">controller</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">Leap</span><span class="o">::</span><span class="n">Frame</span> <span class="n">frame</span> <span class="o">=</span> <span class="n">controller</span><span class="p">.</span><span class="n">frame</span><span class="p">();</span> <span class="c1">//The latest frame</span>
<span class="n">Leap</span><span class="o">::</span><span class="n">Frame</span> <span class="n">previous</span> <span class="o">=</span> <span class="n">controller</span><span class="p">.</span><span class="n">frame</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span> <span class="c1">//The previous frame</span>
<span class="c1">//...</span>
<span class="p">}</span>
<span class="p">};</span>
</pre></div>
</div>
<p>As you can see, getting the tracking data through a <tt class="docutils literal"><span class="pre">Listener</span></tt> object is otherwise the same as polling the controller.</p>
<p>Note that it is possible to skip a frame even when using <tt class="docutils literal"><span class="pre">Listener</span></tt> callbacks. If your onFrame callback function takes too long to complete, then the next frame is added to the history, but the onFrame callback is skipped. Less commonly, if the Leap software itself cannot finish processing a frame in time, that frame can be abandoned and not added to the history. This problem can occur when a computer is bogged down with too many other computing tasks.</p>
</div>
<div class="section" id="following-entities-across-frames">
<h2>Following entities across frames<a class="headerlink" href="#following-entities-across-frames" title="Permalink to this headline">¶</a></h2>
<p>If you have an ID of an entity from a different frame, you can get the object representing that entity in the current frame. Pass the ID to the <tt class="docutils literal"><span class="pre">Frame</span></tt> object function of the appropriate type:</p>
<div class="highlight-cpp"><div class="highlight"><pre><span class="n">Leap</span><span class="o">::</span><span class="n">Hand</span> <span class="n">hand</span> <span class="o">=</span> <span class="n">frame</span><span class="p">.</span><span class="n">hand</span><span class="p">(</span><span class="n">handID</span><span class="p">);</span>
<span class="n">Leap</span><span class="o">::</span><span class="n">Pointable</span> <span class="n">pointable</span> <span class="o">=</span> <span class="n">frame</span><span class="p">.</span><span class="n">pointable</span><span class="p">(</span><span class="n">pointableID</span><span class="p">);</span>
<span class="n">Leap</span><span class="o">::</span><span class="n">Finger</span> <span class="n">finger</span> <span class="o">=</span> <span class="n">frame</span><span class="p">.</span><span class="n">finger</span><span class="p">(</span><span class="n">fingerID</span><span class="p">);</span>
<span class="n">Leap</span><span class="o">::</span><span class="n">Tool</span> <span class="n">tool</span> <span class="o">=</span> <span class="n">frame</span><span class="p">.</span><span class="n">tool</span><span class="p">(</span><span class="n">toolID</span><span class="p">);</span>
</pre></div>
</div>
<p>If an object with the same ID cannot be found – perhaps a hand moved out of the field of view – then a special, invalid object is returned instead. Invalid objects are instances of the appropriate class, but all their members return 0 values, zero vectors, or other invalid objects. This technique makes it more convenient to chain method calls together. For example, the following code snippet averages finger tip positions over several frames:</p>
<div class="highlight-cpp"><div class="highlight"><pre><span class="c1">//Average a finger position for the last 10 frames</span>
<span class="kt">int</span> <span class="n">count</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="n">Leap</span><span class="o">::</span><span class="n">Vector</span> <span class="n">average</span> <span class="o">=</span> <span class="n">Leap</span><span class="o">::</span><span class="n">Vector</span><span class="p">();</span>
<span class="n">Leap</span><span class="o">::</span><span class="n">Finger</span> <span class="n">fingerToAverage</span> <span class="o">=</span> <span class="n">frame</span><span class="p">.</span><span class="n">fingers</span><span class="p">()[</span><span class="mi">0</span><span class="p">];</span>
<span class="k">for</span><span class="p">(</span> <span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o"><</span> <span class="mi">10</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span> <span class="p">)</span>
<span class="p">{</span>
<span class="n">Leap</span><span class="o">::</span><span class="n">Finger</span> <span class="n">fingerFromFrame</span> <span class="o">=</span> <span class="n">controller</span><span class="p">.</span><span class="n">frame</span><span class="p">(</span><span class="n">i</span><span class="p">).</span><span class="n">finger</span><span class="p">(</span><span class="n">fingerToAverage</span><span class="p">.</span><span class="n">id</span><span class="p">());</span>
<span class="k">if</span><span class="p">(</span> <span class="n">fingerFromFrame</span><span class="p">.</span><span class="n">isValid</span><span class="p">()</span> <span class="p">)</span>
<span class="p">{</span>
<span class="n">average</span> <span class="o">+=</span> <span class="n">fingerFromFrame</span><span class="p">.</span><span class="n">tipPosition</span><span class="p">();</span>
<span class="n">count</span><span class="o">++</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="n">average</span> <span class="o">/=</span> <span class="n">count</span><span class="p">;</span>
</pre></div>
</div>
<p>Without invalid objects, this code would have to check each <tt class="docutils literal"><span class="pre">Frame</span></tt> object before checking the returned Finger objects. Invalid objects reduce the amount of null checking you have to do when accessing Leap Motion tracking data.</p>
</div>
<div class="section" id="serialization">
<h2>Serialization<a class="headerlink" href="#serialization" title="Permalink to this headline">¶</a></h2>
<p>The <tt class="docutils literal"><span class="pre">Frame</span></tt> class provides <a class="reference external" href="../api/Leap.Frame.html#cppclass_leap_1_1_frame_1aa163dee25d1f498f7b52279c3eb2c38e">serialize()</a> and <a class="reference external" href="../api/Leap.Frame.html#cppclass_leap_1_1_frame_1adff8cf1970aee948138c9cd4406025e2">deserialize()</a> functions that allow you to store the data from a frame and later reconstruct it as a valid <a class="reference external" href="../api/Leap.Frame.html"><tt class="docutils literal"><span class="pre">Frame</span></tt></a> object. See <a class="reference internal" href="Leap_Serialization.html"><em>Serializing Tracking Data</em></a></p>
</div>
</div>
<!-- get_disqus_sso -->
</div>
<div id="sidebar" class="col-md-3">
<div class="well-sidebar" data-offset-top="188">
<ul>
<li><a href="../index.html" title="Home">C++ Docs (v3.1)</a></li>
</ul><ul class="current">
<li class="toctree-l1"><a class="reference internal" href="Leap_Overview.html">API Overview</a></li>
<li class="toctree-l1"><a class="reference internal" href="../practices/Leap_Practices.html">Guidelines</a></li>
<li class="toctree-l1"><a class="reference internal" href="Leap_Guides.html">Application Development</a></li>
<li class="toctree-l1 current"><a class="reference internal" href="Leap_Guides2.html">Using the Tracking API</a><ul class="current">
<li class="toctree-l2"><a class="reference internal" href="Leap_Controllers.html">Connecting to the Controller</a></li>
<li class="toctree-l2"><a class="reference internal" href="Leap_Tracking.html">Tracking Model</a></li>
<li class="toctree-l2 current"><a class="current reference internal" href="">Frames</a><ul>
<li class="toctree-l3"><a class="reference internal" href="#overview">Overview</a></li>
<li class="toctree-l3"><a class="reference internal" href="#getting-data-from-a-frame">Getting Data from a Frame</a></li>
<li class="toctree-l3"><a class="reference internal" href="#getting-frames-by-polling">Getting Frames by Polling</a></li>
<li class="toctree-l3"><a class="reference internal" href="#getting-frames-with-callbacks">Getting Frames with Callbacks</a></li>
<li class="toctree-l3"><a class="reference internal" href="#following-entities-across-frames">Following entities across frames</a></li>
<li class="toctree-l3"><a class="reference internal" href="#serialization">Serialization</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="Leap_Hand.html">Hands</a></li>
<li class="toctree-l2"><a class="reference internal" href="Leap_Pointables.html">Fingers</a></li>
<li class="toctree-l2"><a class="reference internal" href="Leap_Coordinate_Mapping.html">Coordinate Systems</a></li>
<li class="toctree-l2"><a class="reference internal" href="Leap_Images.html">Camera Images</a></li>
<li class="toctree-l2"><a class="reference internal" href="Leap_Serialization.html">Serializing Tracking Data</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../api/Leap_Classes.html">API Reference</a></li>
<li class="toctree-l1"><a class="reference internal" href="../supplements/Leap_Supplements.html">Appendices</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<!--
<div class="ribbon">
<p>C++</p>
</div>
<footer>
<div id="footer" class="container">
<div class="container">
<div class="copyright">
<span>Copyright © 2012 - 2016, Leap Motion, Inc.</span>
</div>
</div>
</div>
</footer>
</body>
</html>
|
Java
|
{% raw %}{% extends "wagtailadmin/home.html" %}
{% load wagtailcore_tags wagtailsettings_tags %}
{% get_settings %}
{% block branding_welcome %}
Welcome {% if settings.pages.SiteBranding.site_name %}to {{ settings.pages.SiteBranding.site_name }}{% endif %}
{% endblock %}{% endraw %}
|
Java
|
public enum CoffeePrice
{
Small = 50,
Normal = 100,
Double =200
}
|
Java
|
<!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 (1.8.0_66-internal) on Tue Dec 08 09:28:01 GMT 2015 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.apache.jena.sparql.expr.aggregate.AggAvgDistinct (Apache Jena ARQ)</title>
<meta name="date" content="2015-12-08">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.jena.sparql.expr.aggregate.AggAvgDistinct (Apache Jena ARQ)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<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><a href="../../../../../../../org/apache/jena/sparql/expr/aggregate/AggAvgDistinct.html" title="class in org.apache.jena.sparql.expr.aggregate">Class</a></li>
<li class="navBarCell1Rev">Use</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>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/apache/jena/sparql/expr/aggregate/class-use/AggAvgDistinct.html" target="_top">Frames</a></li>
<li><a href="AggAvgDistinct.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>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.jena.sparql.expr.aggregate.AggAvgDistinct" class="title">Uses of Class<br>org.apache.jena.sparql.expr.aggregate.AggAvgDistinct</h2>
</div>
<div class="classUseContainer">No usage of org.apache.jena.sparql.expr.aggregate.AggAvgDistinct</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<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><a href="../../../../../../../org/apache/jena/sparql/expr/aggregate/AggAvgDistinct.html" title="class in org.apache.jena.sparql.expr.aggregate">Class</a></li>
<li class="navBarCell1Rev">Use</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>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/apache/jena/sparql/expr/aggregate/class-use/AggAvgDistinct.html" target="_top">Frames</a></li>
<li><a href="AggAvgDistinct.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>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Licenced under the Apache License, Version 2.0</small></p>
</body>
</html>
|
Java
|
"use strict";
var mathUtils = require("./math-utils");
exports.shuffle = function(array) {
var len = array.length;
for ( var i=0; i<len; i++ ) {
var rand = mathUtils.randomInt(0,len-1);
var temp = array[i];
array[i] = array[rand];
array[rand] = temp;
}
};
|
Java
|
# -*- coding: utf-8 -*-
#
# Cloud Robotics FX 会話理解API用メッセージ
#
# @author: Osamu Noguchi <noguchi@headwaters.co.jp>
# @version: 0.0.1
import cloudrobotics.message as message
APP_ID = 'SbrApiServices'
PROCESSING_ID = 'RbAppConversationApi'
# 会話メッセージ
#
class ConversationMessage(message.CRFXMessage):
def __init__(self, visitor, visitor_id, talkByMe, type):
super(ConversationMessage, self).__init__()
self.header['RoutingType'] = message.ROUTING_TYPE_CALL
self.header['AppProcessingId'] = PROCESSING_ID
self.header['MessageId'] = type
self.body = {
'visitor': visitor,
'visitor_id': visitor_id,
'talkByMe': talkByMe
}
|
Java
|
Rails.application.routes.draw do
namespace :admin do
namespace :reports do
get 'deliveries' => 'deliveries#index'
end
get 'users' => 'users#index'
get 'users/:id' => 'users#show'
end
root to: 'pages#index'
end
|
Java
|
/* eslint quote-props: ["error", "consistent"] */
// Japanese Hirajoshi scale
// 1-4-2-1-4
// Gb G B Db D Gb
export default {
'a': { instrument: 'piano', note: 'a4' },
'b': { instrument: 'piano', note: 'eb3' },
'c': { instrument: 'piano', note: 'd6' },
'd': { instrument: 'piano', note: 'eb4' },
'e': { instrument: 'piano', note: 'd4' },
'f': { instrument: 'piano', note: 'bb5' },
'g': { instrument: 'piano', note: 'd7' },
'h': { instrument: 'piano', note: 'g3' },
'i': { instrument: 'piano', note: 'g5' },
'j': { instrument: 'piano', note: 'bb6' },
'k': { instrument: 'piano', note: 'eb6' },
'l': { instrument: 'piano', note: 'bb4' },
'm': { instrument: 'piano', note: 'a6' },
'n': { instrument: 'piano', note: 'a5' },
'o': { instrument: 'piano', note: 'd5' },
'p': { instrument: 'piano', note: 'a2' },
'q': { instrument: 'piano', note: 'bb2' },
'r': { instrument: 'piano', note: 'a3' },
's': { instrument: 'piano', note: 'd3' },
't': { instrument: 'piano', note: 'g4' },
'u': { instrument: 'piano', note: 'g6' },
'v': { instrument: 'piano', note: 'bb3' },
'w': { instrument: 'piano', note: 'eb5' },
'x': { instrument: 'piano', note: 'eb2' },
'y': { instrument: 'piano', note: 'g2' },
'z': { instrument: 'piano', note: 'eb7' },
'A': { instrument: 'celesta', note: 'a4' },
'B': { instrument: 'celesta', note: 'eb3' },
'C': { instrument: 'celesta', note: 'd6' },
'D': { instrument: 'celesta', note: 'eb4' },
'E': { instrument: 'celesta', note: 'd4' },
'F': { instrument: 'celesta', note: 'bb4' },
'G': { instrument: 'celesta', note: 'd2' },
'H': { instrument: 'celesta', note: 'g3' },
'I': { instrument: 'celesta', note: 'g5' },
'J': { instrument: 'celesta', note: 'bb6' },
'K': { instrument: 'celesta', note: 'eb6' },
'L': { instrument: 'celesta', note: 'bb5' },
'M': { instrument: 'celesta', note: 'a6' },
'N': { instrument: 'celesta', note: 'a5' },
'O': { instrument: 'celesta', note: 'd5' },
'P': { instrument: 'celesta', note: 'a7' },
'Q': { instrument: 'celesta', note: 'bb7' },
'R': { instrument: 'celesta', note: 'a3' },
'S': { instrument: 'celesta', note: 'd3' },
'T': { instrument: 'celesta', note: 'g4' },
'U': { instrument: 'celesta', note: 'g6' },
'V': { instrument: 'celesta', note: 'bb3' },
'W': { instrument: 'celesta', note: 'eb5' },
'X': { instrument: 'celesta', note: 'eb7' },
'Y': { instrument: 'celesta', note: 'g7' },
'Z': { instrument: 'celesta', note: 'eb2' },
'$': { instrument: 'swell', note: 'eb3' },
',': { instrument: 'swell', note: 'eb3' },
'/': { instrument: 'swell', note: 'bb3' },
'\\': { instrument: 'swell', note: 'eb3' },
':': { instrument: 'swell', note: 'g3' },
';': { instrument: 'swell', note: 'bb3' },
'-': { instrument: 'swell', note: 'bb3' },
'+': { instrument: 'swell', note: 'g3' },
'|': { instrument: 'swell', note: 'bb3' },
'{': { instrument: 'swell', note: 'bb3' },
'}': { instrument: 'swell', note: 'eb3' },
'[': { instrument: 'swell', note: 'g3' },
']': { instrument: 'swell', note: 'bb3' },
'%': { instrument: 'swell', note: 'bb3' },
'&': { instrument: 'swell', note: 'eb3' },
'*': { instrument: 'swell', note: 'eb3' },
'^': { instrument: 'swell', note: 'bb3' },
'#': { instrument: 'swell', note: 'g3' },
'!': { instrument: 'swell', note: 'g3' },
'@': { instrument: 'swell', note: 'eb3' },
'(': { instrument: 'swell', note: 'g3' },
')': { instrument: 'swell', note: 'eb3' },
'=': { instrument: 'swell', note: 'eb3' },
'~': { instrument: 'swell', note: 'g3' },
'`': { instrument: 'swell', note: 'eb3' },
'_': { instrument: 'swell', note: 'g3' },
'"': { instrument: 'swell', note: 'eb3' },
"'": { instrument: 'swell', note: 'bb3' },
'<': { instrument: 'swell', note: 'g3' },
'>': { instrument: 'swell', note: 'g3' },
'.': { instrument: 'swell', note: 'g3' },
'?': { instrument: 'swell', note: 'bb3' },
'0': { instrument: 'fluteorgan', note: 'd3' },
'1': { instrument: 'fluteorgan', note: 'eb3' },
'2': { instrument: 'fluteorgan', note: 'g3' },
'3': { instrument: 'fluteorgan', note: 'a3' },
'4': { instrument: 'fluteorgan', note: 'bb3' },
'5': { instrument: 'fluteorgan', note: 'd2' },
'6': { instrument: 'fluteorgan', note: 'eb2' },
'7': { instrument: 'fluteorgan', note: 'g2' },
'8': { instrument: 'fluteorgan', note: 'a2' },
'9': { instrument: 'fluteorgan', note: 'bb2' },
's1': { instrument: 'swell', note: 'eb3' },
's2': { instrument: 'swell', note: 'g3' },
's3': { instrument: 'swell', note: 'bb3' }
};
|
Java
|
<html>
<META HTTP-EQUIV=Content-Type Content="text/html; charset=utf8">
<!-- Mirrored from lis.ly.gov.tw/lghtml/lawstat/version2/01583/0158388122800.htm by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 24 Mar 2013 09:13:25 GMT -->
<head><title>法編號:01583 版本:088122800</title>
<link rel="stylesheet" type="text/css" href="../../version.css" >
</HEAD>
<body><left>
<table><tr><td><FONT COLOR=blue SIZE=5>國有財產法(01583)</font>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td>
<tr><td align=left valign=top>
<a href=0158358011000.html target=law01583><nobr><font size=2>中華民國 58 年 1 月 10 日</font></nobr></a>
</td>
<td valign=top><font size=2>制定77條</font></td>
<tr><td align=left valign=top><nobr><font size=2>中華民國 58 年 1 月 27 日公布</font></nobr></td>
<tr><td align=left valign=top>
<a href=0158360042700.html target=law01583><nobr><font size=2>中華民國 60 年 4 月 27 日</font></nobr></a>
</td>
<td valign=top><font size=2>修正第60條</font></td>
<tr><td align=left valign=top><nobr><font size=2>中華民國 60 年 5 月 5 日公布</font></nobr></td>
<tr><td align=left valign=top>
<a href=0158364010700.html target=law01583><nobr><font size=2>中華民國 64 年 1 月 7 日</font></nobr></a>
</td>
<td valign=top><font size=2>修正第8, 32, 38, 42, 44, 46, 47, 50, 52, 54條<br>
刪除第15條</font></td>
<tr><td align=left valign=top><nobr><font size=2>中華民國 64 年 1 月 17 日公布</font></nobr></td>
<tr><td align=left valign=top>
<a href=0158369122600.html target=law01583><nobr><font size=2>中華民國 69 年 12 月 26 日</font></nobr></a>
</td>
<td valign=top><font size=2>修正第13, 42條</font></td>
<tr><td align=left valign=top><nobr><font size=2>中華民國 70 年 1 月 12 日公布</font></nobr></td>
<tr><td align=left valign=top>
<a href=0158381031900.html target=law01583><nobr><font size=2>中華民國 81 年 3 月 19 日</font></nobr></a>
</td>
<td valign=top><font size=2>刪除第74條</font></td>
<tr><td align=left valign=top><nobr><font size=2>中華民國 81 年 4 月 6 日公布</font></nobr></td>
<tr><td align=left valign=top>
<a href=0158388122800.html target=law01583><nobr><font size=2>中華民國 88 年 12 月 28 日</font></nobr></a>
</td>
<td valign=top><font size=2>修正第42, 43, 46, 47, 49, 52, 58條<br>
增訂第52之1, 52之2條</font></td>
<tr><td align=left valign=top><nobr><font size=2>中華民國 89 年 1 月 12 日公布</font></nobr></td>
<tr><td align=left valign=top>
<a href=0158391040200.html target=law01583><nobr><font size=2>中華民國 91 年 4 月 2 日</font></nobr></a>
</td>
<td valign=top><font size=2>修正第50, 51條</font></td>
<tr><td align=left valign=top><nobr><font size=2>中華民國 91 年 4 月 24 日公布</font></nobr></td>
<tr><td align=left valign=top>
<a href=0158392011300.html target=law01583><nobr><font size=2>中華民國 92 年 1 月 13 日</font></nobr></a>
</td>
<td valign=top><font size=2>修正第52之2條</font></td>
<tr><td align=left valign=top><nobr><font size=2>中華民國 92 年 2 月 6 日公布</font></nobr></td>
<tr><td align=left valign=top>
<a href=01583100121400.html target=law01583><nobr><font size=2>中華民國 100 年 12 月 14 日</font></nobr></a>
</td>
<td valign=top><font size=2>修正第33, 39, 53條</font></td>
<tr><td align=left valign=top><nobr><font size=2>中華民國 101 年 1 月 4 日公布</font></nobr></td>
</table></table></table></table>
<p><table><tr><td><font color=blue size=4>民國88年12月28日(非現行條文)</font></td>
<td><a href=http://lis.ly.gov.tw/lghtml/lawstat/reason2/0158388122800.htm target=reason><font size=2>立法理由</font></a></td>
<td><a href=http://lis.ly.gov.tw/lgcgi/lglawproc?0158388122800 target=proc><font size=2>立法紀錄</font></a></td>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第一章 總則</font>
<table><tr><td> </td><td><font color=8000ff>第一條</font>
</font>
<table><tr><td> </td>
<td>
國有財產之取得、保管、使用、收益及處分,依本法之規定;本法未規定者,適用其他法律。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二條</font>
</font>
<table><tr><td> </td>
<td>
國家依據法律規定,或基於權力行使,或由於預算支出,或由於接受捐贈所取得之財產,為國有財產。<br>
凡不屬於私有或地方所有之財產,除法律另有規定外,均應視為國有財產。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三條</font>
</font>
<table><tr><td> </td>
<td>
依前條取得之國有財產,其範圍如左:<br>
一、不動產:指土地及其改良物暨天然資源。<br>
二、動產:指機械及設備、交通運輸及設備,暨其他雜項設備。<br>
三、有價證券:指國家所有之股份或股票及債券。<br>
四、權利:指地上權、地役權、典權、抵押權、礦業權、漁業權、專利權、著作權、商標權及其他財產上之權利。<br>
前項第二款財產之詳細分類,依照行政院規定辦理。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四條</font>
</font>
<table><tr><td> </td>
<td>
國有財產區分為公用財產與非公用財產兩類。<br>
左列各種財產稱為公用財產。<br>
一、公務用財產:各機關、部隊、學校、辦公、作業及宿舍使用之國有財產均屬之。<br>
二、公共用財產:國家直接供公共使用之國有財產均屬之。<br>
三、事業用財產:國營事業機關使用之財產均屬之。但國營事業為公司組織者,僅指其股份而言。<br>
非公用財產,係指公用財產以外可供收益或處分之一切國有財產。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五條</font>
</font>
<table><tr><td> </td>
<td>
第三條第一項所定範圍以外之左列國有財產,其保管或使用,仍依其他有關法令辦理:<br>
一、軍品及軍用器材。<br>
二、圖書、史料、古物及故宮博物。<br>
三、國營事業之生產材料。<br>
四、其他可供公用或應保存之有形或無形財產。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六條</font>
</font>
<table><tr><td> </td>
<td>
國家為保障邊疆各民族之土地使用,得視地方實際情況,保留國有土地及其定著物;其管理辦法由行政院定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第七條</font>
</font>
<table><tr><td> </td>
<td>
國有財產收益及處分,依預算程序為之;其收入應解國庫。<br>
凡屬事業用之公用財產,在使用期間或變更為非公用財產,而為收益或處分時,均依公營事業有關規定程序辦理。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第八條</font>
</font>
<table><tr><td> </td>
<td>
國有土地及國有建築改良物,除放租有收益及第四條第二項第三款所指事業用者外,免徵土地稅及建築改良物稅。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第二章 機構</font>
<table><tr><td> </td><td><font color=8000ff>第九條</font>
</font>
<table><tr><td> </td>
<td>
財政部承行政院之命,綜理國有財產事務。<br>
財政部設國有財產局,承辦前項事務;其組織以法律定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十條</font>
</font>
<table><tr><td> </td>
<td>
公用財產之主管機關,依預算法之規定。<br>
公用財產為二個以上機關共同使用,不屬於同一機關管理者,其主管機關由行政院指定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十一條</font>
</font>
<table><tr><td> </td>
<td>
公用財產以各直接使用機關為管理機關,直接管理之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十二條</font>
</font>
<table><tr><td> </td>
<td>
非公用財產以財政部國有財產局為管理機關,承財政部之命,直接管理之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十三條</font>
</font>
<table><tr><td> </td>
<td>
財政部視國有財產實際情況之需要,得委託地方政府或適當機構代為管理或經營。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十四條</font>
</font>
<table><tr><td> </td>
<td>
國有財產在國境外者,由外交部主管,並由各使領館直接管理;如當地無使領館時,由外交部委託適當機構代為管理。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十五條</font>
</font>
<table><tr><td> </td>
<td>
(刪除)<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十六條</font>
</font>
<table><tr><td> </td>
<td>
財政部國有財產局設國有財產估價委員會,為國有財產估價機構;其組織由財政部定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第三章 保管</font>
<table><tr><td> </td>
<td><font color=4000ff size=4>第一節 登記</font>
<table><tr><td> </td><td><font color=8000ff>第十七條</font>
</font>
<table><tr><td> </td>
<td>
第三條所指取得之不動產、動產、有價證券及權利,應分別依有關法令完成國有登記,或確定其權屬。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十八條</font>
</font>
<table><tr><td> </td>
<td>
不動產之國有登記,由管理機關囑託該管直轄市、縣(市)地政機關為之。<br>
動產、有價證券及權利有關確定權屬之程序,由管理機關辦理之。<br>
依本條規定取得之產權憑證,除第二十六條規定外,由管理機關保管之。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第十九條</font>
</font>
<table><tr><td> </td>
<td>
尚未完成登記應屬國有之土地,除公用財產依前條規定辦理外,得由財政部國有財產局或其所屬分支機構囑託該管直轄市、縣(市)地政機關辦理國有登記,必要時得分期、分區辦理。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十條</font>
</font>
<table><tr><td> </td>
<td>
國有財產在國境外者,應由外交部或各使領館依所在地國家法令,辦理確定權屬之程序。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td>
<td>
<table><tr><td> </td>
<td><font color=4000ff size=4>第二節 產籍</font>
<table><tr><td> </td><td><font color=8000ff>第二十一條</font>
</font>
<table><tr><td> </td>
<td>
管理機關應設國有財產資料卡及明細分類帳,就所經管之國有財產,分類、編號、製卡、登帳,並列冊層報主管機關;其異動情形,應依會計報告程序為之。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十二條</font>
</font>
<table><tr><td> </td>
<td>
財政部應設國有財產總帳,就各管理機關所送資料整理、分類、登錄。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十三條</font>
</font>
<table><tr><td> </td>
<td>
國有財產因故滅失、毀損或拆卸、改裝,經有關機關核准報廢者,或依本法規定出售或贈與者,應由管理機關於三個月內列表層轉財政部註銷產籍。但涉及民事或刑事者不在此限。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十四條</font>
</font>
<table><tr><td> </td>
<td>
第二十一條至第二十三條所定卡、帳、表、冊之格式及財產編號,由財政部會商中央主計機關及審計機關統一訂定之。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td>
<td>
<table><tr><td> </td>
<td><font color=4000ff size=4>第三節 維護</font>
<table><tr><td> </td><td><font color=8000ff>第二十五條</font>
</font>
<table><tr><td> </td>
<td>
管理機關對其經管之國有財產,除依法令報廢者外,應注意保養及整修,不得毀損、棄置。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十六條</font>
</font>
<table><tr><td> </td>
<td>
有價證券應交由當地國庫或其代理機構負責保管。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十七條</font>
</font>
<table><tr><td> </td>
<td>
國有財產直接經管人員或使用人,因故意或過失,致財產遭受損害時,除涉及刑事責任部分,應由管理機關移送該管法院究辦外,並應負賠償責任。但因不可抗力而發生損害者,其責任經審計機關查核後決定之。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十八條</font>
</font>
<table><tr><td> </td>
<td>
主管機關或管理機關對於公用財產不得為任何處分或擅為收益。但其收益不違背其事業目的或原定用途者,不在此限。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第二十九條</font>
</font>
<table><tr><td> </td>
<td>
國有財產在國境外者,非依法經外交部核准,並徵得財政部同意,不得為任何處分。但為應付國際間之突發事件,得為適當之處理,於處理後即報外交部,並轉財政部及有關機關。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十條</font>
</font>
<table><tr><td> </td>
<td>
國有不動產經他人以虛偽之方法,為權利之登記者,經主管機關或管理機關查明確實後,應依民事訴訟法之規定,提起塗銷之訴;並得於起訴後囑託該管直轄市、縣(市)地政機關,為異議登記。<br>
前項為虛偽登記之申請人及登記人員,並應移送該管法院查究其刑責。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十一條</font>
</font>
<table><tr><td> </td>
<td>
國有財產管理人員,對於經管之國有財產不得買受或承租,或為其他與自己有利之處分或收益行為。<br>
違反前項規定之行為無效。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第四章 使用</font>
<table><tr><td> </td>
<td><font color=4000ff size=4>第一節 公用財產之用途</font>
<table><tr><td> </td><td><font color=8000ff>第三十二條</font>
</font>
<table><tr><td> </td>
<td>
公用財產應依預定計畫及規定用途或事業目的使用;其事業用財產,仍適用營業預算程序。<br>
天然資源之開發、利用及管理,除法律另有規定外,應由管理機關善為規劃,有效運用。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十三條</font>
</font>
<table><tr><td> </td>
<td>
公用財產用途廢止時,應變更為非公用財產。但依法徵收之土地,適用土地法之規定。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十四條</font>
</font>
<table><tr><td> </td>
<td>
財政部基於國家政策需要,得徵商主管機關同意,報經行政院核准,將公用財產變更為非公用財產。<br>
公用財產與非公用財產得互易其財產類別,經財政部與主管機關協議,報經行政院核定為之。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十五條</font>
</font>
<table><tr><td> </td>
<td>
公用財產變更為非公用財產時,由主管機關督飭該管理機關移交財政部國有財產局接管。但原屬事業用財產,得由原事業主管機關,依預算程序處理之。<br>
非公用財產經核定變更為公用財產時,由財政部國有財產局移交公用財產主管機關或管理機關接管。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十六條</font>
</font>
<table><tr><td> </td>
<td>
主管機關基於事實需要,得將公務用、公共用財產,在原規定使用範圍內變更用途,並得將各該種財產相互交換使用。<br>
前項變更用途或相互交換使用,須變更主管機關者,應經各該主管機關之協議,並徵得財政部之同意。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十七條</font>
</font>
<table><tr><td> </td>
<td>
國家接受捐贈之財產,屬於第三條規定之範圍者,應由受贈機關隨時通知財政部轉報行政院,視其用途指定其主管機關。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td>
<td>
<table><tr><td> </td>
<td><font color=4000ff size=4>第二節 非公用財產之撥用</font>
<table><tr><td> </td><td><font color=8000ff>第三十八條</font>
</font>
<table><tr><td> </td>
<td>
非公用財產類之不動產,各級政府機關為公務或公共所需,得申請撥用。但有左列情形之一者,不得辦理撥用:<br>
一、位於繁盛地區,依申請撥用之目的,非有特別需要者。<br>
二、擬作為宿舍用途者。<br>
三、不合區域計畫或都市計畫土地使用分區規定者。<br>
前項撥用,應由申請撥用機關檢具使用計畫及圖說,報經其上級機關核明屬實,並徵得財政部國有財產局同意後,層報行政院核定之。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第三十九條</font>
</font>
<table><tr><td> </td>
<td>
非公用財產經撥為公用後,遇有左列情事之一者,應由財政部查明隨時收回,交財政部國有財產局接管。但撥用土地之收回,應由財政部呈請行政院撤銷撥用後為之:<br>
一、用途廢止時。<br>
二、變更原定用途時。<br>
三、於原定用途外,擅供收益使用時。<br>
四、擅自讓由他人使用時。<br>
五、建地空置逾一年,尚未開始建築時。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td>
<td>
<table><tr><td> </td>
<td><font color=4000ff size=4>第三節 非公用財產之借用</font>
<table><tr><td> </td><td><font color=8000ff>第四十條</font>
</font>
<table><tr><td> </td>
<td>
非公用財產得供各機關、部隊、學校因臨時性或緊急性之公務用或公共用,為短期之借用;其借用期間,不得逾三個月。如屬土地,並不得供建築使用。<br>
前項借用手續,應由需用機關徵得管理機關同意為之,並通知財政部。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四十一條</font>
</font>
<table><tr><td> </td>
<td>
非公用財產經借用後,遇有左列情事之一者,應由管理機關查明隨時收回:<br>
一、借用原因消滅時。<br>
二、於原定用途外,另供收益使用時。<br>
三、擅自讓由他人使用時。<br>
非公用財產借用期間,如有增建、改良或修理情事,收回時不得請求補償。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第五章 收益</font>
<table><tr><td> </td>
<td><font color=4000ff size=4>第一節 非公用財產之出租</font>
<table><tr><td> </td><td><font color=8000ff>第四十二條</font>
</font>
<table><tr><td> </td>
<td>
非公用財產類不動產之出租,得以標租方式辦理。但合於左列各款規定之一者,得逕予出租:<br>
一、原有租賃期限屆滿,未逾六個月者。<br>
二、民國八十二年七月二十一日前已實際使用,並願繳清歷年使用補償金者。<br>
三、依法得讓售者。<br>
非公用財產類之不動產出租,應以書面為之;未以書面為之者,不生效力。<br>
非公用財產類之不動產依法已為不定期租賃關係者,承租人應於規定期限內訂定書面契約;未於規定期限內訂定書面契約者,管理機關得終止租賃關係。<br>
前項期限及非公用財產類不動產出租管理辦法,由財政部擬定報請行政院核定後發布之。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四十三條</font>
</font>
<table><tr><td> </td>
<td>
非公用財產類之不動產出租,應依左列各款規定,約定期限:<br>
一、建築改良物,五年以下。<br>
二、建築基地,二十年以下。<br>
三、其他土地,六年至十年。<br>
約定租賃期限屆滿時,得更新之。<br>
非公用財產類之不動產租金率,依有關土地法律規定;土地法律未規定者,由財政部斟酌實際情形擬訂,報請行政院核定之。但以標租方式出租或出租係供作營利使用者,其租金率得不受有關土地法律規定之限制。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四十四條</font>
</font>
<table><tr><td> </td>
<td>
非公用財產類之不動產出租後,除依其他法律規定得予終止租約收回外,遇有左列情形之一者,亦得解約收回:<br>
一、基於國家政策需要,變更為公用財產時。<br>
二、承租人變更約定用途時。<br>
三、因開發、利用或重行修建,有收回必要時。<br>
承租人因前項第一、第三兩款規定,解除租約所受之損失,得請求補償。其標準由財政部核定之。<br>
非公用財產類之不動產解除租約時,除出租機關許可之增建或改良部分,得由承租人請求補償其現值外,應無償收回;其有毀損情事者,應責令承租人回復原狀。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四十五條</font>
</font>
<table><tr><td> </td>
<td>
非公用財產類之動產,以不出租為原則。但基於國家政策或國庫利益,在無適當用途前,有暫予出租之必要者,得經財政部專案核准為之。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td>
<td>
<table><tr><td> </td>
<td><font color=4000ff size=4>第二節 非公用財產之利用</font>
<table><tr><td> </td><td><font color=8000ff>第四十六條</font>
</font>
<table><tr><td> </td>
<td>
國有耕地得提供為放租或放領之用;其放租、放領實施辦法,由內政部會商財政部擬訂,報請行政院核定之。<br>
邊際及海岸地可闢為觀光或作海水浴場等事業用者,得提供利用辦理放租;可供造林、農墾、養殖等事業用者,得辦理放租或放領。其辦法由財政部會同有關機關擬訂,報請行政院核定之。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四十七條</font>
</font>
<table><tr><td> </td>
<td>
非公用財產類不動產,得依法改良利用。<br>
財政部國有財產局得以委託、合作或信託方式,配合區域計畫、都市計畫辦理左列事項:<br>
一、改良土地。<br>
二、興建公務或公共用房屋。<br>
三、其他非興建房屋之事業。<br>
經改良之土地,以標售為原則。但情形特殊,適於以設定地上權或其他方式處理者,得報請行政院核定之。<br>
第二項各款事業,依其計畫須由財政部國有財產局負擔資金者,應編列預算。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第四十八條</font>
</font>
<table><tr><td> </td>
<td>
非公用財產類之動產,得提供投資之用。但以基於國家政策及國庫利益,確有必要者為限。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第六章 處分</font>
<table><tr><td> </td>
<td><font color=4000ff size=4>第一節 非公用財產類不動產之處分</font>
<table><tr><td> </td><td><font color=8000ff>第四十九條</font>
</font>
<table><tr><td> </td>
<td>
非公用財產類之不動產,其已有租賃關係者,得讓售與直接使用人。<br>
前項得予讓售之不動產範圍,由行政院另定之。<br>
非公用財產類之不動產,其經地方政府認定應與鄰接土地合併建築使用者,得讓售與有合併使用必要之鄰地所有權人。<br>
第一項及第三項讓售,由財政部國有財產局辦理之。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十條</font>
</font>
<table><tr><td> </td>
<td>
非公用財產類之不動產,為國營事業機關或地方公營事業機構,因業務上所必需者,得予讓售。<br>
前項讓售,分別由各該主管機關或省(市)政府,商請財政部核准,並徵得審計機關同意為之。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十一條</font>
</font>
<table><tr><td> </td>
<td>
非公用財產類之不動產,為社會、文化、教育、慈善、救濟團體舉辦公共福利事業或慈善救濟事業所必需者,得予讓售。<br>
前項讓售,分別由各該主管機關或省(市)政府,商請財政部轉報行政院核定,並徵得審計機關同意為之。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十二條</font>
</font>
<table><tr><td> </td>
<td>
非公用財產類之土地,經政府提供興建國民住宅或獎勵投資各項用地者,得予讓售。<br>
前項讓售,依國民住宅條例及其他有關規定辦理。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十二條之一</font>
</font>
<table><tr><td> </td>
<td>
非公用財產類之不動產,有左列各款情形之一者,得專案報經財政部核准讓售:<br>
一、使用他人土地之國有房屋。<br>
二、原屬國有房屋業已出售,其尚未併售之建築基地。<br>
三、共有不動產之國有持分。<br>
四、獲准整體開發範圍內之國有不動產。<br>
五、非屬公墓而其地目為「墓」並有墳墓之土地。<br>
六、其他不屬前五款情況,而其使用情形或位置情形確屬特殊者。<br>
非公用財產類之不動產,基於國家建設需要,不宜標售者,得專案報經行政院核准讓售。<br>
非公用財產類之不動產,為提高利用價值,得專案報經財政部核准與他人所有之不動產交換所有權。其交換辦法,由財政部擬訂,報請行政院核定之。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十二條之二</font>
</font>
<table><tr><td> </td>
<td>
非公用財產類之不動產,於民國三十五年十二月三十一日以前已供建築、居住使用至今者,其直接使用人得於本法修正施行日起三年內,檢具有關證明文件,向財政部國有財產局或所屬分支機構申請讓售。經核准者,其土地面積在五百平方公尺以內部分,得按第一次公告土地現值計價。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十三條</font>
</font>
<table><tr><td> </td>
<td>
非公用財產類之空屋、空地,並無預定用途者,得予標售。<br>
前項標售,由財政部國有財產局辦理之。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十四條</font>
</font>
<table><tr><td> </td>
<td>
非公用財產類之不動產,使用人無租賃關係或不合第四十二條第一項第二款之規定者,應收回標售或自行利用。<br>
其有左列情形之一者,得經財政部核准辦理現狀標售:<br>
一、經財政部核准按現狀接管處理者。<br>
二、接管時已有墳墓或已作墓地使用者。<br>
三、使用情形複雜,短期間內無法騰空辦理標售,且因情形特殊,急待處理者。<br>
前項標售,由財政部國有財產局辦理之。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td>
<td>
<table><tr><td> </td>
<td><font color=4000ff size=4>第二節 非公用財產類動產、有價證券及權利之處分</font>
<table><tr><td> </td><td><font color=8000ff>第五十五條</font>
</font>
<table><tr><td> </td>
<td>
非公用財產類之動產不堪使用者,得予標售,或拆卸後就其殘料另予改裝或標售。<br>
前項標售或拆卸、改裝,由財政部國有財產局報經財政部,按其權責核轉審計機關報廢後為之。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十六條</font>
</font>
<table><tr><td> </td>
<td>
有價證券,得經行政院核准予以出售。<br>
前項出售,由財政部商得審計機關同意,依證券交易法之規定辦理。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十七條</font>
</font>
<table><tr><td> </td>
<td>
第三條第一項第四款財產上權利之處分,應分別按其財產類別,經主管機關或財政部核定之。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td>
<td>
<table><tr><td> </td>
<td><font color=4000ff size=4>第三節 計價</font>
<table><tr><td> </td><td><font color=8000ff>第五十八條</font>
</font>
<table><tr><td> </td>
<td>
國有財產計價方式,經國有財產估價委員會議訂,由財政部報請行政院核定之。但放領土地地價之計算,依放領土地有關法令規定辦理。<br>
有價證券之售價,由財政部核定之。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第五十九條</font>
</font>
<table><tr><td> </td>
<td>
非公用財產之預估售價,達於審計法令規定之稽察限額者,應經審計機關之同意。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td>
<td>
<table><tr><td> </td>
<td><font color=4000ff size=4>第四節 贈與</font>
<table><tr><td> </td><td><font color=8000ff>第六十條</font>
</font>
<table><tr><td> </td>
<td>
在國外之國有財產,有贈與外國政府或其人民必要者,得層請行政院核准贈與之。<br>
在國內之國有財產,其贈與行為以動產為限。但現為寺廟、教堂所使用之不動產,合於國人固有信仰,有贈與該寺廟、教堂依法成立之財團法人必要者,得贈與之。<br>
前項贈與辦法。由行政院定之。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第七章 檢核</font>
<table><tr><td> </td>
<td><font color=4000ff size=4>第一節 財產檢查</font>
<table><tr><td> </td><td><font color=8000ff>第六十一條</font>
</font>
<table><tr><td> </td>
<td>
國有財產之檢查,除審計機關依審計法令規定隨時稽察外,主管機關對於各管理機關或國外代管機構有關公用財產保管、使用、收益及處分情形,應為定期與不定期之檢查。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十二條</font>
</font>
<table><tr><td> </td>
<td>
財政部對於各主管機關及委託代管機構管理公用財產情形,應隨時查詢。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十三條</font>
</font>
<table><tr><td> </td>
<td>
財政部對於財政部國有財產局及委託經營事業機構管理或經營非公用財產情形,應隨時考查,並應注意其撥用或借用後,用途有無變更。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td>
<td>
<table><tr><td> </td>
<td><font color=4000ff size=4>第二節 財產報告</font>
<table><tr><td> </td><td><font color=8000ff>第六十四條</font>
</font>
<table><tr><td> </td>
<td>
管理機關或委託代管機構,應於每一會計年度開始前,擬具公用財產異動計畫,報由主管機關核轉財政部審查。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十五條</font>
</font>
<table><tr><td> </td>
<td>
財政部國有財產局及委託經營事業機構,於每一會計年度開始前,應對非公用財產之管理或經營擬具計畫,報財政部審定。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十六條</font>
</font>
<table><tr><td> </td>
<td>
財政部應於每一會計年度開始前,對於公用財產及非公用財產,就第六十四條及第六十五條所擬之計畫加具審查意見,呈報行政院;其涉及處分事項,應列入中央政府年度總預算。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十七條</font>
</font>
<table><tr><td> </td>
<td>
管理機關及委託代管機構,應於每一會計年度終了時,編具公用財產目錄及財產增減表,呈報主管機關彙轉財政部及中央主計機關暨審計機關。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十八條</font>
</font>
<table><tr><td> </td>
<td>
財政部國有財產局及委託經營事業機構,應於每一會計年度終了時,編具非公用財產目錄及財產增減表,呈報財政部,並分轉中央主計機關及審計機關。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第六十九條</font>
</font>
<table><tr><td> </td>
<td>
財政部應於每一會計年度終了時,就各主管機關及財政部國有財產局等所提供之資料,編具國有財產總目錄,呈報行政院彙入中央政府年度總決算。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第七十條</font>
</font>
<table><tr><td> </td>
<td>
第六十四條至第六十九條所指之計畫、目錄及表報格式,由財政部會商中央主計機關及審計機關定之。<br>
</td>
</table>
</table>
</table>
</table>
<table><tr><td> </td>
<td><font color=4000ff size=4>第八章 附則</font>
<table><tr><td> </td><td><font color=8000ff>第七十一條</font>
</font>
<table><tr><td> </td>
<td>
國有財產經管人員違反第二十一條之規定,應登帳而未登帳,並有隱匿或侵占行為者,加重其刑至二分之一。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第七十二條</font>
</font>
<table><tr><td> </td>
<td>
國有財產被埋藏、沉沒者,其掘發、打撈辦法,由行政院定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第七十三條</font>
</font>
<table><tr><td> </td>
<td>
國有財產漏未接管,經舉報後發現,或被人隱匿經舉報後收回,或經舉報後始撈取、掘獲者,給予舉報人按財產總值一成以下之獎金。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第七十四條</font>
</font>
<table><tr><td> </td>
<td>
(刪除)<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第七十五條</font>
</font>
<table><tr><td> </td>
<td>
本法施行區域,由行政院以命令定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第七十六條</font>
</font>
<table><tr><td> </td>
<td>
本法施行細則,由行政院定之。<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td>
<table><tr><td> </td><td><font color=8000ff>第七十七條</font>
</font>
<table><tr><td> </td>
<td>
本法自公布日施行。<br>
</td>
</table>
</table>
</table>
</left>
</body>
<!-- Mirrored from lis.ly.gov.tw/lghtml/lawstat/version2/01583/0158388122800.htm by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 24 Mar 2013 09:13:25 GMT -->
</html>
|
Java
|
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
namespace PInvoke
{
using System.Runtime.InteropServices;
/// <content>
/// Contains the <see cref="WIN32_FIND_DATA"/> nested type.
/// </content>
public partial class Kernel32
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WIN32_FIND_DATA
{
/// <summary>
/// The file attributes of a file.
/// </summary>
/// <remarks>
/// Although the enum we bind to here exists in the .NET Framework
/// as System.IO.FileAttributes, it is not reliably present.
/// Portable profiles don't include it, for example. So we have to define our own.
/// </remarks>
public FileAttribute dwFileAttributes;
/// <summary>
/// A FILETIME structure that specifies when a file or directory was created.
/// If the underlying file system does not support creation time, this member is zero.
/// </summary>
public FILETIME ftCreationTime;
/// <summary>
/// A FILETIME structure.
/// For a file, the structure specifies when the file was last read from, written to, or for executable files, run.
/// For a directory, the structure specifies when the directory is created.If the underlying file system does not support last access time, this member is zero.
/// On the FAT file system, the specified date for both files and directories is correct, but the time of day is always set to midnight.
/// </summary>
public FILETIME ftLastAccessTime;
/// <summary>
/// A FILETIME structure.
/// For a file, the structure specifies when the file was last written to, truncated, or overwritten, for example, when WriteFile or SetEndOfFile are used.The date and time are not updated when file attributes or security descriptors are changed.
/// For a directory, the structure specifies when the directory is created.If the underlying file system does not support last write time, this member is zero.
/// </summary>
public FILETIME ftLastWriteTime;
/// <summary>
/// The high-order DWORD value of the file size, in bytes.
/// This value is zero unless the file size is greater than MAXDWORD.
/// The size of the file is equal to(nFileSizeHigh* (MAXDWORD+1)) + nFileSizeLow.
/// </summary>
public uint nFileSizeHigh;
/// <summary>
/// The low-order DWORD value of the file size, in bytes.
/// </summary>
public uint nFileSizeLow;
/// <summary>
/// If the dwFileAttributes member includes the FILE_ATTRIBUTE_REPARSE_POINT attribute, this member specifies the reparse point tag.
/// Otherwise, this value is undefined and should not be used.
/// For more information see Reparse Point Tags.
/// </summary>
public uint dwReserved0;
/// <summary>
/// Reserved for future use.
/// </summary>
public uint dwReserved1;
/// <summary>
/// The name of the file.
/// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string cFileName;
/// <summary>
/// An alternative name for the file.
/// This name is in the classic 8.3 file name format.
/// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public string cAlternateFileName;
}
}
}
|
Java
|
package arn
// PersonName represents the name of a person.
type PersonName struct {
English Name `json:"english" editable:"true"`
Japanese Name `json:"japanese" editable:"true"`
}
// String returns the default visualization of the name.
func (name *PersonName) String() string {
return name.ByUser(nil)
}
// ByUser returns the preferred name for the given user.
func (name *PersonName) ByUser(user *User) string {
if user == nil {
return name.English.String()
}
switch user.Settings().TitleLanguage {
case "japanese":
if name.Japanese.String() == "" {
return name.English.String()
}
return name.Japanese.String()
default:
return name.English.String()
}
}
|
Java
|
package testdata
import (
. "goa.design/goa/v3/dsl"
)
var ConflictWithAPINameAndServiceNameDSL = func() {
var _ = API("aloha", func() {
Title("conflict with API name and service names")
})
var _ = Service("aloha", func() {}) // same as API name
var _ = Service("alohaapi", func() {}) // API name + 'api' suffix
var _ = Service("alohaapi1", func() {}) // API name + 'api' suffix + sequential no.
}
var ConflictWithGoifiedAPINameAndServiceNamesDSL = func() {
var _ = API("good-by", func() {
Title("conflict with goified API name and goified service names")
})
var _ = Service("good-by-", func() {}) // Goify name is same as API name
var _ = Service("good-by-api", func() {}) // API name + 'api' suffix
var _ = Service("good-by-api-1", func() {}) // API name + 'api' suffix + sequential no.
}
|
Java
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {async, fakeAsync, tick} from '@angular/core/testing';
import {AsyncTestCompleter, beforeEach, describe, inject, it} from '@angular/core/testing/testing_internal';
import {AbstractControl, FormArray, FormControl, FormGroup, Validators} from '@angular/forms';
import {EventEmitter} from '../src/facade/async';
import {isPresent} from '../src/facade/lang';
export function main() {
function asyncValidator(expected: string, timeouts = {}) {
return (c: AbstractControl) => {
let resolve: (result: any) => void;
const promise = new Promise(res => { resolve = res; });
const t = isPresent((timeouts as any)[c.value]) ? (timeouts as any)[c.value] : 0;
const res = c.value != expected ? {'async': true} : null;
if (t == 0) {
resolve(res);
} else {
setTimeout(() => { resolve(res); }, t);
}
return promise;
};
}
function asyncValidatorReturningObservable(c: FormControl) {
const e = new EventEmitter();
Promise.resolve(null).then(() => { e.emit({'async': true}); });
return e;
}
describe('FormGroup', () => {
describe('value', () => {
it('should be the reduced value of the child controls', () => {
const g = new FormGroup({'one': new FormControl('111'), 'two': new FormControl('222')});
expect(g.value).toEqual({'one': '111', 'two': '222'});
});
it('should be empty when there are no child controls', () => {
const g = new FormGroup({});
expect(g.value).toEqual({});
});
it('should support nested groups', () => {
const g = new FormGroup({
'one': new FormControl('111'),
'nested': new FormGroup({'two': new FormControl('222')})
});
expect(g.value).toEqual({'one': '111', 'nested': {'two': '222'}});
(<FormControl>(g.get('nested.two'))).setValue('333');
expect(g.value).toEqual({'one': '111', 'nested': {'two': '333'}});
});
});
describe('getRawValue', () => {
let fg: FormGroup;
it('should work with nested form groups/arrays', () => {
fg = new FormGroup({
'c1': new FormControl('v1'),
'group': new FormGroup({'c2': new FormControl('v2'), 'c3': new FormControl('v3')}),
'array': new FormArray([new FormControl('v4'), new FormControl('v5')])
});
fg.get('group').get('c3').disable();
(fg.get('array') as FormArray).at(1).disable();
expect(fg.getRawValue())
.toEqual({'c1': 'v1', 'group': {'c2': 'v2', 'c3': 'v3'}, 'array': ['v4', 'v5']});
});
});
describe('adding and removing controls', () => {
it('should update value and validity when control is added', () => {
const g = new FormGroup({'one': new FormControl('1')});
expect(g.value).toEqual({'one': '1'});
expect(g.valid).toBe(true);
g.addControl('two', new FormControl('2', Validators.minLength(10)));
expect(g.value).toEqual({'one': '1', 'two': '2'});
expect(g.valid).toBe(false);
});
it('should update value and validity when control is removed', () => {
const g = new FormGroup(
{'one': new FormControl('1'), 'two': new FormControl('2', Validators.minLength(10))});
expect(g.value).toEqual({'one': '1', 'two': '2'});
expect(g.valid).toBe(false);
g.removeControl('two');
expect(g.value).toEqual({'one': '1'});
expect(g.valid).toBe(true);
});
});
describe('errors', () => {
it('should run the validator when the value changes', () => {
const simpleValidator = (c: FormGroup) =>
c.controls['one'].value != 'correct' ? {'broken': true} : null;
const c = new FormControl(null);
const g = new FormGroup({'one': c}, simpleValidator);
c.setValue('correct');
expect(g.valid).toEqual(true);
expect(g.errors).toEqual(null);
c.setValue('incorrect');
expect(g.valid).toEqual(false);
expect(g.errors).toEqual({'broken': true});
});
});
describe('dirty', () => {
let c: FormControl, g: FormGroup;
beforeEach(() => {
c = new FormControl('value');
g = new FormGroup({'one': c});
});
it('should be false after creating a control', () => { expect(g.dirty).toEqual(false); });
it('should be true after changing the value of the control', () => {
c.markAsDirty();
expect(g.dirty).toEqual(true);
});
});
describe('touched', () => {
let c: FormControl, g: FormGroup;
beforeEach(() => {
c = new FormControl('value');
g = new FormGroup({'one': c});
});
it('should be false after creating a control', () => { expect(g.touched).toEqual(false); });
it('should be true after control is marked as touched', () => {
c.markAsTouched();
expect(g.touched).toEqual(true);
});
});
describe('setValue', () => {
let c: FormControl, c2: FormControl, g: FormGroup;
beforeEach(() => {
c = new FormControl('');
c2 = new FormControl('');
g = new FormGroup({'one': c, 'two': c2});
});
it('should set its own value', () => {
g.setValue({'one': 'one', 'two': 'two'});
expect(g.value).toEqual({'one': 'one', 'two': 'two'});
});
it('should set child values', () => {
g.setValue({'one': 'one', 'two': 'two'});
expect(c.value).toEqual('one');
expect(c2.value).toEqual('two');
});
it('should set child control values if disabled', () => {
c2.disable();
g.setValue({'one': 'one', 'two': 'two'});
expect(c2.value).toEqual('two');
expect(g.value).toEqual({'one': 'one'});
expect(g.getRawValue()).toEqual({'one': 'one', 'two': 'two'});
});
it('should set group value if group is disabled', () => {
g.disable();
g.setValue({'one': 'one', 'two': 'two'});
expect(c.value).toEqual('one');
expect(c2.value).toEqual('two');
expect(g.value).toEqual({'one': 'one', 'two': 'two'});
});
it('should set parent values', () => {
const form = new FormGroup({'parent': g});
g.setValue({'one': 'one', 'two': 'two'});
expect(form.value).toEqual({'parent': {'one': 'one', 'two': 'two'}});
});
it('should not update the parent when explicitly specified', () => {
const form = new FormGroup({'parent': g});
g.setValue({'one': 'one', 'two': 'two'}, {onlySelf: true});
expect(form.value).toEqual({parent: {'one': '', 'two': ''}});
});
it('should throw if fields are missing from supplied value (subset)', () => {
expect(() => g.setValue({
'one': 'one'
})).toThrowError(new RegExp(`Must supply a value for form control with name: 'two'`));
});
it('should throw if a value is provided for a missing control (superset)', () => {
expect(() => g.setValue({'one': 'one', 'two': 'two', 'three': 'three'}))
.toThrowError(new RegExp(`Cannot find form control with name: three`));
});
it('should throw if a value is not provided for a disabled control', () => {
c2.disable();
expect(() => g.setValue({
'one': 'one'
})).toThrowError(new RegExp(`Must supply a value for form control with name: 'two'`));
});
it('should throw if no controls are set yet', () => {
const empty = new FormGroup({});
expect(() => empty.setValue({
'one': 'one'
})).toThrowError(new RegExp(`no form controls registered with this group`));
});
describe('setValue() events', () => {
let form: FormGroup;
let logger: any[];
beforeEach(() => {
form = new FormGroup({'parent': g});
logger = [];
});
it('should emit one valueChange event per control', () => {
form.valueChanges.subscribe(() => logger.push('form'));
g.valueChanges.subscribe(() => logger.push('group'));
c.valueChanges.subscribe(() => logger.push('control1'));
c2.valueChanges.subscribe(() => logger.push('control2'));
g.setValue({'one': 'one', 'two': 'two'});
expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
});
it('should not fire an event when explicitly specified', fakeAsync(() => {
form.valueChanges.subscribe((value) => { throw 'Should not happen'; });
g.valueChanges.subscribe((value) => { throw 'Should not happen'; });
c.valueChanges.subscribe((value) => { throw 'Should not happen'; });
g.setValue({'one': 'one', 'two': 'two'}, {emitEvent: false});
tick();
}));
it('should emit one statusChange event per control', () => {
form.statusChanges.subscribe(() => logger.push('form'));
g.statusChanges.subscribe(() => logger.push('group'));
c.statusChanges.subscribe(() => logger.push('control1'));
c2.statusChanges.subscribe(() => logger.push('control2'));
g.setValue({'one': 'one', 'two': 'two'});
expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
});
});
});
describe('patchValue', () => {
let c: FormControl, c2: FormControl, g: FormGroup;
beforeEach(() => {
c = new FormControl('');
c2 = new FormControl('');
g = new FormGroup({'one': c, 'two': c2});
});
it('should set its own value', () => {
g.patchValue({'one': 'one', 'two': 'two'});
expect(g.value).toEqual({'one': 'one', 'two': 'two'});
});
it('should set child values', () => {
g.patchValue({'one': 'one', 'two': 'two'});
expect(c.value).toEqual('one');
expect(c2.value).toEqual('two');
});
it('should patch disabled control values', () => {
c2.disable();
g.patchValue({'one': 'one', 'two': 'two'});
expect(c2.value).toEqual('two');
expect(g.value).toEqual({'one': 'one'});
expect(g.getRawValue()).toEqual({'one': 'one', 'two': 'two'});
});
it('should patch disabled control groups', () => {
g.disable();
g.patchValue({'one': 'one', 'two': 'two'});
expect(c.value).toEqual('one');
expect(c2.value).toEqual('two');
expect(g.value).toEqual({'one': 'one', 'two': 'two'});
});
it('should set parent values', () => {
const form = new FormGroup({'parent': g});
g.patchValue({'one': 'one', 'two': 'two'});
expect(form.value).toEqual({'parent': {'one': 'one', 'two': 'two'}});
});
it('should not update the parent when explicitly specified', () => {
const form = new FormGroup({'parent': g});
g.patchValue({'one': 'one', 'two': 'two'}, {onlySelf: true});
expect(form.value).toEqual({parent: {'one': '', 'two': ''}});
});
it('should ignore fields that are missing from supplied value (subset)', () => {
g.patchValue({'one': 'one'});
expect(g.value).toEqual({'one': 'one', 'two': ''});
});
it('should not ignore fields that are null', () => {
g.patchValue({'one': null});
expect(g.value).toEqual({'one': null, 'two': ''});
});
it('should ignore any value provided for a missing control (superset)', () => {
g.patchValue({'three': 'three'});
expect(g.value).toEqual({'one': '', 'two': ''});
});
describe('patchValue() events', () => {
let form: FormGroup;
let logger: any[];
beforeEach(() => {
form = new FormGroup({'parent': g});
logger = [];
});
it('should emit one valueChange event per control', () => {
form.valueChanges.subscribe(() => logger.push('form'));
g.valueChanges.subscribe(() => logger.push('group'));
c.valueChanges.subscribe(() => logger.push('control1'));
c2.valueChanges.subscribe(() => logger.push('control2'));
g.patchValue({'one': 'one', 'two': 'two'});
expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
});
it('should not emit valueChange events for skipped controls', () => {
form.valueChanges.subscribe(() => logger.push('form'));
g.valueChanges.subscribe(() => logger.push('group'));
c.valueChanges.subscribe(() => logger.push('control1'));
c2.valueChanges.subscribe(() => logger.push('control2'));
g.patchValue({'one': 'one'});
expect(logger).toEqual(['control1', 'group', 'form']);
});
it('should not fire an event when explicitly specified', fakeAsync(() => {
form.valueChanges.subscribe((value) => { throw 'Should not happen'; });
g.valueChanges.subscribe((value) => { throw 'Should not happen'; });
c.valueChanges.subscribe((value) => { throw 'Should not happen'; });
g.patchValue({'one': 'one', 'two': 'two'}, {emitEvent: false});
tick();
}));
it('should emit one statusChange event per control', () => {
form.statusChanges.subscribe(() => logger.push('form'));
g.statusChanges.subscribe(() => logger.push('group'));
c.statusChanges.subscribe(() => logger.push('control1'));
c2.statusChanges.subscribe(() => logger.push('control2'));
g.patchValue({'one': 'one', 'two': 'two'});
expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
});
});
});
describe('reset()', () => {
let c: FormControl, c2: FormControl, g: FormGroup;
beforeEach(() => {
c = new FormControl('initial value');
c2 = new FormControl('');
g = new FormGroup({'one': c, 'two': c2});
});
it('should set its own value if value passed', () => {
g.setValue({'one': 'new value', 'two': 'new value'});
g.reset({'one': 'initial value', 'two': ''});
expect(g.value).toEqual({'one': 'initial value', 'two': ''});
});
it('should set its own value if boxed value passed', () => {
g.setValue({'one': 'new value', 'two': 'new value'});
g.reset({'one': {value: 'initial value', disabled: false}, 'two': ''});
expect(g.value).toEqual({'one': 'initial value', 'two': ''});
});
it('should clear its own value if no value passed', () => {
g.setValue({'one': 'new value', 'two': 'new value'});
g.reset();
expect(g.value).toEqual({'one': null, 'two': null});
});
it('should set the value of each of its child controls if value passed', () => {
g.setValue({'one': 'new value', 'two': 'new value'});
g.reset({'one': 'initial value', 'two': ''});
expect(c.value).toBe('initial value');
expect(c2.value).toBe('');
});
it('should clear the value of each of its child controls if no value passed', () => {
g.setValue({'one': 'new value', 'two': 'new value'});
g.reset();
expect(c.value).toBe(null);
expect(c2.value).toBe(null);
});
it('should set the value of its parent if value passed', () => {
const form = new FormGroup({'g': g});
g.setValue({'one': 'new value', 'two': 'new value'});
g.reset({'one': 'initial value', 'two': ''});
expect(form.value).toEqual({'g': {'one': 'initial value', 'two': ''}});
});
it('should clear the value of its parent if no value passed', () => {
const form = new FormGroup({'g': g});
g.setValue({'one': 'new value', 'two': 'new value'});
g.reset();
expect(form.value).toEqual({'g': {'one': null, 'two': null}});
});
it('should not update the parent when explicitly specified', () => {
const form = new FormGroup({'g': g});
g.reset({'one': 'new value', 'two': 'new value'}, {onlySelf: true});
expect(form.value).toEqual({g: {'one': 'initial value', 'two': ''}});
});
it('should mark itself as pristine', () => {
g.markAsDirty();
expect(g.pristine).toBe(false);
g.reset();
expect(g.pristine).toBe(true);
});
it('should mark all child controls as pristine', () => {
c.markAsDirty();
c2.markAsDirty();
expect(c.pristine).toBe(false);
expect(c2.pristine).toBe(false);
g.reset();
expect(c.pristine).toBe(true);
expect(c2.pristine).toBe(true);
});
it('should mark the parent as pristine if all siblings pristine', () => {
const c3 = new FormControl('');
const form = new FormGroup({'g': g, 'c3': c3});
g.markAsDirty();
expect(form.pristine).toBe(false);
g.reset();
expect(form.pristine).toBe(true);
});
it('should not mark the parent pristine if any dirty siblings', () => {
const c3 = new FormControl('');
const form = new FormGroup({'g': g, 'c3': c3});
g.markAsDirty();
c3.markAsDirty();
expect(form.pristine).toBe(false);
g.reset();
expect(form.pristine).toBe(false);
});
it('should mark itself as untouched', () => {
g.markAsTouched();
expect(g.untouched).toBe(false);
g.reset();
expect(g.untouched).toBe(true);
});
it('should mark all child controls as untouched', () => {
c.markAsTouched();
c2.markAsTouched();
expect(c.untouched).toBe(false);
expect(c2.untouched).toBe(false);
g.reset();
expect(c.untouched).toBe(true);
expect(c2.untouched).toBe(true);
});
it('should mark the parent untouched if all siblings untouched', () => {
const c3 = new FormControl('');
const form = new FormGroup({'g': g, 'c3': c3});
g.markAsTouched();
expect(form.untouched).toBe(false);
g.reset();
expect(form.untouched).toBe(true);
});
it('should not mark the parent untouched if any touched siblings', () => {
const c3 = new FormControl('');
const form = new FormGroup({'g': g, 'c3': c3});
g.markAsTouched();
c3.markAsTouched();
expect(form.untouched).toBe(false);
g.reset();
expect(form.untouched).toBe(false);
});
it('should retain previous disabled state', () => {
g.disable();
g.reset();
expect(g.disabled).toBe(true);
});
it('should set child disabled state if boxed value passed', () => {
g.disable();
g.reset({'one': {value: '', disabled: false}, 'two': ''});
expect(c.disabled).toBe(false);
expect(g.disabled).toBe(false);
});
describe('reset() events', () => {
let form: FormGroup, c3: FormControl, logger: any[];
beforeEach(() => {
c3 = new FormControl('');
form = new FormGroup({'g': g, 'c3': c3});
logger = [];
});
it('should emit one valueChange event per reset control', () => {
form.valueChanges.subscribe(() => logger.push('form'));
g.valueChanges.subscribe(() => logger.push('group'));
c.valueChanges.subscribe(() => logger.push('control1'));
c2.valueChanges.subscribe(() => logger.push('control2'));
c3.valueChanges.subscribe(() => logger.push('control3'));
g.reset();
expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
});
it('should not fire an event when explicitly specified', fakeAsync(() => {
form.valueChanges.subscribe((value) => { throw 'Should not happen'; });
g.valueChanges.subscribe((value) => { throw 'Should not happen'; });
c.valueChanges.subscribe((value) => { throw 'Should not happen'; });
g.reset({}, {emitEvent: false});
tick();
}));
it('should emit one statusChange event per reset control', () => {
form.statusChanges.subscribe(() => logger.push('form'));
g.statusChanges.subscribe(() => logger.push('group'));
c.statusChanges.subscribe(() => logger.push('control1'));
c2.statusChanges.subscribe(() => logger.push('control2'));
c3.statusChanges.subscribe(() => logger.push('control3'));
g.reset();
expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
});
it('should emit one statusChange event per reset control', () => {
form.statusChanges.subscribe(() => logger.push('form'));
g.statusChanges.subscribe(() => logger.push('group'));
c.statusChanges.subscribe(() => logger.push('control1'));
c2.statusChanges.subscribe(() => logger.push('control2'));
c3.statusChanges.subscribe(() => logger.push('control3'));
g.reset({'one': {value: '', disabled: true}});
expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
});
});
});
describe('contains', () => {
let group: FormGroup;
beforeEach(() => {
group = new FormGroup({
'required': new FormControl('requiredValue'),
'optional': new FormControl({value: 'disabled value', disabled: true})
});
});
it('should return false when the component is disabled',
() => { expect(group.contains('optional')).toEqual(false); });
it('should return false when there is no component with the given name',
() => { expect(group.contains('something else')).toEqual(false); });
it('should return true when the component is enabled', () => {
expect(group.contains('required')).toEqual(true);
group.enable('optional');
expect(group.contains('optional')).toEqual(true);
});
it('should support controls with dots in their name', () => {
expect(group.contains('some.name')).toBe(false);
group.addControl('some.name', new FormControl());
expect(group.contains('some.name')).toBe(true);
});
});
describe('statusChanges', () => {
let control: FormControl;
let group: FormGroup;
beforeEach(async(() => {
control = new FormControl('', asyncValidatorReturningObservable);
group = new FormGroup({'one': control});
}));
// TODO(kara): update these tests to use fake Async
it('should fire a statusChange if child has async validation change',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const loggedValues: string[] = [];
group.statusChanges.subscribe({
next: (status: string) => {
loggedValues.push(status);
if (loggedValues.length === 2) {
expect(loggedValues).toEqual(['PENDING', 'INVALID']);
}
async.done();
}
});
control.setValue('');
}));
});
describe('getError', () => {
it('should return the error when it is present', () => {
const c = new FormControl('', Validators.required);
const g = new FormGroup({'one': c});
expect(c.getError('required')).toEqual(true);
expect(g.getError('required', ['one'])).toEqual(true);
});
it('should return null otherwise', () => {
const c = new FormControl('not empty', Validators.required);
const g = new FormGroup({'one': c});
expect(c.getError('invalid')).toEqual(null);
expect(g.getError('required', ['one'])).toEqual(null);
expect(g.getError('required', ['invalid'])).toEqual(null);
});
});
describe('asyncValidator', () => {
it('should run the async validator', fakeAsync(() => {
const c = new FormControl('value');
const g = new FormGroup({'one': c}, null, asyncValidator('expected'));
expect(g.pending).toEqual(true);
tick(1);
expect(g.errors).toEqual({'async': true});
expect(g.pending).toEqual(false);
}));
it('should set the parent group\'s status to pending', fakeAsync(() => {
const c = new FormControl('value', null, asyncValidator('expected'));
const g = new FormGroup({'one': c});
expect(g.pending).toEqual(true);
tick(1);
expect(g.pending).toEqual(false);
}));
it('should run the parent group\'s async validator when children are pending',
fakeAsync(() => {
const c = new FormControl('value', null, asyncValidator('expected'));
const g = new FormGroup({'one': c}, null, asyncValidator('expected'));
tick(1);
expect(g.errors).toEqual({'async': true});
expect(g.get('one').errors).toEqual({'async': true});
}));
});
describe('disable() & enable()', () => {
it('should mark the group as disabled', () => {
const g = new FormGroup({'one': new FormControl(null)});
expect(g.disabled).toBe(false);
expect(g.valid).toBe(true);
g.disable();
expect(g.disabled).toBe(true);
expect(g.valid).toBe(false);
g.enable();
expect(g.disabled).toBe(false);
expect(g.valid).toBe(true);
});
it('should set the group status as disabled', () => {
const g = new FormGroup({'one': new FormControl(null)});
expect(g.status).toEqual('VALID');
g.disable();
expect(g.status).toEqual('DISABLED');
g.enable();
expect(g.status).toBe('VALID');
});
it('should mark children of the group as disabled', () => {
const c1 = new FormControl(null);
const c2 = new FormControl(null);
const g = new FormGroup({'one': c1, 'two': c2});
expect(c1.disabled).toBe(false);
expect(c2.disabled).toBe(false);
g.disable();
expect(c1.disabled).toBe(true);
expect(c2.disabled).toBe(true);
g.enable();
expect(c1.disabled).toBe(false);
expect(c2.disabled).toBe(false);
});
it('should ignore disabled controls in validation', () => {
const g = new FormGroup({
nested: new FormGroup({one: new FormControl(null, Validators.required)}),
two: new FormControl('two')
});
expect(g.valid).toBe(false);
g.get('nested').disable();
expect(g.valid).toBe(true);
g.get('nested').enable();
expect(g.valid).toBe(false);
});
it('should ignore disabled controls when serializing value', () => {
const g = new FormGroup(
{nested: new FormGroup({one: new FormControl('one')}), two: new FormControl('two')});
expect(g.value).toEqual({'nested': {'one': 'one'}, 'two': 'two'});
g.get('nested').disable();
expect(g.value).toEqual({'two': 'two'});
g.get('nested').enable();
expect(g.value).toEqual({'nested': {'one': 'one'}, 'two': 'two'});
});
it('should update its value when disabled with disabled children', () => {
const g = new FormGroup(
{nested: new FormGroup({one: new FormControl('one'), two: new FormControl('two')})});
g.get('nested.two').disable();
expect(g.value).toEqual({nested: {one: 'one'}});
g.get('nested').disable();
expect(g.value).toEqual({nested: {one: 'one', two: 'two'}});
g.get('nested').enable();
expect(g.value).toEqual({nested: {one: 'one', two: 'two'}});
});
it('should update its value when enabled with disabled children', () => {
const g = new FormGroup(
{nested: new FormGroup({one: new FormControl('one'), two: new FormControl('two')})});
g.get('nested.two').disable();
expect(g.value).toEqual({nested: {one: 'one'}});
g.get('nested').enable();
expect(g.value).toEqual({nested: {one: 'one', two: 'two'}});
});
it('should ignore disabled controls when determining dirtiness', () => {
const g = new FormGroup(
{nested: new FormGroup({one: new FormControl('one')}), two: new FormControl('two')});
g.get('nested.one').markAsDirty();
expect(g.dirty).toBe(true);
g.get('nested').disable();
expect(g.get('nested').dirty).toBe(true);
expect(g.dirty).toEqual(false);
g.get('nested').enable();
expect(g.dirty).toEqual(true);
});
it('should ignore disabled controls when determining touched state', () => {
const g = new FormGroup(
{nested: new FormGroup({one: new FormControl('one')}), two: new FormControl('two')});
g.get('nested.one').markAsTouched();
expect(g.touched).toBe(true);
g.get('nested').disable();
expect(g.get('nested').touched).toBe(true);
expect(g.touched).toEqual(false);
g.get('nested').enable();
expect(g.touched).toEqual(true);
});
it('should keep empty, disabled groups disabled when updating validity', () => {
const group = new FormGroup({});
expect(group.status).toEqual('VALID');
group.disable();
expect(group.status).toEqual('DISABLED');
group.updateValueAndValidity();
expect(group.status).toEqual('DISABLED');
group.addControl('one', new FormControl({value: '', disabled: true}));
expect(group.status).toEqual('DISABLED');
group.addControl('two', new FormControl());
expect(group.status).toEqual('VALID');
});
it('should re-enable empty, disabled groups', () => {
const group = new FormGroup({});
group.disable();
expect(group.status).toEqual('DISABLED');
group.enable();
expect(group.status).toEqual('VALID');
});
it('should not run validators on disabled controls', () => {
const validator = jasmine.createSpy('validator');
const g = new FormGroup({'one': new FormControl()}, validator);
expect(validator.calls.count()).toEqual(1);
g.disable();
expect(validator.calls.count()).toEqual(1);
g.setValue({one: 'value'});
expect(validator.calls.count()).toEqual(1);
g.enable();
expect(validator.calls.count()).toEqual(2);
});
describe('disabled errors', () => {
it('should clear out group errors when disabled', () => {
const g = new FormGroup({'one': new FormControl()}, () => ({'expected': true}));
expect(g.errors).toEqual({'expected': true});
g.disable();
expect(g.errors).toEqual(null);
g.enable();
expect(g.errors).toEqual({'expected': true});
});
it('should re-populate group errors when enabled from a child', () => {
const g = new FormGroup({'one': new FormControl()}, () => ({'expected': true}));
g.disable();
expect(g.errors).toEqual(null);
g.addControl('two', new FormControl());
expect(g.errors).toEqual({'expected': true});
});
it('should clear out async group errors when disabled', fakeAsync(() => {
const g = new FormGroup({'one': new FormControl()}, null, asyncValidator('expected'));
tick();
expect(g.errors).toEqual({'async': true});
g.disable();
expect(g.errors).toEqual(null);
g.enable();
tick();
expect(g.errors).toEqual({'async': true});
}));
it('should re-populate async group errors when enabled from a child', fakeAsync(() => {
const g = new FormGroup({'one': new FormControl()}, null, asyncValidator('expected'));
tick();
expect(g.errors).toEqual({'async': true});
g.disable();
expect(g.errors).toEqual(null);
g.addControl('two', new FormControl());
tick();
expect(g.errors).toEqual({'async': true});
}));
});
describe('disabled events', () => {
let logger: string[];
let c: FormControl;
let g: FormGroup;
let form: FormGroup;
beforeEach(() => {
logger = [];
c = new FormControl('', Validators.required);
g = new FormGroup({one: c});
form = new FormGroup({g: g});
});
it('should emit value change events in the right order', () => {
c.valueChanges.subscribe(() => logger.push('control'));
g.valueChanges.subscribe(() => logger.push('group'));
form.valueChanges.subscribe(() => logger.push('form'));
g.disable();
expect(logger).toEqual(['control', 'group', 'form']);
});
it('should emit status change events in the right order', () => {
c.statusChanges.subscribe(() => logger.push('control'));
g.statusChanges.subscribe(() => logger.push('group'));
form.statusChanges.subscribe(() => logger.push('form'));
g.disable();
expect(logger).toEqual(['control', 'group', 'form']);
});
});
});
describe('updateTreeValidity()', () => {
let c: FormControl, c2: FormControl, c3: FormControl;
let nested: FormGroup, form: FormGroup;
let logger: string[];
beforeEach(() => {
c = new FormControl('one');
c2 = new FormControl('two');
c3 = new FormControl('three');
nested = new FormGroup({one: c, two: c2});
form = new FormGroup({nested: nested, three: c3});
logger = [];
c.statusChanges.subscribe(() => logger.push('one'));
c2.statusChanges.subscribe(() => logger.push('two'));
c3.statusChanges.subscribe(() => logger.push('three'));
nested.statusChanges.subscribe(() => logger.push('nested'));
form.statusChanges.subscribe(() => logger.push('form'));
});
it('should update tree validity', () => {
form._updateTreeValidity();
expect(logger).toEqual(['one', 'two', 'nested', 'three', 'form']);
});
it('should not emit events when turned off', () => {
form._updateTreeValidity({emitEvent: false});
expect(logger).toEqual([]);
});
});
describe('setControl()', () => {
let c: FormControl;
let g: FormGroup;
beforeEach(() => {
c = new FormControl('one');
g = new FormGroup({one: c});
});
it('should replace existing control with new control', () => {
const c2 = new FormControl('new!', Validators.minLength(10));
g.setControl('one', c2);
expect(g.controls['one']).toEqual(c2);
expect(g.value).toEqual({one: 'new!'});
expect(g.valid).toBe(false);
});
it('should add control if control did not exist before', () => {
const c2 = new FormControl('new!', Validators.minLength(10));
g.setControl('two', c2);
expect(g.controls['two']).toEqual(c2);
expect(g.value).toEqual({one: 'one', two: 'new!'});
expect(g.valid).toBe(false);
});
it('should remove control if new control is null', () => {
g.setControl('one', null);
expect(g.controls['one']).not.toBeDefined();
expect(g.value).toEqual({});
});
it('should only emit value change event once', () => {
const logger: string[] = [];
const c2 = new FormControl('new!');
g.valueChanges.subscribe(() => logger.push('change!'));
g.setControl('one', c2);
expect(logger).toEqual(['change!']);
});
});
});
}
|
Java
|
// ==========================================================================
// Project: SproutCore Metal
// Copyright: ©2011 Strobe Inc. and contributors.
// License: Licensed under MIT license (see license.js)
// ==========================================================================
require('sproutcore-metal');
function isEnumerable(obj, keyName) {
var keys = [];
for(var key in obj) {
if (obj.hasOwnProperty(key)) keys.push(key);
}
return keys.indexOf(keyName)>=0;
}
module("SC.platform.defineProperty()");
test("defining a simple property", function() {
var obj = {};
SC.platform.defineProperty(obj, 'foo', {
enumerable: true,
writable: true,
value: 'FOO'
});
equals(obj.foo, 'FOO', 'should have added property');
obj.foo = "BAR";
equals(obj.foo, 'BAR', 'writable defined property should be writable');
equals(isEnumerable(obj, 'foo'), true, 'foo should be enumerable');
});
test('defining a read only property', function() {
var obj = {};
SC.platform.defineProperty(obj, 'foo', {
enumerable: true,
writable: false,
value: 'FOO'
});
equals(obj.foo, 'FOO', 'should have added property');
obj.foo = "BAR";
if (SC.platform.defineProperty.isSimulated) {
equals(obj.foo, 'BAR', 'simulated defineProperty should silently work');
} else {
equals(obj.foo, 'FOO', 'real defined property should not be writable');
}
});
test('defining a non enumerable property', function() {
var obj = {};
SC.platform.defineProperty(obj, 'foo', {
enumerable: false,
writable: true,
value: 'FOO'
});
if (SC.platform.defineProperty.isSimulated) {
equals(isEnumerable(obj, 'foo'), true, 'simulated defineProperty will leave properties enumerable');
} else {
equals(isEnumerable(obj, 'foo'), false, 'real defineProperty will make property not-enumerable');
}
});
test('defining a getter/setter', function() {
var obj = {}, getCnt = 0, setCnt = 0, v = 'FOO';
var desc = {
enumerable: true,
get: function() { getCnt++; return v; },
set: function(val) { setCnt++; v = val; }
};
if (SC.platform.hasPropertyAccessors) {
SC.platform.defineProperty(obj, 'foo', desc);
equals(obj.foo, 'FOO', 'should return getter');
equals(getCnt, 1, 'should have invoked getter');
obj.foo = 'BAR';
equals(obj.foo, 'BAR', 'setter should have worked');
equals(setCnt, 1, 'should have invoked setter');
} else {
raises(function() {
SC.platform.defineProperty(obj, 'foo', desc);
}, Error, 'should throw exception if getters/setters not supported');
}
});
test('defining getter/setter along with writable', function() {
var obj ={};
raises(function() {
SC.platform.defineProperty(obj, 'foo', {
enumerable: true,
get: function() {},
set: function() {},
writable: true
});
}, Error, 'defining writable and get/set should throw exception');
});
test('defining getter/setter along with value', function() {
var obj ={};
raises(function() {
SC.platform.defineProperty(obj, 'foo', {
enumerable: true,
get: function() {},
set: function() {},
value: 'FOO'
});
}, Error, 'defining value and get/set should throw exception');
});
|
Java
|
require 'rubygems'
require 'active_support'
require 'active_merchant'
class GatewaySupport #:nodoc:
ACTIONS = [:purchase, :authorize, :capture, :void, :credit, :recurring]
include ActiveMerchant::Billing
attr_reader :gateways
def initialize
Dir[File.expand_path(File.dirname(__FILE__) + '/../active_merchant/billing/gateways/*.rb')].each do |f|
filename = File.basename(f, '.rb')
gateway_name = filename + '_gateway'
begin
gateway_class = ('ActiveMerchant::Billing::' + gateway_name.camelize).constantize
rescue NameError
puts 'Could not load gateway ' + gateway_name.camelize + ' from ' + f + '.'
end
end
@gateways = Gateway.implementations.sort_by(&:name)
@gateways.delete(ActiveMerchant::Billing::BogusGateway)
end
def each_gateway
@gateways.each{|g| yield g }
end
def features
width = 15
print 'Name'.center(width + 20)
ACTIONS.each{|f| print "#{f.to_s.capitalize.center(width)}" }
puts
each_gateway do |g|
print "#{g.display_name.ljust(width + 20)}"
ACTIONS.each do |f|
print "#{(g.instance_methods.include?(f.to_s) ? "Y" : "N").center(width)}"
end
puts
end
end
def to_rdoc
each_gateway do |g|
puts "* {#{g.display_name}}[#{g.homepage_url}] - #{g.supported_countries.join(', ')}"
end
end
def to_textile
each_gateway do |g|
puts %/ * "#{g.display_name}":#{g.homepage_url} [#{g.supported_countries.join(', ')}]/
end
end
def to_markdown
each_gateway do |g|
puts %/* [#{g.display_name}](#{g.homepage_url}) - #{g.supported_countries.join(', ')}/
end
end
def to_s
each_gateway do |g|
puts "#{g.display_name} - #{g.homepage_url} [#{g.supported_countries.join(', ')}]"
end
end
end
|
Java
|
/*
* Copyright (c) 2011-2015 Håkan Edling
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
* http://github.com/piranhacms/piranha
*
*/
using System;
using System.Collections.Generic;
namespace Piranha.Extend
{
/// <summary>
/// Base class for easily defining a page type.
/// </summary>
public abstract class PageType : IPageType
{
/// <summary>
/// Gets the name.
/// </summary>
public virtual string Name { get; protected set; }
/// <summary>
/// Gets the optional description.
/// </summary>
public virtual string Description { get; protected set; }
/// <summary>
/// Gets the html preview.
/// </summary>
public virtual string Preview { get; protected set; }
/// <summary>
/// Gets the controller/viewtemplate depending on the current
/// application is using WebPages or Mvc.
/// </summary>
public virtual string Controller { get; protected set; }
/// <summary>
/// Gets if pages of the current type should be able to
/// override the controller.
/// </summary>
public virtual bool ShowController { get; protected set; }
/// <summary>
/// Gets the view. This is only relevant for Mvc applications.
/// </summary>
public virtual string View { get; protected set; }
/// <summary>
/// Gets if pages of the current type should be able to
/// override the controller.
/// </summary>
public virtual bool ShowView { get; protected set; }
/// <summary>
/// Gets/sets the optional permalink of a page this sould redirect to.
/// </summary>
public virtual string Redirect { get; protected set; }
/// <summary>
/// Gets/sets if the redirect can be overriden by the implementing page.
/// </summary>
public virtual bool ShowRedirect { get; protected set; }
/// <summary>
/// Gets the defíned properties.
/// </summary>
public virtual IList<string> Properties { get; protected set; }
/// <summary>
/// Gets the defined regions.
/// </summary>
public virtual IList<RegionType> Regions { get; protected set; }
public PageType() {
Properties = new List<string>();
Regions = new List<RegionType>();
Preview = "<table class=\"template\"><tr><td></td></tr></table>";
}
}
}
|
Java
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="GetNodeScriptsTest.cs" company="automotiveMastermind and contributors">
// © automotiveMastermind and contributors. Licensed under MIT. See LICENSE and CREDITS for details.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace AM.Condo.Tasks
{
using System.IO;
using Microsoft.Build.Utilities;
using Newtonsoft.Json;
using Xunit;
using AM.Condo.IO;
[Class(nameof(GetNodeMetadata))]
public class GetNodeScriptsTest
{
[Fact]
[Priority(2)]
[Purpose(PurposeType.Integration)]
public void Execute_WithValidProject_Succeeds()
{
using (var temp = new TemporaryPath())
{
// arrange
var project = new
{
name = "test",
version = "1.0.0",
description = "",
main = "index.js",
scripts = new
{
test = "echo this is a test script",
ci = "echo this is a ci script"
},
author = "automotiveMastermind",
license = "MIT"
};
var expected = new[] { "test", "ci" };
var path = temp.Combine("package.json");
using (var writer = File.CreateText(path))
{
var serializer = new JsonSerializer();
serializer.Serialize(writer, project);
writer.Flush();
}
var items = new[] { new TaskItem(path) };
var engine = MSBuildMocks.CreateEngine();
var instance = new GetNodeMetadata
{
Projects = items,
BuildEngine = engine
};
// act
var result = instance.Execute();
// assert
Assert.True(result);
}
}
}
}
|
Java
|
<?php
/* SonataAdminBundle:CRUD:base_list_flat_inner_row.html.twig */
class __TwigTemplate_16b98d4be50387198a258942bcac860cb5e7d142e913464f9538849439128cff extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
'row' => array($this, 'block_row'),
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 11
echo "
";
// line 12
if (($this->getAttribute($this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "list", array()), "has", array(0 => "batch"), "method") && !$this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : null), "request", array()), "isXmlHttpRequest", array()))) {
// line 13
echo " <td class=\"sonata-ba-list-field sonata-ba-list-field-batch\">
";
// line 14
echo $this->env->getExtension('sonata_admin')->renderListElement((isset($context["object"]) ? $context["object"] : null), $this->getAttribute($this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "list", array()), "batch", array(), "array"));
echo "
</td>
";
}
// line 17
echo "
<td class=\"sonata-ba-list-field sonata-ba-list-field-inline-fields\" colspan=\"";
// line 18
echo twig_escape_filter($this->env, (twig_length_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "list", array()), "elements", array())) - ($this->getAttribute($this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "list", array()), "has", array(0 => "_action"), "method") + $this->getAttribute($this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "list", array()), "has", array(0 => "batch"), "method"))), "html", null, true);
echo "\" objectId=\"";
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "id", array(0 => (isset($context["object"]) ? $context["object"] : null)), "method"), "html", null, true);
echo "\">
";
// line 19
$this->displayBlock('row', $context, $blocks);
// line 20
echo "</td>
";
// line 22
if (($this->getAttribute($this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "list", array()), "has", array(0 => "_action"), "method") && !$this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : null), "request", array()), "isXmlHttpRequest", array()))) {
// line 23
echo " <td class=\"sonata-ba-list-field sonata-ba-list-field-_action\" objectId=\"";
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "id", array(0 => (isset($context["object"]) ? $context["object"] : null)), "method"), "html", null, true);
echo "\">
";
// line 24
echo $this->env->getExtension('sonata_admin')->renderListElement((isset($context["object"]) ? $context["object"] : null), $this->getAttribute($this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "list", array()), "_action", array(), "array"));
echo "
</td>
";
}
}
// line 19
public function block_row($context, array $blocks = array())
{
}
public function getTemplateName()
{
return "SonataAdminBundle:CRUD:base_list_flat_inner_row.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 64 => 19, 56 => 24, 51 => 23, 49 => 22, 45 => 20, 43 => 19, 37 => 18, 34 => 17, 28 => 14, 25 => 13, 23 => 12, 20 => 11,);
}
}
|
Java
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Qt 4.8: tictactoeplugin.h Example File (designer/taskmenuextension/tictactoeplugin.h)</title>
<link rel="stylesheet" type="text/css" href="style/style.css" />
<script src="scripts/jquery.js" type="text/javascript"></script>
<script src="scripts/functions.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style/superfish.css" />
<link rel="stylesheet" type="text/css" href="style/narrow.css" />
<!--[if IE]>
<meta name="MSSmartTagsPreventParsing" content="true">
<meta http-equiv="imagetoolbar" content="no">
<![endif]-->
<!--[if lt IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie6.css">
<![endif]-->
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie7.css">
<![endif]-->
<!--[if IE 8]>
<link rel="stylesheet" type="text/css" href="style/style_ie8.css">
<![endif]-->
<script src="scripts/superfish.js" type="text/javascript"></script>
<script src="scripts/narrow.js" type="text/javascript"></script>
</head>
<body class="" onload="CheckEmptyAndLoadList();">
<div class="header" id="qtdocheader">
<div class="content">
<div id="nav-logo">
<a href="index.html">Home</a></div>
<a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a>
<div id="narrowsearch"></div>
<div id="nav-topright">
<ul>
<li class="nav-topright-home"><a href="http://qt.digia.com/">Qt HOME</a></li>
<li class="nav-topright-dev"><a href="http://qt-project.org/">DEV</a></li>
<li class="nav-topright-doc nav-topright-doc-active"><a href="http://qt-project.org/doc/">
DOC</a></li>
<li class="nav-topright-blog"><a href="http://blog.qt.digia.com/">BLOG</a></li>
</ul>
</div>
<div id="shortCut">
<ul>
<li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.8</a></span></li>
<li class="shortCut-topleft-active"><a href="http://qt-project.org/doc/">ALL VERSIONS </a></li>
</ul>
</div>
<ul class="sf-menu" id="narrowmenu">
<li><a href="#">API Lookup</a>
<ul>
<li><a href="classes.html">Class index</a></li>
<li><a href="functions.html">Function index</a></li>
<li><a href="modules.html">Modules</a></li>
<li><a href="namespaces.html">Namespaces</a></li>
<li><a href="qtglobal.html">Global Declarations</a></li>
<li><a href="qdeclarativeelements.html">QML elements</a></li>
</ul>
</li>
<li><a href="#">Qt Topics</a>
<ul>
<li><a href="qt-basic-concepts.html">Programming with Qt</a></li>
<li><a href="qtquick.html">Device UIs & Qt Quick</a></li>
<li><a href="qt-gui-concepts.html">UI Design with Qt</a></li>
<li><a href="supported-platforms.html">Supported Platforms</a></li>
<li><a href="technology-apis.html">Qt and Key Technologies</a></li>
<li><a href="best-practices.html">How-To's and Best Practices</a></li>
</ul>
</li>
<li><a href="#">Examples</a>
<ul>
<li><a href="all-examples.html">Examples</a></li>
<li><a href="tutorials.html">Tutorials</a></li>
<li><a href="demos.html">Demos</a></li>
<li><a href="qdeclarativeexamples.html">QML Examples</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div class="wrapper">
<div class="hd">
<span></span>
</div>
<div class="bd group">
<div class="sidebar">
<div class="searchlabel">
Search index:</div>
<div class="search" id="sidebarsearch">
<form id="qtdocsearch" action="" onsubmit="return false;">
<fieldset>
<input type="text" name="searchstring" id="pageType" value="" />
<div id="resultdialog">
<a href="#" id="resultclose">Close</a>
<p id="resultlinks" class="all"><a href="#" id="showallresults">All</a> | <a href="#" id="showapiresults">API</a> | <a href="#" id="showarticleresults">Articles</a> | <a href="#" id="showexampleresults">Examples</a></p>
<p id="searchcount" class="all"><span id="resultcount"></span><span id="apicount"></span><span id="articlecount"></span><span id="examplecount"></span> results:</p>
<ul id="resultlist" class="all">
</ul>
</div>
</fieldset>
</form>
</div>
<div class="box first bottombar" id="lookup">
<h2 title="API Lookup"><span></span>
API Lookup</h2>
<div id="list001" class="list">
<ul id="ul001" >
<li class="defaultLink"><a href="classes.html">Class index</a></li>
<li class="defaultLink"><a href="functions.html">Function index</a></li>
<li class="defaultLink"><a href="modules.html">Modules</a></li>
<li class="defaultLink"><a href="namespaces.html">Namespaces</a></li>
<li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li>
<li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li>
</ul>
</div>
</div>
<div class="box bottombar" id="topics">
<h2 title="Qt Topics"><span></span>
Qt Topics</h2>
<div id="list002" class="list">
<ul id="ul002" >
<li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li>
<li class="defaultLink"><a href="qtquick.html">Device UIs & Qt Quick</a></li>
<li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li>
<li class="defaultLink"><a href="supported-platforms.html">Supported Platforms</a></li>
<li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li>
<li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li>
</ul>
</div>
</div>
<div class="box" id="examples">
<h2 title="Examples"><span></span>
Examples</h2>
<div id="list003" class="list">
<ul id="ul003">
<li class="defaultLink"><a href="all-examples.html">Examples</a></li>
<li class="defaultLink"><a href="tutorials.html">Tutorials</a></li>
<li class="defaultLink"><a href="demos.html">Demos</a></li>
<li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li>
</ul>
</div>
</div>
</div>
<div class="wrap">
<div class="toolbar">
<div class="breadcrumb toolblock">
<ul>
<li class="first"><a href="index.html">Home</a></li>
<!-- Breadcrumbs go here -->
</ul>
</div>
<div class="toolbuttons toolblock">
<ul>
<li id="smallA" class="t_button">A</li>
<li id="medA" class="t_button active">A</li>
<li id="bigA" class="t_button">A</li>
<li id="print" class="t_button"><a href="javascript:this.print();">
<span>Print</span></a></li>
</ul>
</div>
</div>
<div class="content mainContent">
<h1 class="title">tictactoeplugin.h Example File</h1>
<span class="small-subtitle">designer/taskmenuextension/tictactoeplugin.h</span>
<!-- $$$designer/taskmenuextension/tictactoeplugin.h-description -->
<div class="descr"> <a name="details"></a>
<pre class="cpp"> <span class="comment">/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "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 Digia Plc and its Subsidiary(-ies) nor the names
** of its contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/</span>
<span class="preprocessor">#ifndef TICTACTOEPLUGIN_H</span>
<span class="preprocessor">#define TICTACTOEPLUGIN_H</span>
<span class="preprocessor">#include <QDesignerCustomWidgetInterface></span>
<span class="keyword">class</span> <span class="type"><a href="qicon.html">QIcon</a></span>;
<span class="keyword">class</span> <span class="type"><a href="qwidget.html">QWidget</a></span>;
<span class="keyword">class</span> TicTacToePlugin : <span class="keyword">public</span> <span class="type"><a href="qobject.html">QObject</a></span><span class="operator">,</span> <span class="keyword">public</span> <span class="type"><a href="qdesignercustomwidgetinterface.html">QDesignerCustomWidgetInterface</a></span>
{
Q_OBJECT
Q_INTERFACES(<span class="type"><a href="qdesignercustomwidgetinterface.html">QDesignerCustomWidgetInterface</a></span>)
<span class="keyword">public</span>:
TicTacToePlugin(<span class="type"><a href="qobject.html">QObject</a></span> <span class="operator">*</span>parent <span class="operator">=</span> <span class="number">0</span>);
<span class="type"><a href="qstring.html">QString</a></span> name() <span class="keyword">const</span>;
<span class="type"><a href="qstring.html">QString</a></span> group() <span class="keyword">const</span>;
<span class="type"><a href="qstring.html">QString</a></span> toolTip() <span class="keyword">const</span>;
<span class="type"><a href="qstring.html">QString</a></span> whatsThis() <span class="keyword">const</span>;
<span class="type"><a href="qstring.html">QString</a></span> includeFile() <span class="keyword">const</span>;
<span class="type"><a href="qicon.html">QIcon</a></span> icon() <span class="keyword">const</span>;
<span class="type">bool</span> isContainer() <span class="keyword">const</span>;
<span class="type"><a href="qwidget.html">QWidget</a></span> <span class="operator">*</span>createWidget(<span class="type"><a href="qwidget.html">QWidget</a></span> <span class="operator">*</span>parent);
<span class="type">bool</span> isInitialized() <span class="keyword">const</span>;
<span class="type">void</span> initialize(<span class="type"><a href="qdesignerformeditorinterface.html">QDesignerFormEditorInterface</a></span> <span class="operator">*</span>formEditor);
<span class="type"><a href="qstring.html">QString</a></span> domXml() <span class="keyword">const</span>;
<span class="keyword">private</span>:
<span class="type">bool</span> initialized;
};
<span class="preprocessor">#endif</span></pre>
</div>
<!-- @@@designer/taskmenuextension/tictactoeplugin.h -->
</div>
</div>
</div>
<div class="ft">
<span></span>
</div>
</div>
<div class="footer">
<p>
<acronym title="Copyright">©</acronym> 2013 Digia Plc and/or its
subsidiaries. Documentation contributions included herein are the copyrights of
their respective owners.</p>
<br />
<p>
The documentation provided herein is licensed under the terms of the
<a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation
License version 1.3</a> as published by the Free Software Foundation.</p>
<p>
Documentation sources may be obtained from <a href="http://www.qt-project.org">
www.qt-project.org</a>.</p>
<br />
<p>
Digia, Qt and their respective logos are trademarks of Digia Plc
in Finland and/or other countries worldwide. All other trademarks are property
of their respective owners. <a title="Privacy Policy"
href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p>
</div>
<script src="scripts/functions.js" type="text/javascript"></script>
</body>
</html>
|
Java
|
var Promise = require('ember-cli/lib/ext/promise');
module.exports = {
normalizeEntityName: function() {},
afterInstall: function() {
var addonContext = this;
return this.addBowerPackageToProject('jquery-ui', '1.10.1')
.then(function() {
return addonContext.addBowerPackageToProject('jquery-mousewheel', '~3.1.4');
})
.then(function() {
return addonContext.addBowerPackageToProject('taras/antiscroll', '92505e0e0d0ef9383630df509883bce558215b22');
});
}
};
|
Java
|
import time
import random
from random import randint
# from library import Trigger, Axis
# from library import PS4
from library import Joystick
import RPi.GPIO as GPIO # remove!!!
from emotions import angry, happy, confused
# from pysabertooth import Sabertooth
# from smc import SMC
from library import LEDDisplay
from library import factory
from library import reset_all_hw
# Leg Motor Speed Global
global_LegMotor = 70
# # Happy Emotion
# def happy(leds, servos, mc, audio):
# print("4")
# print("Happy")
#
# # Dome Motor Initialization
# # mc = SMC(dome_motor_port, 115200)
# # mc.init()
#
# # Spins Motor
# # mc.init()
# mc.speed(3200)
#
# # LED Matrix Green
# # breadboard has mono
# # R2 has bi-color leds
# # mono:0 bi:1
# # led_type = 0
# # leds = [0]*5
# # leds[1] = LEDDisplay(0x70, led_type)
# # leds[2] = LEDDisplay(0x71, led_type)
# # leds[3] = LEDDisplay(0x72, led_type)
# # leds[4] = LEDDisplay(0x73, led_type)
#
# for x in [0, 1, 2, 3, 4, 5, 6, 7]:
# for y in [0, 1, 2, 3, 4, 5, 6, 7]:
# for i in range(1, 5):
# leds[i].set(x, y, 1)
#
# for i in range(1, 5):
# leds[i].write()
#
# # Servo Wave
# # s0.angle = 0
# # time.sleep(0.2)
# # s1.angle = 0
# # time.sleep(0.2)
# # s2.angle = 0
# # time.sleep(0.2)
# # s3.angle = 0
# # time.sleep(0.2)
# # s4.angle = 0
# # time.sleep(0.5)
# # s4.angle = 130
# # time.sleep(0.2)
# # s3.angle = 130
# # time.sleep(0.2)
# # s2.angle = 130
# # time.sleep(0.2)
# # s1.angle = 130
# # time.sleep(0.2)
# # s0.angle = 130
#
# for a in [0, 130]:
# for i in range(4):
# servos[i].angle = a
# time.sleep(0.2)
# time.sleep(0.5)
#
# time.sleep(1.5)
# mc.stop()
# time.sleep(1.5)
# for i in range(1, 5):
# leds[i].clear()
#
#
# # Confused Emotion
# def confused(leds, servos, mc, audio):
# print("5")
# print("Confused")
# # LED Matrix Yellow
# # leds = [0]*5
# # leds[1] = LEDDisplay(0x70, 1)
# # leds[2] = LEDDisplay(0x71, 1)
# # leds[3] = LEDDisplay(0x72, 1)
# # leds[4] = LEDDisplay(0x73, 1)
#
# for x in [0, 1, 2, 3, 4, 5, 6, 7]:
# for y in [0, 1, 2, 3, 4, 5, 6, 7]:
# for i in range(1, 5):
# leds[i].set(x, y, 3)
# for i in range(1, 5):
# leds[i].write()
# time.sleep(3)
# for i in range(1, 5):
# leds[i].clear()
#
#
# # Angry Emotion
# def angry(leds, servos, mc, audio):
# print("6")
# print("Angry")
# # LED Matrix Red
# # leds = [0]*5
# # leds[1] = LEDDisplay(0x70, 1)
# # leds[2] = LEDDisplay(0x71, 1)
# # leds[3] = LEDDisplay(0x72, 1)
# # leds[4] = LEDDisplay(0x73, 1)
#
# for x in [0, 1, 2, 3, 4, 5, 6, 7]:
# for y in [0, 1, 2, 3, 4, 5, 6, 7]:
# for i in range(1, 5):
# leds[i].set(x, y, 2)
#
# for i in range(1, 5):
# leds[i].write()
#
# # Plays Imperial Theme Sound
# audio.sound('imperial')
#
# # Servo Open and Close
# # s0.angle = 0
# # s1.angle = 0
# # s2.angle = 0
# # s3.angle = 0
# # s4.angle = 0
# # time.sleep(1)
# # s4.angle = 130
# # s3.angle = 130
# # s2.angle = 130
# # s1.angle = 130
# # s0.angle = 130
#
# for a in [0, 130]:
# for i in range(5):
# servos[i].angle = a
# time.sleep(1)
#
# time.sleep(3)
# for i in range(1, 5):
# leds[i].clear()
#######################################
# original remote
#######################################
# # Remote Mode
# def remote(remoteflag, namespace):
# print("Remote")
#
# # create objects
# (leds, dome, legs, servos, Flash) = factory(['leds', 'dome', 'legs', 'servos', 'flashlight'])
#
# # initalize everything
# dome.init()
# dome.speed(0)
#
# legs.drive(1, 0)
# legs.drive(2, 0)
#
# for s in servos:
# s.angle = 0
# time.sleep(0.25)
#
# # what is this???
# GPIO.setmode(GPIO.BCM)
# GPIO.setwarnings(False)
# GPIO.setup(26, GPIO.OUT)
#
# # Joystick Initialization
# js = Joystick()
#
# # get audio
# audio = namespace.audio
#
# # Flash = FlashlightPWM(15)
# # Flash = namespace.flashlight
#
# while(remoteflag.is_set()):
# try:
# # Button Initialization
# ps4 = js.get()
# btnSquare = ps4.buttons[0]
# btnTriangle = ps4.buttons[1]
# btnCircle = ps4.buttons[2]
# btnX = ps4.buttons[3]
# btnLeftStickLeftRight = ps4.leftStick.y
# btnLeftStickUpDown = ps4.leftStick.x
# btnRightStickLeftRight = ps4.rightStick.y
# btnRightStickUpDown = ps4.rightStick.x
# Left1 = ps4.shoulder[0]
# Right1 = ps4.shoulder[1]
# Left2 = ps4.triggers.x
# Right2 = ps4.triggers.y
# hat = ps4.hat
#
# # print("PRINT")
#
# # Button Controls
# if hat == 1:
# # Happy Emotion
# print("Arrow Up Pressed")
# happy(leds, servos, dome, audio) # namespace.emotions['happy'](leds, servos, mc, audio)
# if hat == 8:
# # Confused Emotion
# print("Arrow Left Pressed")
# confused(leds, servos, dome, audio)
# if hat == 2:
# # Angry Emotion
# print("Arrow Right Pressed")
# angry(leds, servos, dome, audio)
# if hat == 4:
# print("Arrow Down Pressed")
# if btnSquare == 1:
# # word = random_char(2)
# audio.speak_random(2)
# time.sleep(0.5)
# if btnTriangle == 1:
# # FlashLight ON
# GPIO.output(26, GPIO.HIGH)
# Flash.pwm.set_pwm(15, 0, 130)
# if btnCircle == 1:
# # FlashLight OFF
# GPIO.output(26, GPIO.LOW)
# Flash.pwm.set_pwm(15, 0, 0)
# if btnX == 1:
# for x in [0, 1, 2, 3, 4, 5, 6, 7]:
# for y in [0, 1, 2, 3, 4, 5, 6, 7]:
# if x == randint(0, 8) or y == randint(0, 8):
# for i in range(1, 5):
# leds[i].set(x, y, randint(0, 4))
# else:
# for i in range(1, 5):
# leds[i].set(x, y, 4)
# for i in range(1, 5):
# leds[i].write()
# time.sleep(0.1)
# for i in range(1, 5):
# leds[i].clear()
# if Left1 == 1:
# # Dome Motor Forward
# dome.speed(3200)
# time.sleep(2)
# dome.speed(0)
# if Right1 == 1:
# # Dome Motor Backward
# dome.speed(-3200)
# time.sleep(2)
# dome.speed(0)
# # if Left1 == 0 or Right1 == 0:
# # # Dome Motor Stop
# # dome.speed(0)
# # if Left2 > 1:
# # # Servo Open
# # s0.angle = 0
# # s1.angle = 0
# # s2.angle = 0
# # s3.angle = 0
# # s4.angle = 0
# # Flash.pwm.set_pwm(15, 0, 3000)
# #
# # if Right2 > 1:
# # # Servo Close
# # s0.angle = 130
# # s1.angle = 130
# # s2.angle = 130
# # s3.angle = 130
# # s4.angle = 130
# # Flash.pwm.set_pwm(15, 0, 130)
# if Left2 > 1:
# for s in servos:
# s.angle = 0
# time.sleep(0.25)
# Flash.pwm.set_pwm(15, 0, 300)
# if Right2 > 1:
# for s in servos:
# s.angle = 130
# time.sleep(0.25)
# Flash.pwm.set_pwm(15, 0, 130)
# if btnLeftStickLeftRight < 0.3 and btnLeftStickLeftRight > -0.3:
# legs.drive(1, 0)
# if btnRightStickUpDown < 0.3 and btnRightStickUpDown > -0.3:
# legs.drive(2, 0)
# if btnRightStickUpDown >= 0.3:
# # Right and Left Motor Forward
# legs.drive(1, btnRightStickUpDown*global_LegMotor)
# legs.drive(2, btnRightStickUpDown*-global_LegMotor)
# if btnRightStickUpDown <= -0.3:
# # Right and Left Motor Backward
# legs.drive(1, btnRightStickUpDown*global_LegMotor)
# legs.drive(2, btnRightStickUpDown*-global_LegMotor)
# if btnLeftStickLeftRight <= 0.3:
# # Turn Left
# legs.drive(1, btnLeftStickLeftRight*(-global_LegMotor))
# legs.drive(2, btnLeftStickLeftRight*-global_LegMotor)
# if btnLeftStickLeftRight >= -0.3:
# # Turn Right
# legs.drive(1, btnLeftStickLeftRight*(-global_LegMotor))
# legs.drive(2, btnLeftStickLeftRight*-global_LegMotor)
#
# except KeyboardInterrupt:
# print('js exiting ...')
# return
# return
def remote_func(hw, ns):
print("Remote")
dome = hw['dome']
dome.speed(0)
legs = hw['legs']
legs.drive(1, 0)
legs.drive(2, 0)
flashlight = hw['flashlight']
audio = hw['audio']
audio.speak('start')
while ns.current_state == 3:
print('remote ...')
spd = random.randint(0, 40)
legs.drive(1, spd)
legs.drive(2, spd)
dome.speed(spd)
time.sleep(0.5)
legs.drive(1, 0)
legs.drive(2, 0)
dome.speed(0)
time.sleep(0.1)
return
###### real loop here #####
# Joystick Initialization
js = Joystick()
while ns.current_state == 3:
try:
# Button Initialization
ps4 = js.get()
btnSquare = ps4.buttons[0]
btnTriangle = ps4.buttons[1]
btnCircle = ps4.buttons[2]
btnX = ps4.buttons[3]
btnLeftStickLeftRight = ps4.leftStick.y
btnLeftStickUpDown = ps4.leftStick.x
btnRightStickLeftRight = ps4.rightStick.y
btnRightStickUpDown = ps4.rightStick.x
Left1 = ps4.shoulder[0]
Right1 = ps4.shoulder[1]
Left2 = ps4.triggers.x
Right2 = ps4.triggers.y
hat = ps4.hat
# print("PRINT")
# Button Controls
if hat == 1:
# Happy Emotion
print("Arrow Up Pressed")
happy(leds, servos, dome, audio) # namespace.emotions['happy'](leds, servos, mc, audio)
if hat == 8:
# Confused Emotion
print("Arrow Left Pressed")
confused(leds, servos, dome, audio)
if hat == 2:
# Angry Emotion
print("Arrow Right Pressed")
angry(leds, servos, dome, audio)
if hat == 4:
print("Arrow Down Pressed")
if btnSquare == 1:
# word = random_char(2)
audio.speak_random(2)
time.sleep(0.5)
if btnTriangle == 1:
# FlashLight ON
GPIO.output(26, GPIO.HIGH)
Flash.pwm.set_pwm(15, 0, 130)
if btnCircle == 1:
# FlashLight OFF
GPIO.output(26, GPIO.LOW)
Flash.pwm.set_pwm(15, 0, 0)
if btnX == 1:
for x in [0, 1, 2, 3, 4, 5, 6, 7]:
for y in [0, 1, 2, 3, 4, 5, 6, 7]:
if x == randint(0, 8) or y == randint(0, 8):
for i in range(1, 5):
leds[i].set(x, y, randint(0, 4))
else:
for i in range(1, 5):
leds[i].set(x, y, 4)
for i in range(1, 5):
leds[i].write()
time.sleep(0.1)
for i in range(1, 5):
leds[i].clear()
if Left1 == 1:
# Dome Motor Forward
dome.speed(3200)
time.sleep(2)
dome.speed(0)
if Right1 == 1:
# Dome Motor Backward
dome.speed(-3200)
time.sleep(2)
dome.speed(0)
# if Left1 == 0 or Right1 == 0:
# # Dome Motor Stop
# dome.speed(0)
# if Left2 > 1:
# # Servo Open
# s0.angle = 0
# s1.angle = 0
# s2.angle = 0
# s3.angle = 0
# s4.angle = 0
# Flash.pwm.set_pwm(15, 0, 3000)
#
# if Right2 > 1:
# # Servo Close
# s0.angle = 130
# s1.angle = 130
# s2.angle = 130
# s3.angle = 130
# s4.angle = 130
# Flash.pwm.set_pwm(15, 0, 130)
if Left2 > 1:
for s in servos:
s.angle = 0
time.sleep(0.25)
Flash.pwm.set_pwm(15, 0, 300)
if Right2 > 1:
for s in servos:
s.angle = 130
time.sleep(0.25)
Flash.pwm.set_pwm(15, 0, 130)
if btnLeftStickLeftRight < 0.3 and btnLeftStickLeftRight > -0.3:
legs.drive(1, 0)
if btnRightStickUpDown < 0.3 and btnRightStickUpDown > -0.3:
legs.drive(2, 0)
if btnRightStickUpDown >= 0.3:
# Right and Left Motor Forward
legs.drive(1, btnRightStickUpDown*global_LegMotor)
legs.drive(2, btnRightStickUpDown*-global_LegMotor)
if btnRightStickUpDown <= -0.3:
# Right and Left Motor Backward
legs.drive(1, btnRightStickUpDown*global_LegMotor)
legs.drive(2, btnRightStickUpDown*-global_LegMotor)
if btnLeftStickLeftRight <= 0.3:
# Turn Left
legs.drive(1, btnLeftStickLeftRight*(-global_LegMotor))
legs.drive(2, btnLeftStickLeftRight*-global_LegMotor)
if btnLeftStickLeftRight >= -0.3:
# Turn Right
legs.drive(1, btnLeftStickLeftRight*(-global_LegMotor))
legs.drive(2, btnLeftStickLeftRight*-global_LegMotor)
except KeyboardInterrupt:
print('js exiting ...')
return
# exiting, reset all hw
reset_all_hw(hw)
return
|
Java
|
##
# This code was generated by
# \ / _ _ _| _ _
# | (_)\/(_)(_|\/| |(/_ v1.0.0
# / /
#
# frozen_string_literal: true
module Twilio
module REST
class Api < Domain
class V2010 < Version
class AccountContext < InstanceContext
class ApplicationList < ListResource
##
# Initialize the ApplicationList
# @param [Version] version Version that contains the resource
# @param [String] account_sid The SID of the
# {Account}[https://www.twilio.com/docs/iam/api/account] that created the
# Application resource.
# @return [ApplicationList] ApplicationList
def initialize(version, account_sid: nil)
super(version)
# Path Solution
@solution = {account_sid: account_sid}
@uri = "/Accounts/#{@solution[:account_sid]}/Applications.json"
end
##
# Create the ApplicationInstance
# @param [String] api_version The API version to use to start a new TwiML session.
# Can be: `2010-04-01` or `2008-08-01`. The default value is the account's default
# API version.
# @param [String] voice_url The URL we should call when the phone number assigned
# to this application receives a call.
# @param [String] voice_method The HTTP method we should use to call `voice_url`.
# Can be: `GET` or `POST`.
# @param [String] voice_fallback_url The URL that we should call when an error
# occurs retrieving or executing the TwiML requested by `url`.
# @param [String] voice_fallback_method The HTTP method we should use to call
# `voice_fallback_url`. Can be: `GET` or `POST`.
# @param [String] status_callback The URL we should call using the
# `status_callback_method` to send status information to your application.
# @param [String] status_callback_method The HTTP method we should use to call
# `status_callback`. Can be: `GET` or `POST`.
# @param [Boolean] voice_caller_id_lookup Whether we should look up the caller's
# caller-ID name from the CNAM database (additional charges apply). Can be: `true`
# or `false`.
# @param [String] sms_url The URL we should call when the phone number receives an
# incoming SMS message.
# @param [String] sms_method The HTTP method we should use to call `sms_url`. Can
# be: `GET` or `POST`.
# @param [String] sms_fallback_url The URL that we should call when an error
# occurs while retrieving or executing the TwiML from `sms_url`.
# @param [String] sms_fallback_method The HTTP method we should use to call
# `sms_fallback_url`. Can be: `GET` or `POST`.
# @param [String] sms_status_callback The URL we should call using a POST method
# to send status information about SMS messages sent by the application.
# @param [String] message_status_callback The URL we should call using a POST
# method to send message status information to your application.
# @param [String] friendly_name A descriptive string that you create to describe
# the new application. It can be up to 64 characters long.
# @return [ApplicationInstance] Created ApplicationInstance
def create(api_version: :unset, voice_url: :unset, voice_method: :unset, voice_fallback_url: :unset, voice_fallback_method: :unset, status_callback: :unset, status_callback_method: :unset, voice_caller_id_lookup: :unset, sms_url: :unset, sms_method: :unset, sms_fallback_url: :unset, sms_fallback_method: :unset, sms_status_callback: :unset, message_status_callback: :unset, friendly_name: :unset)
data = Twilio::Values.of({
'ApiVersion' => api_version,
'VoiceUrl' => voice_url,
'VoiceMethod' => voice_method,
'VoiceFallbackUrl' => voice_fallback_url,
'VoiceFallbackMethod' => voice_fallback_method,
'StatusCallback' => status_callback,
'StatusCallbackMethod' => status_callback_method,
'VoiceCallerIdLookup' => voice_caller_id_lookup,
'SmsUrl' => sms_url,
'SmsMethod' => sms_method,
'SmsFallbackUrl' => sms_fallback_url,
'SmsFallbackMethod' => sms_fallback_method,
'SmsStatusCallback' => sms_status_callback,
'MessageStatusCallback' => message_status_callback,
'FriendlyName' => friendly_name,
})
payload = @version.create('POST', @uri, data: data)
ApplicationInstance.new(@version, payload, account_sid: @solution[:account_sid], )
end
##
# Lists ApplicationInstance records from the API as a list.
# Unlike stream(), this operation is eager and will load `limit` records into
# memory before returning.
# @param [String] friendly_name The string that identifies the Application
# resources to read.
# @param [Integer] limit Upper limit for the number of records to return. stream()
# guarantees to never return more than limit. Default is no limit
# @param [Integer] page_size Number of records to fetch per request, when
# not set will use the default value of 50 records. If no page_size is defined
# but a limit is defined, stream() will attempt to read the limit with the most
# efficient page size, i.e. min(limit, 1000)
# @return [Array] Array of up to limit results
def list(friendly_name: :unset, limit: nil, page_size: nil)
self.stream(friendly_name: friendly_name, limit: limit, page_size: page_size).entries
end
##
# Streams ApplicationInstance records from the API as an Enumerable.
# This operation lazily loads records as efficiently as possible until the limit
# is reached.
# @param [String] friendly_name The string that identifies the Application
# resources to read.
# @param [Integer] limit Upper limit for the number of records to return. stream()
# guarantees to never return more than limit. Default is no limit.
# @param [Integer] page_size Number of records to fetch per request, when
# not set will use the default value of 50 records. If no page_size is defined
# but a limit is defined, stream() will attempt to read the limit with the most
# efficient page size, i.e. min(limit, 1000)
# @return [Enumerable] Enumerable that will yield up to limit results
def stream(friendly_name: :unset, limit: nil, page_size: nil)
limits = @version.read_limits(limit, page_size)
page = self.page(friendly_name: friendly_name, page_size: limits[:page_size], )
@version.stream(page, limit: limits[:limit], page_limit: limits[:page_limit])
end
##
# When passed a block, yields ApplicationInstance records from the API.
# This operation lazily loads records as efficiently as possible until the limit
# is reached.
def each
limits = @version.read_limits
page = self.page(page_size: limits[:page_size], )
@version.stream(page,
limit: limits[:limit],
page_limit: limits[:page_limit]).each {|x| yield x}
end
##
# Retrieve a single page of ApplicationInstance records from the API.
# Request is executed immediately.
# @param [String] friendly_name The string that identifies the Application
# resources to read.
# @param [String] page_token PageToken provided by the API
# @param [Integer] page_number Page Number, this value is simply for client state
# @param [Integer] page_size Number of records to return, defaults to 50
# @return [Page] Page of ApplicationInstance
def page(friendly_name: :unset, page_token: :unset, page_number: :unset, page_size: :unset)
params = Twilio::Values.of({
'FriendlyName' => friendly_name,
'PageToken' => page_token,
'Page' => page_number,
'PageSize' => page_size,
})
response = @version.page('GET', @uri, params: params)
ApplicationPage.new(@version, response, @solution)
end
##
# Retrieve a single page of ApplicationInstance records from the API.
# Request is executed immediately.
# @param [String] target_url API-generated URL for the requested results page
# @return [Page] Page of ApplicationInstance
def get_page(target_url)
response = @version.domain.request(
'GET',
target_url
)
ApplicationPage.new(@version, response, @solution)
end
##
# Provide a user friendly representation
def to_s
'#<Twilio.Api.V2010.ApplicationList>'
end
end
class ApplicationPage < Page
##
# Initialize the ApplicationPage
# @param [Version] version Version that contains the resource
# @param [Response] response Response from the API
# @param [Hash] solution Path solution for the resource
# @return [ApplicationPage] ApplicationPage
def initialize(version, response, solution)
super(version, response)
# Path Solution
@solution = solution
end
##
# Build an instance of ApplicationInstance
# @param [Hash] payload Payload response from the API
# @return [ApplicationInstance] ApplicationInstance
def get_instance(payload)
ApplicationInstance.new(@version, payload, account_sid: @solution[:account_sid], )
end
##
# Provide a user friendly representation
def to_s
'<Twilio.Api.V2010.ApplicationPage>'
end
end
class ApplicationContext < InstanceContext
##
# Initialize the ApplicationContext
# @param [Version] version Version that contains the resource
# @param [String] account_sid The SID of the
# {Account}[https://www.twilio.com/docs/iam/api/account] that created the
# Application resource to fetch.
# @param [String] sid The Twilio-provided string that uniquely identifies the
# Application resource to fetch.
# @return [ApplicationContext] ApplicationContext
def initialize(version, account_sid, sid)
super(version)
# Path Solution
@solution = {account_sid: account_sid, sid: sid, }
@uri = "/Accounts/#{@solution[:account_sid]}/Applications/#{@solution[:sid]}.json"
end
##
# Delete the ApplicationInstance
# @return [Boolean] true if delete succeeds, false otherwise
def delete
@version.delete('DELETE', @uri)
end
##
# Fetch the ApplicationInstance
# @return [ApplicationInstance] Fetched ApplicationInstance
def fetch
payload = @version.fetch('GET', @uri)
ApplicationInstance.new(
@version,
payload,
account_sid: @solution[:account_sid],
sid: @solution[:sid],
)
end
##
# Update the ApplicationInstance
# @param [String] friendly_name A descriptive string that you create to describe
# the resource. It can be up to 64 characters long.
# @param [String] api_version The API version to use to start a new TwiML session.
# Can be: `2010-04-01` or `2008-08-01`. The default value is your account's
# default API version.
# @param [String] voice_url The URL we should call when the phone number assigned
# to this application receives a call.
# @param [String] voice_method The HTTP method we should use to call `voice_url`.
# Can be: `GET` or `POST`.
# @param [String] voice_fallback_url The URL that we should call when an error
# occurs retrieving or executing the TwiML requested by `url`.
# @param [String] voice_fallback_method The HTTP method we should use to call
# `voice_fallback_url`. Can be: `GET` or `POST`.
# @param [String] status_callback The URL we should call using the
# `status_callback_method` to send status information to your application.
# @param [String] status_callback_method The HTTP method we should use to call
# `status_callback`. Can be: `GET` or `POST`.
# @param [Boolean] voice_caller_id_lookup Whether we should look up the caller's
# caller-ID name from the CNAM database (additional charges apply). Can be: `true`
# or `false`.
# @param [String] sms_url The URL we should call when the phone number receives an
# incoming SMS message.
# @param [String] sms_method The HTTP method we should use to call `sms_url`. Can
# be: `GET` or `POST`.
# @param [String] sms_fallback_url The URL that we should call when an error
# occurs while retrieving or executing the TwiML from `sms_url`.
# @param [String] sms_fallback_method The HTTP method we should use to call
# `sms_fallback_url`. Can be: `GET` or `POST`.
# @param [String] sms_status_callback Same as message_status_callback: The URL we
# should call using a POST method to send status information about SMS messages
# sent by the application. Deprecated, included for backwards compatibility.
# @param [String] message_status_callback The URL we should call using a POST
# method to send message status information to your application.
# @return [ApplicationInstance] Updated ApplicationInstance
def update(friendly_name: :unset, api_version: :unset, voice_url: :unset, voice_method: :unset, voice_fallback_url: :unset, voice_fallback_method: :unset, status_callback: :unset, status_callback_method: :unset, voice_caller_id_lookup: :unset, sms_url: :unset, sms_method: :unset, sms_fallback_url: :unset, sms_fallback_method: :unset, sms_status_callback: :unset, message_status_callback: :unset)
data = Twilio::Values.of({
'FriendlyName' => friendly_name,
'ApiVersion' => api_version,
'VoiceUrl' => voice_url,
'VoiceMethod' => voice_method,
'VoiceFallbackUrl' => voice_fallback_url,
'VoiceFallbackMethod' => voice_fallback_method,
'StatusCallback' => status_callback,
'StatusCallbackMethod' => status_callback_method,
'VoiceCallerIdLookup' => voice_caller_id_lookup,
'SmsUrl' => sms_url,
'SmsMethod' => sms_method,
'SmsFallbackUrl' => sms_fallback_url,
'SmsFallbackMethod' => sms_fallback_method,
'SmsStatusCallback' => sms_status_callback,
'MessageStatusCallback' => message_status_callback,
})
payload = @version.update('POST', @uri, data: data)
ApplicationInstance.new(
@version,
payload,
account_sid: @solution[:account_sid],
sid: @solution[:sid],
)
end
##
# Provide a user friendly representation
def to_s
context = @solution.map {|k, v| "#{k}: #{v}"}.join(',')
"#<Twilio.Api.V2010.ApplicationContext #{context}>"
end
##
# Provide a detailed, user friendly representation
def inspect
context = @solution.map {|k, v| "#{k}: #{v}"}.join(',')
"#<Twilio.Api.V2010.ApplicationContext #{context}>"
end
end
class ApplicationInstance < InstanceResource
##
# Initialize the ApplicationInstance
# @param [Version] version Version that contains the resource
# @param [Hash] payload payload that contains response from Twilio
# @param [String] account_sid The SID of the
# {Account}[https://www.twilio.com/docs/iam/api/account] that created the
# Application resource.
# @param [String] sid The Twilio-provided string that uniquely identifies the
# Application resource to fetch.
# @return [ApplicationInstance] ApplicationInstance
def initialize(version, payload, account_sid: nil, sid: nil)
super(version)
# Marshaled Properties
@properties = {
'account_sid' => payload['account_sid'],
'api_version' => payload['api_version'],
'date_created' => Twilio.deserialize_rfc2822(payload['date_created']),
'date_updated' => Twilio.deserialize_rfc2822(payload['date_updated']),
'friendly_name' => payload['friendly_name'],
'message_status_callback' => payload['message_status_callback'],
'sid' => payload['sid'],
'sms_fallback_method' => payload['sms_fallback_method'],
'sms_fallback_url' => payload['sms_fallback_url'],
'sms_method' => payload['sms_method'],
'sms_status_callback' => payload['sms_status_callback'],
'sms_url' => payload['sms_url'],
'status_callback' => payload['status_callback'],
'status_callback_method' => payload['status_callback_method'],
'uri' => payload['uri'],
'voice_caller_id_lookup' => payload['voice_caller_id_lookup'],
'voice_fallback_method' => payload['voice_fallback_method'],
'voice_fallback_url' => payload['voice_fallback_url'],
'voice_method' => payload['voice_method'],
'voice_url' => payload['voice_url'],
}
# Context
@instance_context = nil
@params = {'account_sid' => account_sid, 'sid' => sid || @properties['sid'], }
end
##
# Generate an instance context for the instance, the context is capable of
# performing various actions. All instance actions are proxied to the context
# @return [ApplicationContext] ApplicationContext for this ApplicationInstance
def context
unless @instance_context
@instance_context = ApplicationContext.new(@version, @params['account_sid'], @params['sid'], )
end
@instance_context
end
##
# @return [String] The SID of the Account that created the resource
def account_sid
@properties['account_sid']
end
##
# @return [String] The API version used to start a new TwiML session
def api_version
@properties['api_version']
end
##
# @return [Time] The RFC 2822 date and time in GMT that the resource was created
def date_created
@properties['date_created']
end
##
# @return [Time] The RFC 2822 date and time in GMT that the resource was last updated
def date_updated
@properties['date_updated']
end
##
# @return [String] The string that you assigned to describe the resource
def friendly_name
@properties['friendly_name']
end
##
# @return [String] The URL to send message status information to your application
def message_status_callback
@properties['message_status_callback']
end
##
# @return [String] The unique string that identifies the resource
def sid
@properties['sid']
end
##
# @return [String] The HTTP method used with sms_fallback_url
def sms_fallback_method
@properties['sms_fallback_method']
end
##
# @return [String] The URL that we call when an error occurs while retrieving or executing the TwiML
def sms_fallback_url
@properties['sms_fallback_url']
end
##
# @return [String] The HTTP method to use with sms_url
def sms_method
@properties['sms_method']
end
##
# @return [String] The URL to send status information to your application
def sms_status_callback
@properties['sms_status_callback']
end
##
# @return [String] The URL we call when the phone number receives an incoming SMS message
def sms_url
@properties['sms_url']
end
##
# @return [String] The URL to send status information to your application
def status_callback
@properties['status_callback']
end
##
# @return [String] The HTTP method we use to call status_callback
def status_callback_method
@properties['status_callback_method']
end
##
# @return [String] The URI of the resource, relative to `https://api.twilio.com`
def uri
@properties['uri']
end
##
# @return [Boolean] Whether to lookup the caller's name
def voice_caller_id_lookup
@properties['voice_caller_id_lookup']
end
##
# @return [String] The HTTP method used with voice_fallback_url
def voice_fallback_method
@properties['voice_fallback_method']
end
##
# @return [String] The URL we call when a TwiML error occurs
def voice_fallback_url
@properties['voice_fallback_url']
end
##
# @return [String] The HTTP method used with the voice_url
def voice_method
@properties['voice_method']
end
##
# @return [String] The URL we call when the phone number receives a call
def voice_url
@properties['voice_url']
end
##
# Delete the ApplicationInstance
# @return [Boolean] true if delete succeeds, false otherwise
def delete
context.delete
end
##
# Fetch the ApplicationInstance
# @return [ApplicationInstance] Fetched ApplicationInstance
def fetch
context.fetch
end
##
# Update the ApplicationInstance
# @param [String] friendly_name A descriptive string that you create to describe
# the resource. It can be up to 64 characters long.
# @param [String] api_version The API version to use to start a new TwiML session.
# Can be: `2010-04-01` or `2008-08-01`. The default value is your account's
# default API version.
# @param [String] voice_url The URL we should call when the phone number assigned
# to this application receives a call.
# @param [String] voice_method The HTTP method we should use to call `voice_url`.
# Can be: `GET` or `POST`.
# @param [String] voice_fallback_url The URL that we should call when an error
# occurs retrieving or executing the TwiML requested by `url`.
# @param [String] voice_fallback_method The HTTP method we should use to call
# `voice_fallback_url`. Can be: `GET` or `POST`.
# @param [String] status_callback The URL we should call using the
# `status_callback_method` to send status information to your application.
# @param [String] status_callback_method The HTTP method we should use to call
# `status_callback`. Can be: `GET` or `POST`.
# @param [Boolean] voice_caller_id_lookup Whether we should look up the caller's
# caller-ID name from the CNAM database (additional charges apply). Can be: `true`
# or `false`.
# @param [String] sms_url The URL we should call when the phone number receives an
# incoming SMS message.
# @param [String] sms_method The HTTP method we should use to call `sms_url`. Can
# be: `GET` or `POST`.
# @param [String] sms_fallback_url The URL that we should call when an error
# occurs while retrieving or executing the TwiML from `sms_url`.
# @param [String] sms_fallback_method The HTTP method we should use to call
# `sms_fallback_url`. Can be: `GET` or `POST`.
# @param [String] sms_status_callback Same as message_status_callback: The URL we
# should call using a POST method to send status information about SMS messages
# sent by the application. Deprecated, included for backwards compatibility.
# @param [String] message_status_callback The URL we should call using a POST
# method to send message status information to your application.
# @return [ApplicationInstance] Updated ApplicationInstance
def update(friendly_name: :unset, api_version: :unset, voice_url: :unset, voice_method: :unset, voice_fallback_url: :unset, voice_fallback_method: :unset, status_callback: :unset, status_callback_method: :unset, voice_caller_id_lookup: :unset, sms_url: :unset, sms_method: :unset, sms_fallback_url: :unset, sms_fallback_method: :unset, sms_status_callback: :unset, message_status_callback: :unset)
context.update(
friendly_name: friendly_name,
api_version: api_version,
voice_url: voice_url,
voice_method: voice_method,
voice_fallback_url: voice_fallback_url,
voice_fallback_method: voice_fallback_method,
status_callback: status_callback,
status_callback_method: status_callback_method,
voice_caller_id_lookup: voice_caller_id_lookup,
sms_url: sms_url,
sms_method: sms_method,
sms_fallback_url: sms_fallback_url,
sms_fallback_method: sms_fallback_method,
sms_status_callback: sms_status_callback,
message_status_callback: message_status_callback,
)
end
##
# Provide a user friendly representation
def to_s
values = @params.map{|k, v| "#{k}: #{v}"}.join(" ")
"<Twilio.Api.V2010.ApplicationInstance #{values}>"
end
##
# Provide a detailed, user friendly representation
def inspect
values = @properties.map{|k, v| "#{k}: #{v}"}.join(" ")
"<Twilio.Api.V2010.ApplicationInstance #{values}>"
end
end
end
end
end
end
end
|
Java
|
<?php
namespace Omnipay\Braintree\Message;
/**
* Find Customer Request
*
* @method CustomerResponse send()
*/
class FindCustomerRequest extends AbstractRequest
{
public function getData()
{
return $this->getCustomerData();
}
/**
* Send the request with specified data
*
* @param mixed $data The data to send
* @return CustomerResponse
*/
public function sendData($data)
{
$response = $this->braintree->customer()->find($this->getCustomerId());
return $this->response = new CustomerResponse($this, $response);
}
}
|
Java
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# pywim documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another
# directory, add these directories to sys.path here. If the directory is
# relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# Get the project root dir, which is the parent dir of this
cwd = os.getcwd()
project_root = os.path.dirname(cwd)
# Insert the project root dir as the first element in the PYTHONPATH.
# This lets us ensure that the source package is imported, and that its
# version is used.
sys.path.insert(0, project_root)
import pywim
# -- General configuration ---------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'PyWIM'
copyright = u"2016, Ivan Ogasawara"
# The version info for the project you're documenting, acts as replacement
# for |version| and |release|, also used in various other places throughout
# the built documents.
#
# The short X.Y version.
version = pywim.__version__
# The full version, including alpha/beta/rc tags.
release = pywim.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to
# some non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built
# documents.
#keep_warnings = False
# -- Options for HTML output -------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a
# theme further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as
# html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the
# top of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon
# of the docs. This file should be a Windows icon file (.ico) being
# 16x16 or 32x32 pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets)
# here, relative to this directory. They are copied after the builtin
# static files, so a file named "default.css" will overwrite the builtin
# "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names
# to template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer.
# Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer.
# Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages
# will contain a <link> tag referring to it. The value of this option
# must be the base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'pywimdoc'
# -- Options for LaTeX output ------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto/manual]).
latex_documents = [
('index', 'pywim.tex',
u'PyWIM Documentation',
u'Ivan Ogasawara', 'manual'),
]
# The name of an image file (relative to this directory) to place at
# the top of the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings
# are parts, not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'pywim',
u'PyWIM Documentation',
[u'Ivan Ogasawara'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ----------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'pywim',
u'PyWIM Documentation',
u'Ivan Ogasawara',
'pywim',
'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.