code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
package com.funnycat.popularmovies.connectivity; import android.net.Uri; import android.util.Log; import com.funnycat.popularmovies.BuildConfig; import com.funnycat.popularmovies.domain.commands.Command; import com.funnycat.popularmovies.domain.models.Review; import com.google.gson.Gson; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Created by daniel on 18/01/2017. */ public class Reviews_Request implements Command<List<Review>> { private static String TAG = "Reviews_Request"; private static String BASE_URL = "https://api.themoviedb.org/3/movie/"; private static String END_URL = "reviews"; private String mUrl; public Reviews_Request(int movieId){ mUrl = buildUrl(movieId); Log.d(TAG, "URL: " + mUrl); } private String buildUrl(int movieId){ Uri uri = Uri.parse(BASE_URL).buildUpon() .appendPath(String.valueOf(movieId)) .appendPath(END_URL) .appendQueryParameter("api_key", BuildConfig.MOVIES_API_KEY) .build(); return uri.toString(); } @Override public List<Review> execute() { Request request = new Request.Builder() .url(mUrl) .build(); try { OkHttpClient client = new OkHttpClient(); Response response = client.newCall(request).execute(); if(response.isSuccessful()){ String body = response.body().string(); JSONObject jsonBody = new JSONObject(body); JSONArray resultArray = new JSONArray(jsonBody.getString("results")); Gson gson = new Gson(); List<Review> resultList = new ArrayList<>(); for(int i=0; i<resultArray.length(); i++){ resultList.add(gson.fromJson(resultArray.getString(i), Review.class)); } return resultList; } } catch (Exception e) { e.printStackTrace(); return null; } return null; } }
danielgf3/PopularMovies_Udacity
app/src/main/java/com/funnycat/popularmovies/connectivity/Reviews_Request.java
Java
gpl-3.0
2,244
using System; namespace Hyper.Db { public interface IDbScriptProvider { void ExecuteAllScripts(string dbSchemaName, Action<string> executeDelegate); } }
jheitz1117/Hyper
Hyper.Db/IDbScriptProvider.cs
C#
gpl-3.0
177
<?php /* Substance - Content Management System and application framework. * Copyright (C) 2015 Kevin Rogers * * Substance is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Substance is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Substance. If not, see <http://www.gnu.org/licenses/>. */ namespace Substance\Core\Database\SQL\TableReferences; use Substance\Core\Database\SQL\Query; use Substance\Core\Database\SQL\TableReference; /** * An abstract table reference, for easily building concrete table references. */ abstract class AbstractTableReference implements TableReference { }
or1can/substance
application/src/Substance/Core/Database/SQL/TableReferences/AbstractTableReference.php
PHP
gpl-3.0
1,054
//===--- DeclCXX.cpp - C++ Declaration AST Node Implementation ------------===// // // 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 C++ related Decl classes. // //===----------------------------------------------------------------------===// #include "clang/AST/DeclCXX.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTLambda.h" #include "clang/AST/ASTMutationListener.h" #include "clang/AST/CXXInheritance.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/TypeLoc.h" #include "clang/Basic/IdentifierTable.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallPtrSet.h" using namespace clang; //===----------------------------------------------------------------------===// // Decl Allocation/Deallocation Method Implementations //===----------------------------------------------------------------------===// void AccessSpecDecl::anchor() { } AccessSpecDecl *AccessSpecDecl::CreateDeserialized(ASTContext &C, unsigned ID) { return new (C, ID) AccessSpecDecl(EmptyShell()); } void LazyASTUnresolvedSet::getFromExternalSource(ASTContext &C) const { ExternalASTSource *Source = C.getExternalSource(); assert(Impl.Decls.isLazy() && "getFromExternalSource for non-lazy set"); assert(Source && "getFromExternalSource with no external source"); for (ASTUnresolvedSet::iterator I = Impl.begin(); I != Impl.end(); ++I) I.setDecl(cast<NamedDecl>(Source->GetExternalDecl( reinterpret_cast<uintptr_t>(I.getDecl()) >> 2))); Impl.Decls.setLazy(false); } CXXRecordDecl::DefinitionData::DefinitionData(CXXRecordDecl *D) : UserDeclaredConstructor(false), UserDeclaredSpecialMembers(0), Aggregate(true), PlainOldData(true), Empty(true), Polymorphic(false), Abstract(false), IsStandardLayout(true), HasNoNonEmptyBases(true), HasPrivateFields(false), HasProtectedFields(false), HasPublicFields(false), HasMutableFields(false), HasVariantMembers(false), HasOnlyCMembers(true), HasInClassInitializer(false), HasUninitializedReferenceMember(false), NeedOverloadResolutionForMoveConstructor(false), NeedOverloadResolutionForMoveAssignment(false), NeedOverloadResolutionForDestructor(false), DefaultedMoveConstructorIsDeleted(false), DefaultedMoveAssignmentIsDeleted(false), DefaultedDestructorIsDeleted(false), HasTrivialSpecialMembers(SMF_All), DeclaredNonTrivialSpecialMembers(0), HasIrrelevantDestructor(true), HasConstexprNonCopyMoveConstructor(false), DefaultedDefaultConstructorIsConstexpr(true), HasConstexprDefaultConstructor(false), HasNonLiteralTypeFieldsOrBases(false), ComputedVisibleConversions(false), UserProvidedDefaultConstructor(false), DeclaredSpecialMembers(0), ImplicitCopyConstructorHasConstParam(true), ImplicitCopyAssignmentHasConstParam(true), HasDeclaredCopyConstructorWithConstParam(false), HasDeclaredCopyAssignmentWithConstParam(false), IsLambda(false), IsParsingBaseSpecifiers(false), NumBases(0), NumVBases(0), Bases(), VBases(), Definition(D), FirstFriend() { } CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getBasesSlowCase() const { return Bases.get(Definition->getASTContext().getExternalSource()); } CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getVBasesSlowCase() const { return VBases.get(Definition->getASTContext().getExternalSource()); } CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl) : RecordDecl(K, TK, C, DC, StartLoc, IdLoc, Id, PrevDecl), DefinitionData(PrevDecl ? PrevDecl->DefinitionData : DefinitionDataPtr(this)), TemplateOrInstantiation() {} CXXRecordDecl *CXXRecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl* PrevDecl, bool DelayTypeCreation) { CXXRecordDecl *R = new (C, DC) CXXRecordDecl(CXXRecord, TK, C, DC, StartLoc, IdLoc, Id, PrevDecl); R->MayHaveOutOfDateDef = C.getLangOpts().Modules; // FIXME: DelayTypeCreation seems like such a hack if (!DelayTypeCreation) C.getTypeDeclType(R, PrevDecl); return R; } CXXRecordDecl * CXXRecordDecl::CreateLambda(const ASTContext &C, DeclContext *DC, TypeSourceInfo *Info, SourceLocation Loc, bool Dependent, bool IsGeneric, LambdaCaptureDefault CaptureDefault) { CXXRecordDecl *R = new (C, DC) CXXRecordDecl(CXXRecord, TTK_Class, C, DC, Loc, Loc, nullptr, nullptr); R->IsBeingDefined = true; R->DefinitionData = new (C) struct LambdaDefinitionData(R, Info, Dependent, IsGeneric, CaptureDefault); R->MayHaveOutOfDateDef = false; R->setImplicit(true); C.getTypeDeclType(R, /*PrevDecl=*/nullptr); return R; } CXXRecordDecl * CXXRecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) { CXXRecordDecl *R = new (C, ID) CXXRecordDecl( CXXRecord, TTK_Struct, C, nullptr, SourceLocation(), SourceLocation(), nullptr, nullptr); R->MayHaveOutOfDateDef = false; return R; } void CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases, unsigned NumBases) { ASTContext &C = getASTContext(); if (!data().Bases.isOffset() && data().NumBases > 0) C.Deallocate(data().getBases()); if (NumBases) { // C++ [dcl.init.aggr]p1: // An aggregate is [...] a class with [...] no base classes [...]. data().Aggregate = false; // C++ [class]p4: // A POD-struct is an aggregate class... data().PlainOldData = false; } // The set of seen virtual base types. llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes; // The virtual bases of this class. SmallVector<const CXXBaseSpecifier *, 8> VBases; data().Bases = new(C) CXXBaseSpecifier [NumBases]; data().NumBases = NumBases; for (unsigned i = 0; i < NumBases; ++i) { data().getBases()[i] = *Bases[i]; // Keep track of inherited vbases for this base class. const CXXBaseSpecifier *Base = Bases[i]; QualType BaseType = Base->getType(); // Skip dependent types; we can't do any checking on them now. if (BaseType->isDependentType()) continue; CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl()); // A class with a non-empty base class is not empty. // FIXME: Standard ref? if (!BaseClassDecl->isEmpty()) { if (!data().Empty) { // C++0x [class]p7: // A standard-layout class is a class that: // [...] // -- either has no non-static data members in the most derived // class and at most one base class with non-static data members, // or has no base classes with non-static data members, and // If this is the second non-empty base, then neither of these two // clauses can be true. data().IsStandardLayout = false; } data().Empty = false; data().HasNoNonEmptyBases = false; } // C++ [class.virtual]p1: // A class that declares or inherits a virtual function is called a // polymorphic class. if (BaseClassDecl->isPolymorphic()) data().Polymorphic = true; // C++0x [class]p7: // A standard-layout class is a class that: [...] // -- has no non-standard-layout base classes if (!BaseClassDecl->isStandardLayout()) data().IsStandardLayout = false; // Record if this base is the first non-literal field or base. if (!hasNonLiteralTypeFieldsOrBases() && !BaseType->isLiteralType(C)) data().HasNonLiteralTypeFieldsOrBases = true; // Now go through all virtual bases of this base and add them. for (const auto &VBase : BaseClassDecl->vbases()) { // Add this base if it's not already in the list. if (SeenVBaseTypes.insert(C.getCanonicalType(VBase.getType()))) { VBases.push_back(&VBase); // C++11 [class.copy]p8: // The implicitly-declared copy constructor for a class X will have // the form 'X::X(const X&)' if each [...] virtual base class B of X // has a copy constructor whose first parameter is of type // 'const B&' or 'const volatile B&' [...] if (CXXRecordDecl *VBaseDecl = VBase.getType()->getAsCXXRecordDecl()) if (!VBaseDecl->hasCopyConstructorWithConstParam()) data().ImplicitCopyConstructorHasConstParam = false; } } if (Base->isVirtual()) { // Add this base if it's not already in the list. if (SeenVBaseTypes.insert(C.getCanonicalType(BaseType))) VBases.push_back(Base); // C++0x [meta.unary.prop] is_empty: // T is a class type, but not a union type, with ... no virtual base // classes data().Empty = false; // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: // A [default constructor, copy/move constructor, or copy/move assignment // operator for a class X] is trivial [...] if: // -- class X has [...] no virtual base classes data().HasTrivialSpecialMembers &= SMF_Destructor; // C++0x [class]p7: // A standard-layout class is a class that: [...] // -- has [...] no virtual base classes data().IsStandardLayout = false; // C++11 [dcl.constexpr]p4: // In the definition of a constexpr constructor [...] // -- the class shall not have any virtual base classes data().DefaultedDefaultConstructorIsConstexpr = false; } else { // C++ [class.ctor]p5: // A default constructor is trivial [...] if: // -- all the direct base classes of its class have trivial default // constructors. if (!BaseClassDecl->hasTrivialDefaultConstructor()) data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor; // C++0x [class.copy]p13: // A copy/move constructor for class X is trivial if [...] // [...] // -- the constructor selected to copy/move each direct base class // subobject is trivial, and if (!BaseClassDecl->hasTrivialCopyConstructor()) data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor; // If the base class doesn't have a simple move constructor, we'll eagerly // declare it and perform overload resolution to determine which function // it actually calls. If it does have a simple move constructor, this // check is correct. if (!BaseClassDecl->hasTrivialMoveConstructor()) data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor; // C++0x [class.copy]p27: // A copy/move assignment operator for class X is trivial if [...] // [...] // -- the assignment operator selected to copy/move each direct base // class subobject is trivial, and if (!BaseClassDecl->hasTrivialCopyAssignment()) data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment; // If the base class doesn't have a simple move assignment, we'll eagerly // declare it and perform overload resolution to determine which function // it actually calls. If it does have a simple move assignment, this // check is correct. if (!BaseClassDecl->hasTrivialMoveAssignment()) data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment; // C++11 [class.ctor]p6: // If that user-written default constructor would satisfy the // requirements of a constexpr constructor, the implicitly-defined // default constructor is constexpr. if (!BaseClassDecl->hasConstexprDefaultConstructor()) data().DefaultedDefaultConstructorIsConstexpr = false; } // C++ [class.ctor]p3: // A destructor is trivial if all the direct base classes of its class // have trivial destructors. if (!BaseClassDecl->hasTrivialDestructor()) data().HasTrivialSpecialMembers &= ~SMF_Destructor; if (!BaseClassDecl->hasIrrelevantDestructor()) data().HasIrrelevantDestructor = false; // C++11 [class.copy]p18: // The implicitly-declared copy assignment oeprator for a class X will // have the form 'X& X::operator=(const X&)' if each direct base class B // of X has a copy assignment operator whose parameter is of type 'const // B&', 'const volatile B&', or 'B' [...] if (!BaseClassDecl->hasCopyAssignmentWithConstParam()) data().ImplicitCopyAssignmentHasConstParam = false; // C++11 [class.copy]p8: // The implicitly-declared copy constructor for a class X will have // the form 'X::X(const X&)' if each direct [...] base class B of X // has a copy constructor whose first parameter is of type // 'const B&' or 'const volatile B&' [...] if (!BaseClassDecl->hasCopyConstructorWithConstParam()) data().ImplicitCopyConstructorHasConstParam = false; // A class has an Objective-C object member if... or any of its bases // has an Objective-C object member. if (BaseClassDecl->hasObjectMember()) setHasObjectMember(true); if (BaseClassDecl->hasVolatileMember()) setHasVolatileMember(true); // Keep track of the presence of mutable fields. if (BaseClassDecl->hasMutableFields()) data().HasMutableFields = true; if (BaseClassDecl->hasUninitializedReferenceMember()) data().HasUninitializedReferenceMember = true; addedClassSubobject(BaseClassDecl); } if (VBases.empty()) { data().IsParsingBaseSpecifiers = false; return; } // Create base specifier for any direct or indirect virtual bases. data().VBases = new (C) CXXBaseSpecifier[VBases.size()]; data().NumVBases = VBases.size(); for (int I = 0, E = VBases.size(); I != E; ++I) { QualType Type = VBases[I]->getType(); if (!Type->isDependentType()) addedClassSubobject(Type->getAsCXXRecordDecl()); data().getVBases()[I] = *VBases[I]; } data().IsParsingBaseSpecifiers = false; } void CXXRecordDecl::addedClassSubobject(CXXRecordDecl *Subobj) { // C++11 [class.copy]p11: // A defaulted copy/move constructor for a class X is defined as // deleted if X has: // -- a direct or virtual base class B that cannot be copied/moved [...] // -- a non-static data member of class type M (or array thereof) // that cannot be copied or moved [...] if (!Subobj->hasSimpleMoveConstructor()) data().NeedOverloadResolutionForMoveConstructor = true; // C++11 [class.copy]p23: // A defaulted copy/move assignment operator for a class X is defined as // deleted if X has: // -- a direct or virtual base class B that cannot be copied/moved [...] // -- a non-static data member of class type M (or array thereof) // that cannot be copied or moved [...] if (!Subobj->hasSimpleMoveAssignment()) data().NeedOverloadResolutionForMoveAssignment = true; // C++11 [class.ctor]p5, C++11 [class.copy]p11, C++11 [class.dtor]p5: // A defaulted [ctor or dtor] for a class X is defined as // deleted if X has: // -- any direct or virtual base class [...] has a type with a destructor // that is deleted or inaccessible from the defaulted [ctor or dtor]. // -- any non-static data member has a type with a destructor // that is deleted or inaccessible from the defaulted [ctor or dtor]. if (!Subobj->hasSimpleDestructor()) { data().NeedOverloadResolutionForMoveConstructor = true; data().NeedOverloadResolutionForDestructor = true; } } /// Callback function for CXXRecordDecl::forallBases that acknowledges /// that it saw a base class. static bool SawBase(const CXXRecordDecl *, void *) { return true; } bool CXXRecordDecl::hasAnyDependentBases() const { if (!isDependentContext()) return false; return !forallBases(SawBase, nullptr); } bool CXXRecordDecl::isTriviallyCopyable() const { // C++0x [class]p5: // A trivially copyable class is a class that: // -- has no non-trivial copy constructors, if (hasNonTrivialCopyConstructor()) return false; // -- has no non-trivial move constructors, if (hasNonTrivialMoveConstructor()) return false; // -- has no non-trivial copy assignment operators, if (hasNonTrivialCopyAssignment()) return false; // -- has no non-trivial move assignment operators, and if (hasNonTrivialMoveAssignment()) return false; // -- has a trivial destructor. if (!hasTrivialDestructor()) return false; return true; } void CXXRecordDecl::markedVirtualFunctionPure() { // C++ [class.abstract]p2: // A class is abstract if it has at least one pure virtual function. data().Abstract = true; } void CXXRecordDecl::addedMember(Decl *D) { if (!D->isImplicit() && !isa<FieldDecl>(D) && !isa<IndirectFieldDecl>(D) && (!isa<TagDecl>(D) || cast<TagDecl>(D)->getTagKind() == TTK_Class || cast<TagDecl>(D)->getTagKind() == TTK_Interface)) data().HasOnlyCMembers = false; // Ignore friends and invalid declarations. if (D->getFriendObjectKind() || D->isInvalidDecl()) return; FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); if (FunTmpl) D = FunTmpl->getTemplatedDecl(); if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { if (Method->isVirtual()) { // C++ [dcl.init.aggr]p1: // An aggregate is an array or a class with [...] no virtual functions. data().Aggregate = false; // C++ [class]p4: // A POD-struct is an aggregate class... data().PlainOldData = false; // Virtual functions make the class non-empty. // FIXME: Standard ref? data().Empty = false; // C++ [class.virtual]p1: // A class that declares or inherits a virtual function is called a // polymorphic class. data().Polymorphic = true; // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: // A [default constructor, copy/move constructor, or copy/move // assignment operator for a class X] is trivial [...] if: // -- class X has no virtual functions [...] data().HasTrivialSpecialMembers &= SMF_Destructor; // C++0x [class]p7: // A standard-layout class is a class that: [...] // -- has no virtual functions data().IsStandardLayout = false; } } // Notify the listener if an implicit member was added after the definition // was completed. if (!isBeingDefined() && D->isImplicit()) if (ASTMutationListener *L = getASTMutationListener()) L->AddedCXXImplicitMember(data().Definition, D); // The kind of special member this declaration is, if any. unsigned SMKind = 0; // Handle constructors. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { if (!Constructor->isImplicit()) { // Note that we have a user-declared constructor. data().UserDeclaredConstructor = true; // C++ [class]p4: // A POD-struct is an aggregate class [...] // Since the POD bit is meant to be C++03 POD-ness, clear it even if the // type is technically an aggregate in C++0x since it wouldn't be in 03. data().PlainOldData = false; } // Technically, "user-provided" is only defined for special member // functions, but the intent of the standard is clearly that it should apply // to all functions. bool UserProvided = Constructor->isUserProvided(); if (Constructor->isDefaultConstructor()) { SMKind |= SMF_DefaultConstructor; if (UserProvided) data().UserProvidedDefaultConstructor = true; if (Constructor->isConstexpr()) data().HasConstexprDefaultConstructor = true; } if (!FunTmpl) { unsigned Quals; if (Constructor->isCopyConstructor(Quals)) { SMKind |= SMF_CopyConstructor; if (Quals & Qualifiers::Const) data().HasDeclaredCopyConstructorWithConstParam = true; } else if (Constructor->isMoveConstructor()) SMKind |= SMF_MoveConstructor; } // Record if we see any constexpr constructors which are neither copy // nor move constructors. if (Constructor->isConstexpr() && !Constructor->isCopyOrMoveConstructor()) data().HasConstexprNonCopyMoveConstructor = true; // C++ [dcl.init.aggr]p1: // An aggregate is an array or a class with no user-declared // constructors [...]. // C++11 [dcl.init.aggr]p1: // An aggregate is an array or a class with no user-provided // constructors [...]. if (getASTContext().getLangOpts().CPlusPlus11 ? UserProvided : !Constructor->isImplicit()) data().Aggregate = false; } // Handle destructors. if (CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) { SMKind |= SMF_Destructor; if (DD->isUserProvided()) data().HasIrrelevantDestructor = false; // If the destructor is explicitly defaulted and not trivial or not public // or if the destructor is deleted, we clear HasIrrelevantDestructor in // finishedDefaultedOrDeletedMember. // C++11 [class.dtor]p5: // A destructor is trivial if [...] the destructor is not virtual. if (DD->isVirtual()) data().HasTrivialSpecialMembers &= ~SMF_Destructor; } // Handle member functions. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { if (Method->isCopyAssignmentOperator()) { SMKind |= SMF_CopyAssignment; const ReferenceType *ParamTy = Method->getParamDecl(0)->getType()->getAs<ReferenceType>(); if (!ParamTy || ParamTy->getPointeeType().isConstQualified()) data().HasDeclaredCopyAssignmentWithConstParam = true; } if (Method->isMoveAssignmentOperator()) SMKind |= SMF_MoveAssignment; // Keep the list of conversion functions up-to-date. if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) { // FIXME: We use the 'unsafe' accessor for the access specifier here, // because Sema may not have set it yet. That's really just a misdesign // in Sema. However, LLDB *will* have set the access specifier correctly, // and adds declarations after the class is technically completed, // so completeDefinition()'s overriding of the access specifiers doesn't // work. AccessSpecifier AS = Conversion->getAccessUnsafe(); if (Conversion->getPrimaryTemplate()) { // We don't record specializations. } else { ASTContext &Ctx = getASTContext(); ASTUnresolvedSet &Conversions = data().Conversions.get(Ctx); NamedDecl *Primary = FunTmpl ? cast<NamedDecl>(FunTmpl) : cast<NamedDecl>(Conversion); if (Primary->getPreviousDecl()) Conversions.replace(cast<NamedDecl>(Primary->getPreviousDecl()), Primary, AS); else Conversions.addDecl(Ctx, Primary, AS); } } if (SMKind) { // If this is the first declaration of a special member, we no longer have // an implicit trivial special member. data().HasTrivialSpecialMembers &= data().DeclaredSpecialMembers | ~SMKind; if (!Method->isImplicit() && !Method->isUserProvided()) { // This method is user-declared but not user-provided. We can't work out // whether it's trivial yet (not until we get to the end of the class). // We'll handle this method in finishedDefaultedOrDeletedMember. } else if (Method->isTrivial()) data().HasTrivialSpecialMembers |= SMKind; else data().DeclaredNonTrivialSpecialMembers |= SMKind; // Note when we have declared a declared special member, and suppress the // implicit declaration of this special member. data().DeclaredSpecialMembers |= SMKind; if (!Method->isImplicit()) { data().UserDeclaredSpecialMembers |= SMKind; // C++03 [class]p4: // A POD-struct is an aggregate class that has [...] no user-defined // copy assignment operator and no user-defined destructor. // // Since the POD bit is meant to be C++03 POD-ness, and in C++03, // aggregates could not have any constructors, clear it even for an // explicitly defaulted or deleted constructor. // type is technically an aggregate in C++0x since it wouldn't be in 03. // // Also, a user-declared move assignment operator makes a class non-POD. // This is an extension in C++03. data().PlainOldData = false; } } return; } // Handle non-static data members. if (FieldDecl *Field = dyn_cast<FieldDecl>(D)) { // C++ [class.bit]p2: // A declaration for a bit-field that omits the identifier declares an // unnamed bit-field. Unnamed bit-fields are not members and cannot be // initialized. if (Field->isUnnamedBitfield()) return; // C++ [dcl.init.aggr]p1: // An aggregate is an array or a class (clause 9) with [...] no // private or protected non-static data members (clause 11). // // A POD must be an aggregate. if (D->getAccess() == AS_private || D->getAccess() == AS_protected) { data().Aggregate = false; data().PlainOldData = false; } // C++0x [class]p7: // A standard-layout class is a class that: // [...] // -- has the same access control for all non-static data members, switch (D->getAccess()) { case AS_private: data().HasPrivateFields = true; break; case AS_protected: data().HasProtectedFields = true; break; case AS_public: data().HasPublicFields = true; break; case AS_none: llvm_unreachable("Invalid access specifier"); }; if ((data().HasPrivateFields + data().HasProtectedFields + data().HasPublicFields) > 1) data().IsStandardLayout = false; // Keep track of the presence of mutable fields. if (Field->isMutable()) data().HasMutableFields = true; // C++11 [class.union]p8, DR1460: // If X is a union, a non-static data member of X that is not an anonymous // union is a variant member of X. if (isUnion() && !Field->isAnonymousStructOrUnion()) data().HasVariantMembers = true; // C++0x [class]p9: // A POD struct is a class that is both a trivial class and a // standard-layout class, and has no non-static data members of type // non-POD struct, non-POD union (or array of such types). // // Automatic Reference Counting: the presence of a member of Objective-C pointer type // that does not explicitly have no lifetime makes the class a non-POD. // However, we delay setting PlainOldData to false in this case so that // Sema has a chance to diagnostic causes where the same class will be // non-POD with Automatic Reference Counting but a POD without ARC. // In this case, the class will become a non-POD class when we complete // the definition. ASTContext &Context = getASTContext(); QualType T = Context.getBaseElementType(Field->getType()); if (T->isObjCRetainableType() || T.isObjCGCStrong()) { if (!Context.getLangOpts().ObjCAutoRefCount || T.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) setHasObjectMember(true); } else if (!T.isCXX98PODType(Context)) data().PlainOldData = false; if (T->isReferenceType()) { if (!Field->hasInClassInitializer()) data().HasUninitializedReferenceMember = true; // C++0x [class]p7: // A standard-layout class is a class that: // -- has no non-static data members of type [...] reference, data().IsStandardLayout = false; } // Record if this field is the first non-literal or volatile field or base. if (!T->isLiteralType(Context) || T.isVolatileQualified()) data().HasNonLiteralTypeFieldsOrBases = true; if (Field->hasInClassInitializer() || (Field->isAnonymousStructOrUnion() && Field->getType()->getAsCXXRecordDecl()->hasInClassInitializer())) { data().HasInClassInitializer = true; // C++11 [class]p5: // A default constructor is trivial if [...] no non-static data member // of its class has a brace-or-equal-initializer. data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor; // C++11 [dcl.init.aggr]p1: // An aggregate is a [...] class with [...] no // brace-or-equal-initializers for non-static data members. // // This rule was removed in C++1y. if (!getASTContext().getLangOpts().CPlusPlus1y) data().Aggregate = false; // C++11 [class]p10: // A POD struct is [...] a trivial class. data().PlainOldData = false; } // C++11 [class.copy]p23: // A defaulted copy/move assignment operator for a class X is defined // as deleted if X has: // -- a non-static data member of reference type if (T->isReferenceType()) data().DefaultedMoveAssignmentIsDeleted = true; if (const RecordType *RecordTy = T->getAs<RecordType>()) { CXXRecordDecl* FieldRec = cast<CXXRecordDecl>(RecordTy->getDecl()); if (FieldRec->getDefinition()) { addedClassSubobject(FieldRec); // We may need to perform overload resolution to determine whether a // field can be moved if it's const or volatile qualified. if (T.getCVRQualifiers() & (Qualifiers::Const | Qualifiers::Volatile)) { data().NeedOverloadResolutionForMoveConstructor = true; data().NeedOverloadResolutionForMoveAssignment = true; } // C++11 [class.ctor]p5, C++11 [class.copy]p11: // A defaulted [special member] for a class X is defined as // deleted if: // -- X is a union-like class that has a variant member with a // non-trivial [corresponding special member] if (isUnion()) { if (FieldRec->hasNonTrivialMoveConstructor()) data().DefaultedMoveConstructorIsDeleted = true; if (FieldRec->hasNonTrivialMoveAssignment()) data().DefaultedMoveAssignmentIsDeleted = true; if (FieldRec->hasNonTrivialDestructor()) data().DefaultedDestructorIsDeleted = true; } // C++0x [class.ctor]p5: // A default constructor is trivial [...] if: // -- for all the non-static data members of its class that are of // class type (or array thereof), each such class has a trivial // default constructor. if (!FieldRec->hasTrivialDefaultConstructor()) data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor; // C++0x [class.copy]p13: // A copy/move constructor for class X is trivial if [...] // [...] // -- for each non-static data member of X that is of class type (or // an array thereof), the constructor selected to copy/move that // member is trivial; if (!FieldRec->hasTrivialCopyConstructor()) data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor; // If the field doesn't have a simple move constructor, we'll eagerly // declare the move constructor for this class and we'll decide whether // it's trivial then. if (!FieldRec->hasTrivialMoveConstructor()) data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor; // C++0x [class.copy]p27: // A copy/move assignment operator for class X is trivial if [...] // [...] // -- for each non-static data member of X that is of class type (or // an array thereof), the assignment operator selected to // copy/move that member is trivial; if (!FieldRec->hasTrivialCopyAssignment()) data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment; // If the field doesn't have a simple move assignment, we'll eagerly // declare the move assignment for this class and we'll decide whether // it's trivial then. if (!FieldRec->hasTrivialMoveAssignment()) data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment; if (!FieldRec->hasTrivialDestructor()) data().HasTrivialSpecialMembers &= ~SMF_Destructor; if (!FieldRec->hasIrrelevantDestructor()) data().HasIrrelevantDestructor = false; if (FieldRec->hasObjectMember()) setHasObjectMember(true); if (FieldRec->hasVolatileMember()) setHasVolatileMember(true); // C++0x [class]p7: // A standard-layout class is a class that: // -- has no non-static data members of type non-standard-layout // class (or array of such types) [...] if (!FieldRec->isStandardLayout()) data().IsStandardLayout = false; // C++0x [class]p7: // A standard-layout class is a class that: // [...] // -- has no base classes of the same type as the first non-static // data member. // We don't want to expend bits in the state of the record decl // tracking whether this is the first non-static data member so we // cheat a bit and use some of the existing state: the empty bit. // Virtual bases and virtual methods make a class non-empty, but they // also make it non-standard-layout so we needn't check here. // A non-empty base class may leave the class standard-layout, but not // if we have arrived here, and have at least one non-static data // member. If IsStandardLayout remains true, then the first non-static // data member must come through here with Empty still true, and Empty // will subsequently be set to false below. if (data().IsStandardLayout && data().Empty) { for (const auto &BI : bases()) { if (Context.hasSameUnqualifiedType(BI.getType(), T)) { data().IsStandardLayout = false; break; } } } // Keep track of the presence of mutable fields. if (FieldRec->hasMutableFields()) data().HasMutableFields = true; // C++11 [class.copy]p13: // If the implicitly-defined constructor would satisfy the // requirements of a constexpr constructor, the implicitly-defined // constructor is constexpr. // C++11 [dcl.constexpr]p4: // -- every constructor involved in initializing non-static data // members [...] shall be a constexpr constructor if (!Field->hasInClassInitializer() && !FieldRec->hasConstexprDefaultConstructor() && !isUnion()) // The standard requires any in-class initializer to be a constant // expression. We consider this to be a defect. data().DefaultedDefaultConstructorIsConstexpr = false; // C++11 [class.copy]p8: // The implicitly-declared copy constructor for a class X will have // the form 'X::X(const X&)' if [...] for all the non-static data // members of X that are of a class type M (or array thereof), each // such class type has a copy constructor whose first parameter is // of type 'const M&' or 'const volatile M&'. if (!FieldRec->hasCopyConstructorWithConstParam()) data().ImplicitCopyConstructorHasConstParam = false; // C++11 [class.copy]p18: // The implicitly-declared copy assignment oeprator for a class X will // have the form 'X& X::operator=(const X&)' if [...] for all the // non-static data members of X that are of a class type M (or array // thereof), each such class type has a copy assignment operator whose // parameter is of type 'const M&', 'const volatile M&' or 'M'. if (!FieldRec->hasCopyAssignmentWithConstParam()) data().ImplicitCopyAssignmentHasConstParam = false; if (FieldRec->hasUninitializedReferenceMember() && !Field->hasInClassInitializer()) data().HasUninitializedReferenceMember = true; // C++11 [class.union]p8, DR1460: // a non-static data member of an anonymous union that is a member of // X is also a variant member of X. if (FieldRec->hasVariantMembers() && Field->isAnonymousStructOrUnion()) data().HasVariantMembers = true; } } else { // Base element type of field is a non-class type. if (!T->isLiteralType(Context) || (!Field->hasInClassInitializer() && !isUnion())) data().DefaultedDefaultConstructorIsConstexpr = false; // C++11 [class.copy]p23: // A defaulted copy/move assignment operator for a class X is defined // as deleted if X has: // -- a non-static data member of const non-class type (or array // thereof) if (T.isConstQualified()) data().DefaultedMoveAssignmentIsDeleted = true; } // C++0x [class]p7: // A standard-layout class is a class that: // [...] // -- either has no non-static data members in the most derived // class and at most one base class with non-static data members, // or has no base classes with non-static data members, and // At this point we know that we have a non-static data member, so the last // clause holds. if (!data().HasNoNonEmptyBases) data().IsStandardLayout = false; // If this is not a zero-length bit-field, then the class is not empty. if (data().Empty) { if (!Field->isBitField() || (!Field->getBitWidth()->isTypeDependent() && !Field->getBitWidth()->isValueDependent() && Field->getBitWidthValue(Context) != 0)) data().Empty = false; } } // Handle using declarations of conversion functions. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(D)) { if (Shadow->getDeclName().getNameKind() == DeclarationName::CXXConversionFunctionName) { ASTContext &Ctx = getASTContext(); data().Conversions.get(Ctx).addDecl(Ctx, Shadow, Shadow->getAccess()); } } } void CXXRecordDecl::finishedDefaultedOrDeletedMember(CXXMethodDecl *D) { assert(!D->isImplicit() && !D->isUserProvided()); // The kind of special member this declaration is, if any. unsigned SMKind = 0; if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { if (Constructor->isDefaultConstructor()) { SMKind |= SMF_DefaultConstructor; if (Constructor->isConstexpr()) data().HasConstexprDefaultConstructor = true; } if (Constructor->isCopyConstructor()) SMKind |= SMF_CopyConstructor; else if (Constructor->isMoveConstructor()) SMKind |= SMF_MoveConstructor; else if (Constructor->isConstexpr()) // We may now know that the constructor is constexpr. data().HasConstexprNonCopyMoveConstructor = true; } else if (isa<CXXDestructorDecl>(D)) { SMKind |= SMF_Destructor; if (!D->isTrivial() || D->getAccess() != AS_public || D->isDeleted()) data().HasIrrelevantDestructor = false; } else if (D->isCopyAssignmentOperator()) SMKind |= SMF_CopyAssignment; else if (D->isMoveAssignmentOperator()) SMKind |= SMF_MoveAssignment; // Update which trivial / non-trivial special members we have. // addedMember will have skipped this step for this member. if (D->isTrivial()) data().HasTrivialSpecialMembers |= SMKind; else data().DeclaredNonTrivialSpecialMembers |= SMKind; } bool CXXRecordDecl::isCLike() const { if (getTagKind() == TTK_Class || getTagKind() == TTK_Interface || !TemplateOrInstantiation.isNull()) return false; if (!hasDefinition()) return true; return isPOD() && data().HasOnlyCMembers; } bool CXXRecordDecl::isGenericLambda() const { if (!isLambda()) return false; return getLambdaData().IsGenericLambda; } CXXMethodDecl* CXXRecordDecl::getLambdaCallOperator() const { if (!isLambda()) return nullptr; DeclarationName Name = getASTContext().DeclarationNames.getCXXOperatorName(OO_Call); DeclContext::lookup_const_result Calls = lookup(Name); assert(!Calls.empty() && "Missing lambda call operator!"); assert(Calls.size() == 1 && "More than one lambda call operator!"); NamedDecl *CallOp = Calls.front(); if (FunctionTemplateDecl *CallOpTmpl = dyn_cast<FunctionTemplateDecl>(CallOp)) return cast<CXXMethodDecl>(CallOpTmpl->getTemplatedDecl()); return cast<CXXMethodDecl>(CallOp); } CXXMethodDecl* CXXRecordDecl::getLambdaStaticInvoker() const { if (!isLambda()) return nullptr; DeclarationName Name = &getASTContext().Idents.get(getLambdaStaticInvokerName()); DeclContext::lookup_const_result Invoker = lookup(Name); if (Invoker.empty()) return nullptr; assert(Invoker.size() == 1 && "More than one static invoker operator!"); NamedDecl *InvokerFun = Invoker.front(); if (FunctionTemplateDecl *InvokerTemplate = dyn_cast<FunctionTemplateDecl>(InvokerFun)) return cast<CXXMethodDecl>(InvokerTemplate->getTemplatedDecl()); return cast<CXXMethodDecl>(InvokerFun); } void CXXRecordDecl::getCaptureFields( llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures, FieldDecl *&ThisCapture) const { Captures.clear(); ThisCapture = nullptr; LambdaDefinitionData &Lambda = getLambdaData(); RecordDecl::field_iterator Field = field_begin(); for (const LambdaCapture *C = Lambda.Captures, *CEnd = C + Lambda.NumCaptures; C != CEnd; ++C, ++Field) { if (C->capturesThis()) ThisCapture = *Field; else if (C->capturesVariable()) Captures[C->getCapturedVar()] = *Field; } assert(Field == field_end()); } TemplateParameterList * CXXRecordDecl::getGenericLambdaTemplateParameterList() const { if (!isLambda()) return nullptr; CXXMethodDecl *CallOp = getLambdaCallOperator(); if (FunctionTemplateDecl *Tmpl = CallOp->getDescribedFunctionTemplate()) return Tmpl->getTemplateParameters(); return nullptr; } static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv) { QualType T = cast<CXXConversionDecl>(Conv->getUnderlyingDecl()->getAsFunction()) ->getConversionType(); return Context.getCanonicalType(T); } /// Collect the visible conversions of a base class. /// /// \param Record a base class of the class we're considering /// \param InVirtual whether this base class is a virtual base (or a base /// of a virtual base) /// \param Access the access along the inheritance path to this base /// \param ParentHiddenTypes the conversions provided by the inheritors /// of this base /// \param Output the set to which to add conversions from non-virtual bases /// \param VOutput the set to which to add conversions from virtual bases /// \param HiddenVBaseCs the set of conversions which were hidden in a /// virtual base along some inheritance path static void CollectVisibleConversions(ASTContext &Context, CXXRecordDecl *Record, bool InVirtual, AccessSpecifier Access, const llvm::SmallPtrSet<CanQualType, 8> &ParentHiddenTypes, ASTUnresolvedSet &Output, UnresolvedSetImpl &VOutput, llvm::SmallPtrSet<NamedDecl*, 8> &HiddenVBaseCs) { // The set of types which have conversions in this class or its // subclasses. As an optimization, we don't copy the derived set // unless it might change. const llvm::SmallPtrSet<CanQualType, 8> *HiddenTypes = &ParentHiddenTypes; llvm::SmallPtrSet<CanQualType, 8> HiddenTypesBuffer; // Collect the direct conversions and figure out which conversions // will be hidden in the subclasses. CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin(); CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end(); if (ConvI != ConvE) { HiddenTypesBuffer = ParentHiddenTypes; HiddenTypes = &HiddenTypesBuffer; for (CXXRecordDecl::conversion_iterator I = ConvI; I != ConvE; ++I) { CanQualType ConvType(GetConversionType(Context, I.getDecl())); bool Hidden = ParentHiddenTypes.count(ConvType); if (!Hidden) HiddenTypesBuffer.insert(ConvType); // If this conversion is hidden and we're in a virtual base, // remember that it's hidden along some inheritance path. if (Hidden && InVirtual) HiddenVBaseCs.insert(cast<NamedDecl>(I.getDecl()->getCanonicalDecl())); // If this conversion isn't hidden, add it to the appropriate output. else if (!Hidden) { AccessSpecifier IAccess = CXXRecordDecl::MergeAccess(Access, I.getAccess()); if (InVirtual) VOutput.addDecl(I.getDecl(), IAccess); else Output.addDecl(Context, I.getDecl(), IAccess); } } } // Collect information recursively from any base classes. for (const auto &I : Record->bases()) { const RecordType *RT = I.getType()->getAs<RecordType>(); if (!RT) continue; AccessSpecifier BaseAccess = CXXRecordDecl::MergeAccess(Access, I.getAccessSpecifier()); bool BaseInVirtual = InVirtual || I.isVirtual(); CXXRecordDecl *Base = cast<CXXRecordDecl>(RT->getDecl()); CollectVisibleConversions(Context, Base, BaseInVirtual, BaseAccess, *HiddenTypes, Output, VOutput, HiddenVBaseCs); } } /// Collect the visible conversions of a class. /// /// This would be extremely straightforward if it weren't for virtual /// bases. It might be worth special-casing that, really. static void CollectVisibleConversions(ASTContext &Context, CXXRecordDecl *Record, ASTUnresolvedSet &Output) { // The collection of all conversions in virtual bases that we've // found. These will be added to the output as long as they don't // appear in the hidden-conversions set. UnresolvedSet<8> VBaseCs; // The set of conversions in virtual bases that we've determined to // be hidden. llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs; // The set of types hidden by classes derived from this one. llvm::SmallPtrSet<CanQualType, 8> HiddenTypes; // Go ahead and collect the direct conversions and add them to the // hidden-types set. CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin(); CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end(); Output.append(Context, ConvI, ConvE); for (; ConvI != ConvE; ++ConvI) HiddenTypes.insert(GetConversionType(Context, ConvI.getDecl())); // Recursively collect conversions from base classes. for (const auto &I : Record->bases()) { const RecordType *RT = I.getType()->getAs<RecordType>(); if (!RT) continue; CollectVisibleConversions(Context, cast<CXXRecordDecl>(RT->getDecl()), I.isVirtual(), I.getAccessSpecifier(), HiddenTypes, Output, VBaseCs, HiddenVBaseCs); } // Add any unhidden conversions provided by virtual bases. for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end(); I != E; ++I) { if (!HiddenVBaseCs.count(cast<NamedDecl>(I.getDecl()->getCanonicalDecl()))) Output.addDecl(Context, I.getDecl(), I.getAccess()); } } /// getVisibleConversionFunctions - get all conversion functions visible /// in current class; including conversion function templates. std::pair<CXXRecordDecl::conversion_iterator,CXXRecordDecl::conversion_iterator> CXXRecordDecl::getVisibleConversionFunctions() { ASTContext &Ctx = getASTContext(); ASTUnresolvedSet *Set; if (bases_begin() == bases_end()) { // If root class, all conversions are visible. Set = &data().Conversions.get(Ctx); } else { Set = &data().VisibleConversions.get(Ctx); // If visible conversion list is not evaluated, evaluate it. if (!data().ComputedVisibleConversions) { CollectVisibleConversions(Ctx, this, *Set); data().ComputedVisibleConversions = true; } } return std::make_pair(Set->begin(), Set->end()); } void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) { // This operation is O(N) but extremely rare. Sema only uses it to // remove UsingShadowDecls in a class that were followed by a direct // declaration, e.g.: // class A : B { // using B::operator int; // operator int(); // }; // This is uncommon by itself and even more uncommon in conjunction // with sufficiently large numbers of directly-declared conversions // that asymptotic behavior matters. ASTUnresolvedSet &Convs = data().Conversions.get(getASTContext()); for (unsigned I = 0, E = Convs.size(); I != E; ++I) { if (Convs[I].getDecl() == ConvDecl) { Convs.erase(I); assert(std::find(Convs.begin(), Convs.end(), ConvDecl) == Convs.end() && "conversion was found multiple times in unresolved set"); return; } } llvm_unreachable("conversion not found in set!"); } CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const { if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) return cast<CXXRecordDecl>(MSInfo->getInstantiatedFrom()); return nullptr; } void CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD, TemplateSpecializationKind TSK) { assert(TemplateOrInstantiation.isNull() && "Previous template or instantiation?"); assert(!isa<ClassTemplatePartialSpecializationDecl>(this)); TemplateOrInstantiation = new (getASTContext()) MemberSpecializationInfo(RD, TSK); } TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{ if (const ClassTemplateSpecializationDecl *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this)) return Spec->getSpecializationKind(); if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) return MSInfo->getTemplateSpecializationKind(); return TSK_Undeclared; } void CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) { if (ClassTemplateSpecializationDecl *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this)) { Spec->setSpecializationKind(TSK); return; } if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) { MSInfo->setTemplateSpecializationKind(TSK); return; } llvm_unreachable("Not a class template or member class specialization"); } CXXDestructorDecl *CXXRecordDecl::getDestructor() const { ASTContext &Context = getASTContext(); QualType ClassType = Context.getTypeDeclType(this); DeclarationName Name = Context.DeclarationNames.getCXXDestructorName( Context.getCanonicalType(ClassType)); DeclContext::lookup_const_result R = lookup(Name); if (R.empty()) return nullptr; CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(R.front()); return Dtor; } void CXXRecordDecl::completeDefinition() { completeDefinition(nullptr); } void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) { RecordDecl::completeDefinition(); if (hasObjectMember() && getASTContext().getLangOpts().ObjCAutoRefCount) { // Objective-C Automatic Reference Counting: // If a class has a non-static data member of Objective-C pointer // type (or array thereof), it is a non-POD type and its // default constructor (if any), copy constructor, move constructor, // copy assignment operator, move assignment operator, and destructor are // non-trivial. struct DefinitionData &Data = data(); Data.PlainOldData = false; Data.HasTrivialSpecialMembers = 0; Data.HasIrrelevantDestructor = false; } // If the class may be abstract (but hasn't been marked as such), check for // any pure final overriders. if (mayBeAbstract()) { CXXFinalOverriderMap MyFinalOverriders; if (!FinalOverriders) { getFinalOverriders(MyFinalOverriders); FinalOverriders = &MyFinalOverriders; } bool Done = false; for (CXXFinalOverriderMap::iterator M = FinalOverriders->begin(), MEnd = FinalOverriders->end(); M != MEnd && !Done; ++M) { for (OverridingMethods::iterator SO = M->second.begin(), SOEnd = M->second.end(); SO != SOEnd && !Done; ++SO) { assert(SO->second.size() > 0 && "All virtual functions have overridding virtual functions"); // C++ [class.abstract]p4: // A class is abstract if it contains or inherits at least one // pure virtual function for which the final overrider is pure // virtual. if (SO->second.front().Method->isPure()) { data().Abstract = true; Done = true; break; } } } } // Set access bits correctly on the directly-declared conversions. for (conversion_iterator I = conversion_begin(), E = conversion_end(); I != E; ++I) I.setAccess((*I)->getAccess()); } bool CXXRecordDecl::mayBeAbstract() const { if (data().Abstract || isInvalidDecl() || !data().Polymorphic || isDependentContext()) return false; for (const auto &B : bases()) { CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(B.getType()->getAs<RecordType>()->getDecl()); if (BaseDecl->isAbstract()) return true; } return false; } void CXXMethodDecl::anchor() { } bool CXXMethodDecl::isStatic() const { const CXXMethodDecl *MD = getCanonicalDecl(); if (MD->getStorageClass() == SC_Static) return true; OverloadedOperatorKind OOK = getDeclName().getCXXOverloadedOperator(); return isStaticOverloadedOperator(OOK); } static bool recursivelyOverrides(const CXXMethodDecl *DerivedMD, const CXXMethodDecl *BaseMD) { for (CXXMethodDecl::method_iterator I = DerivedMD->begin_overridden_methods(), E = DerivedMD->end_overridden_methods(); I != E; ++I) { const CXXMethodDecl *MD = *I; if (MD->getCanonicalDecl() == BaseMD->getCanonicalDecl()) return true; if (recursivelyOverrides(MD, BaseMD)) return true; } return false; } CXXMethodDecl * CXXMethodDecl::getCorrespondingMethodInClass(const CXXRecordDecl *RD, bool MayBeBase) { if (this->getParent()->getCanonicalDecl() == RD->getCanonicalDecl()) return this; // Lookup doesn't work for destructors, so handle them separately. if (isa<CXXDestructorDecl>(this)) { CXXMethodDecl *MD = RD->getDestructor(); if (MD) { if (recursivelyOverrides(MD, this)) return MD; if (MayBeBase && recursivelyOverrides(this, MD)) return MD; } return nullptr; } lookup_const_result Candidates = RD->lookup(getDeclName()); for (NamedDecl * const * I = Candidates.begin(); I != Candidates.end(); ++I) { CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*I); if (!MD) continue; if (recursivelyOverrides(MD, this)) return MD; if (MayBeBase && recursivelyOverrides(this, MD)) return MD; } for (const auto &I : RD->bases()) { const RecordType *RT = I.getType()->getAs<RecordType>(); if (!RT) continue; const CXXRecordDecl *Base = cast<CXXRecordDecl>(RT->getDecl()); CXXMethodDecl *T = this->getCorrespondingMethodInClass(Base); if (T) return T; } return nullptr; } CXXMethodDecl * CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool isInline, bool isConstexpr, SourceLocation EndLocation) { return new (C, RD) CXXMethodDecl(CXXMethod, C, RD, StartLoc, NameInfo, T, TInfo, SC, isInline, isConstexpr, EndLocation); } CXXMethodDecl *CXXMethodDecl::CreateDeserialized(ASTContext &C, unsigned ID) { return new (C, ID) CXXMethodDecl(CXXMethod, C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr, SC_None, false, false, SourceLocation()); } bool CXXMethodDecl::isUsualDeallocationFunction() const { if (getOverloadedOperator() != OO_Delete && getOverloadedOperator() != OO_Array_Delete) return false; // C++ [basic.stc.dynamic.deallocation]p2: // A template instance is never a usual deallocation function, // regardless of its signature. if (getPrimaryTemplate()) return false; // C++ [basic.stc.dynamic.deallocation]p2: // If a class T has a member deallocation function named operator delete // with exactly one parameter, then that function is a usual (non-placement) // deallocation function. [...] if (getNumParams() == 1) return true; // C++ [basic.stc.dynamic.deallocation]p2: // [...] If class T does not declare such an operator delete but does // declare a member deallocation function named operator delete with // exactly two parameters, the second of which has type std::size_t (18.1), // then this function is a usual deallocation function. ASTContext &Context = getASTContext(); if (getNumParams() != 2 || !Context.hasSameUnqualifiedType(getParamDecl(1)->getType(), Context.getSizeType())) return false; // This function is a usual deallocation function if there are no // single-parameter deallocation functions of the same kind. DeclContext::lookup_const_result R = getDeclContext()->lookup(getDeclName()); for (DeclContext::lookup_const_result::iterator I = R.begin(), E = R.end(); I != E; ++I) { if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) if (FD->getNumParams() == 1) return false; } return true; } bool CXXMethodDecl::isCopyAssignmentOperator() const { // C++0x [class.copy]p17: // A user-declared copy assignment operator X::operator= is a non-static // non-template member function of class X with exactly one parameter of // type X, X&, const X&, volatile X& or const volatile X&. if (/*operator=*/getOverloadedOperator() != OO_Equal || /*non-static*/ isStatic() || /*non-template*/getPrimaryTemplate() || getDescribedFunctionTemplate() || getNumParams() != 1) return false; QualType ParamType = getParamDecl(0)->getType(); if (const LValueReferenceType *Ref = ParamType->getAs<LValueReferenceType>()) ParamType = Ref->getPointeeType(); ASTContext &Context = getASTContext(); QualType ClassType = Context.getCanonicalType(Context.getTypeDeclType(getParent())); return Context.hasSameUnqualifiedType(ClassType, ParamType); } bool CXXMethodDecl::isMoveAssignmentOperator() const { // C++0x [class.copy]p19: // A user-declared move assignment operator X::operator= is a non-static // non-template member function of class X with exactly one parameter of type // X&&, const X&&, volatile X&&, or const volatile X&&. if (getOverloadedOperator() != OO_Equal || isStatic() || getPrimaryTemplate() || getDescribedFunctionTemplate() || getNumParams() != 1) return false; QualType ParamType = getParamDecl(0)->getType(); if (!isa<RValueReferenceType>(ParamType)) return false; ParamType = ParamType->getPointeeType(); ASTContext &Context = getASTContext(); QualType ClassType = Context.getCanonicalType(Context.getTypeDeclType(getParent())); return Context.hasSameUnqualifiedType(ClassType, ParamType); } void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) { assert(MD->isCanonicalDecl() && "Method is not canonical!"); assert(!MD->getParent()->isDependentContext() && "Can't add an overridden method to a class template!"); assert(MD->isVirtual() && "Method is not virtual!"); getASTContext().addOverriddenMethod(this, MD); } CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const { if (isa<CXXConstructorDecl>(this)) return nullptr; return getASTContext().overridden_methods_begin(this); } CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const { if (isa<CXXConstructorDecl>(this)) return nullptr; return getASTContext().overridden_methods_end(this); } unsigned CXXMethodDecl::size_overridden_methods() const { if (isa<CXXConstructorDecl>(this)) return 0; return getASTContext().overridden_methods_size(this); } QualType CXXMethodDecl::getThisType(ASTContext &C) const { // C++ 9.3.2p1: The type of this in a member function of a class X is X*. // If the member function is declared const, the type of this is const X*, // if the member function is declared volatile, the type of this is // volatile X*, and if the member function is declared const volatile, // the type of this is const volatile X*. assert(isInstance() && "No 'this' for static methods!"); QualType ClassTy = C.getTypeDeclType(getParent()); ClassTy = C.getQualifiedType(ClassTy, Qualifiers::fromCVRMask(getTypeQualifiers())); return C.getPointerType(ClassTy); } bool CXXMethodDecl::hasInlineBody() const { // If this function is a template instantiation, look at the template from // which it was instantiated. const FunctionDecl *CheckFn = getTemplateInstantiationPattern(); if (!CheckFn) CheckFn = this; const FunctionDecl *fn; return CheckFn->hasBody(fn) && !fn->isOutOfLine(); } bool CXXMethodDecl::isLambdaStaticInvoker() const { const CXXRecordDecl *P = getParent(); if (P->isLambda()) { if (const CXXMethodDecl *StaticInvoker = P->getLambdaStaticInvoker()) { if (StaticInvoker == this) return true; if (P->isGenericLambda() && this->isFunctionTemplateSpecialization()) return StaticInvoker == this->getPrimaryTemplate()->getTemplatedDecl(); } } return false; } CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, bool IsVirtual, SourceLocation L, Expr *Init, SourceLocation R, SourceLocation EllipsisLoc) : Initializee(TInfo), MemberOrEllipsisLocation(EllipsisLoc), Init(Init), LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(IsVirtual), IsWritten(false), SourceOrderOrNumArrayIndices(0) { } CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, FieldDecl *Member, SourceLocation MemberLoc, SourceLocation L, Expr *Init, SourceLocation R) : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init), LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false), IsWritten(false), SourceOrderOrNumArrayIndices(0) { } CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, IndirectFieldDecl *Member, SourceLocation MemberLoc, SourceLocation L, Expr *Init, SourceLocation R) : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init), LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false), IsWritten(false), SourceOrderOrNumArrayIndices(0) { } CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, SourceLocation L, Expr *Init, SourceLocation R) : Initializee(TInfo), MemberOrEllipsisLocation(), Init(Init), LParenLoc(L), RParenLoc(R), IsDelegating(true), IsVirtual(false), IsWritten(false), SourceOrderOrNumArrayIndices(0) { } CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, FieldDecl *Member, SourceLocation MemberLoc, SourceLocation L, Expr *Init, SourceLocation R, VarDecl **Indices, unsigned NumIndices) : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init), LParenLoc(L), RParenLoc(R), IsVirtual(false), IsWritten(false), SourceOrderOrNumArrayIndices(NumIndices) { VarDecl **MyIndices = reinterpret_cast<VarDecl **> (this + 1); memcpy(MyIndices, Indices, NumIndices * sizeof(VarDecl *)); } CXXCtorInitializer *CXXCtorInitializer::Create(ASTContext &Context, FieldDecl *Member, SourceLocation MemberLoc, SourceLocation L, Expr *Init, SourceLocation R, VarDecl **Indices, unsigned NumIndices) { void *Mem = Context.Allocate(sizeof(CXXCtorInitializer) + sizeof(VarDecl *) * NumIndices, llvm::alignOf<CXXCtorInitializer>()); return new (Mem) CXXCtorInitializer(Context, Member, MemberLoc, L, Init, R, Indices, NumIndices); } TypeLoc CXXCtorInitializer::getBaseClassLoc() const { if (isBaseInitializer()) return Initializee.get<TypeSourceInfo*>()->getTypeLoc(); else return TypeLoc(); } const Type *CXXCtorInitializer::getBaseClass() const { if (isBaseInitializer()) return Initializee.get<TypeSourceInfo*>()->getType().getTypePtr(); else return nullptr; } SourceLocation CXXCtorInitializer::getSourceLocation() const { if (isAnyMemberInitializer()) return getMemberLocation(); if (isInClassMemberInitializer()) return getAnyMember()->getLocation(); if (TypeSourceInfo *TSInfo = Initializee.get<TypeSourceInfo*>()) return TSInfo->getTypeLoc().getLocalSourceRange().getBegin(); return SourceLocation(); } SourceRange CXXCtorInitializer::getSourceRange() const { if (isInClassMemberInitializer()) { FieldDecl *D = getAnyMember(); if (Expr *I = D->getInClassInitializer()) return I->getSourceRange(); return SourceRange(); } return SourceRange(getSourceLocation(), getRParenLoc()); } void CXXConstructorDecl::anchor() { } CXXConstructorDecl * CXXConstructorDecl::CreateDeserialized(ASTContext &C, unsigned ID) { return new (C, ID) CXXConstructorDecl(C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr, false, false, false, false); } CXXConstructorDecl * CXXConstructorDecl::Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool isExplicit, bool isInline, bool isImplicitlyDeclared, bool isConstexpr) { assert(NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName && "Name must refer to a constructor"); return new (C, RD) CXXConstructorDecl(C, RD, StartLoc, NameInfo, T, TInfo, isExplicit, isInline, isImplicitlyDeclared, isConstexpr); } CXXConstructorDecl *CXXConstructorDecl::getTargetConstructor() const { assert(isDelegatingConstructor() && "Not a delegating constructor!"); Expr *E = (*init_begin())->getInit()->IgnoreImplicit(); if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(E)) return Construct->getConstructor(); return nullptr; } bool CXXConstructorDecl::isDefaultConstructor() const { // C++ [class.ctor]p5: // A default constructor for a class X is a constructor of class // X that can be called without an argument. return (getNumParams() == 0) || (getNumParams() > 0 && getParamDecl(0)->hasDefaultArg()); } bool CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const { return isCopyOrMoveConstructor(TypeQuals) && getParamDecl(0)->getType()->isLValueReferenceType(); } bool CXXConstructorDecl::isMoveConstructor(unsigned &TypeQuals) const { return isCopyOrMoveConstructor(TypeQuals) && getParamDecl(0)->getType()->isRValueReferenceType(); } /// \brief Determine whether this is a copy or move constructor. bool CXXConstructorDecl::isCopyOrMoveConstructor(unsigned &TypeQuals) const { // C++ [class.copy]p2: // A non-template constructor for class X is a copy constructor // if its first parameter is of type X&, const X&, volatile X& or // const volatile X&, and either there are no other parameters // or else all other parameters have default arguments (8.3.6). // C++0x [class.copy]p3: // A non-template constructor for class X is a move constructor if its // first parameter is of type X&&, const X&&, volatile X&&, or // const volatile X&&, and either there are no other parameters or else // all other parameters have default arguments. if ((getNumParams() < 1) || (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) || (getPrimaryTemplate() != nullptr) || (getDescribedFunctionTemplate() != nullptr)) return false; const ParmVarDecl *Param = getParamDecl(0); // Do we have a reference type? const ReferenceType *ParamRefType = Param->getType()->getAs<ReferenceType>(); if (!ParamRefType) return false; // Is it a reference to our class type? ASTContext &Context = getASTContext(); CanQualType PointeeType = Context.getCanonicalType(ParamRefType->getPointeeType()); CanQualType ClassTy = Context.getCanonicalType(Context.getTagDeclType(getParent())); if (PointeeType.getUnqualifiedType() != ClassTy) return false; // FIXME: other qualifiers? // We have a copy or move constructor. TypeQuals = PointeeType.getCVRQualifiers(); return true; } bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const { // C++ [class.conv.ctor]p1: // A constructor declared without the function-specifier explicit // that can be called with a single parameter specifies a // conversion from the type of its first parameter to the type of // its class. Such a constructor is called a converting // constructor. if (isExplicit() && !AllowExplicit) return false; return (getNumParams() == 0 && getType()->getAs<FunctionProtoType>()->isVariadic()) || (getNumParams() == 1) || (getNumParams() > 1 && (getParamDecl(1)->hasDefaultArg() || getParamDecl(1)->isParameterPack())); } bool CXXConstructorDecl::isSpecializationCopyingObject() const { if ((getNumParams() < 1) || (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) || (getPrimaryTemplate() == nullptr) || (getDescribedFunctionTemplate() != nullptr)) return false; const ParmVarDecl *Param = getParamDecl(0); ASTContext &Context = getASTContext(); CanQualType ParamType = Context.getCanonicalType(Param->getType()); // Is it the same as our our class type? CanQualType ClassTy = Context.getCanonicalType(Context.getTagDeclType(getParent())); if (ParamType.getUnqualifiedType() != ClassTy) return false; return true; } const CXXConstructorDecl *CXXConstructorDecl::getInheritedConstructor() const { // Hack: we store the inherited constructor in the overridden method table method_iterator It = getASTContext().overridden_methods_begin(this); if (It == getASTContext().overridden_methods_end(this)) return nullptr; return cast<CXXConstructorDecl>(*It); } void CXXConstructorDecl::setInheritedConstructor(const CXXConstructorDecl *BaseCtor){ // Hack: we store the inherited constructor in the overridden method table assert(getASTContext().overridden_methods_size(this) == 0 && "Base ctor already set."); getASTContext().addOverriddenMethod(this, BaseCtor); } void CXXDestructorDecl::anchor() { } CXXDestructorDecl * CXXDestructorDecl::CreateDeserialized(ASTContext &C, unsigned ID) { return new (C, ID) CXXDestructorDecl(C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr, false, false); } CXXDestructorDecl * CXXDestructorDecl::Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool isInline, bool isImplicitlyDeclared) { assert(NameInfo.getName().getNameKind() == DeclarationName::CXXDestructorName && "Name must refer to a destructor"); return new (C, RD) CXXDestructorDecl(C, RD, StartLoc, NameInfo, T, TInfo, isInline, isImplicitlyDeclared); } void CXXConversionDecl::anchor() { } CXXConversionDecl * CXXConversionDecl::CreateDeserialized(ASTContext &C, unsigned ID) { return new (C, ID) CXXConversionDecl(C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr, false, false, false, SourceLocation()); } CXXConversionDecl * CXXConversionDecl::Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool isInline, bool isExplicit, bool isConstexpr, SourceLocation EndLocation) { assert(NameInfo.getName().getNameKind() == DeclarationName::CXXConversionFunctionName && "Name must refer to a conversion function"); return new (C, RD) CXXConversionDecl(C, RD, StartLoc, NameInfo, T, TInfo, isInline, isExplicit, isConstexpr, EndLocation); } bool CXXConversionDecl::isLambdaToBlockPointerConversion() const { return isImplicit() && getParent()->isLambda() && getConversionType()->isBlockPointerType(); } void LinkageSpecDecl::anchor() { } LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LanguageIDs Lang, bool HasBraces) { return new (C, DC) LinkageSpecDecl(DC, ExternLoc, LangLoc, Lang, HasBraces); } LinkageSpecDecl *LinkageSpecDecl::CreateDeserialized(ASTContext &C, unsigned ID) { return new (C, ID) LinkageSpecDecl(nullptr, SourceLocation(), SourceLocation(), lang_c, false); } void UsingDirectiveDecl::anchor() { } UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Used, DeclContext *CommonAncestor) { if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Used)) Used = NS->getOriginalNamespace(); return new (C, DC) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierLoc, IdentLoc, Used, CommonAncestor); } UsingDirectiveDecl *UsingDirectiveDecl::CreateDeserialized(ASTContext &C, unsigned ID) { return new (C, ID) UsingDirectiveDecl(nullptr, SourceLocation(), SourceLocation(), NestedNameSpecifierLoc(), SourceLocation(), nullptr, nullptr); } NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() { if (NamespaceAliasDecl *NA = dyn_cast_or_null<NamespaceAliasDecl>(NominatedNamespace)) return NA->getNamespace(); return cast_or_null<NamespaceDecl>(NominatedNamespace); } NamespaceDecl::NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl) : NamedDecl(Namespace, DC, IdLoc, Id), DeclContext(Namespace), redeclarable_base(C), LocStart(StartLoc), RBraceLoc(), AnonOrFirstNamespaceAndInline(nullptr, Inline) { setPreviousDecl(PrevDecl); if (PrevDecl) AnonOrFirstNamespaceAndInline.setPointer(PrevDecl->getOriginalNamespace()); } NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl) { return new (C, DC) NamespaceDecl(C, DC, Inline, StartLoc, IdLoc, Id, PrevDecl); } NamespaceDecl *NamespaceDecl::CreateDeserialized(ASTContext &C, unsigned ID) { return new (C, ID) NamespaceDecl(C, nullptr, false, SourceLocation(), SourceLocation(), nullptr, nullptr); } NamespaceDecl *NamespaceDecl::getNextRedeclarationImpl() { return getNextRedeclaration(); } NamespaceDecl *NamespaceDecl::getPreviousDeclImpl() { return getPreviousDecl(); } NamespaceDecl *NamespaceDecl::getMostRecentDeclImpl() { return getMostRecentDecl(); } void NamespaceAliasDecl::anchor() { } NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Namespace) { if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Namespace)) Namespace = NS->getOriginalNamespace(); return new (C, DC) NamespaceAliasDecl(DC, UsingLoc, AliasLoc, Alias, QualifierLoc, IdentLoc, Namespace); } NamespaceAliasDecl * NamespaceAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) { return new (C, ID) NamespaceAliasDecl(nullptr, SourceLocation(), SourceLocation(), nullptr, NestedNameSpecifierLoc(), SourceLocation(), nullptr); } void UsingShadowDecl::anchor() { } UsingShadowDecl * UsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) { return new (C, ID) UsingShadowDecl(C, nullptr, SourceLocation(), nullptr, nullptr); } UsingDecl *UsingShadowDecl::getUsingDecl() const { const UsingShadowDecl *Shadow = this; while (const UsingShadowDecl *NextShadow = dyn_cast<UsingShadowDecl>(Shadow->UsingOrNextShadow)) Shadow = NextShadow; return cast<UsingDecl>(Shadow->UsingOrNextShadow); } void UsingDecl::anchor() { } void UsingDecl::addShadowDecl(UsingShadowDecl *S) { assert(std::find(shadow_begin(), shadow_end(), S) == shadow_end() && "declaration already in set"); assert(S->getUsingDecl() == this); if (FirstUsingShadow.getPointer()) S->UsingOrNextShadow = FirstUsingShadow.getPointer(); FirstUsingShadow.setPointer(S); } void UsingDecl::removeShadowDecl(UsingShadowDecl *S) { assert(std::find(shadow_begin(), shadow_end(), S) != shadow_end() && "declaration not in set"); assert(S->getUsingDecl() == this); // Remove S from the shadow decl chain. This is O(n) but hopefully rare. if (FirstUsingShadow.getPointer() == S) { FirstUsingShadow.setPointer( dyn_cast<UsingShadowDecl>(S->UsingOrNextShadow)); S->UsingOrNextShadow = this; return; } UsingShadowDecl *Prev = FirstUsingShadow.getPointer(); while (Prev->UsingOrNextShadow != S) Prev = cast<UsingShadowDecl>(Prev->UsingOrNextShadow); Prev->UsingOrNextShadow = S->UsingOrNextShadow; S->UsingOrNextShadow = this; } UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation UL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypename) { return new (C, DC) UsingDecl(DC, UL, QualifierLoc, NameInfo, HasTypename); } UsingDecl *UsingDecl::CreateDeserialized(ASTContext &C, unsigned ID) { return new (C, ID) UsingDecl(nullptr, SourceLocation(), NestedNameSpecifierLoc(), DeclarationNameInfo(), false); } SourceRange UsingDecl::getSourceRange() const { SourceLocation Begin = isAccessDeclaration() ? getQualifierLoc().getBeginLoc() : UsingLocation; return SourceRange(Begin, getNameInfo().getEndLoc()); } void UnresolvedUsingValueDecl::anchor() { } UnresolvedUsingValueDecl * UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo) { return new (C, DC) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc, QualifierLoc, NameInfo); } UnresolvedUsingValueDecl * UnresolvedUsingValueDecl::CreateDeserialized(ASTContext &C, unsigned ID) { return new (C, ID) UnresolvedUsingValueDecl(nullptr, QualType(), SourceLocation(), NestedNameSpecifierLoc(), DeclarationNameInfo()); } SourceRange UnresolvedUsingValueDecl::getSourceRange() const { SourceLocation Begin = isAccessDeclaration() ? getQualifierLoc().getBeginLoc() : UsingLocation; return SourceRange(Begin, getNameInfo().getEndLoc()); } void UnresolvedUsingTypenameDecl::anchor() { } UnresolvedUsingTypenameDecl * UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TargetNameLoc, DeclarationName TargetName) { return new (C, DC) UnresolvedUsingTypenameDecl( DC, UsingLoc, TypenameLoc, QualifierLoc, TargetNameLoc, TargetName.getAsIdentifierInfo()); } UnresolvedUsingTypenameDecl * UnresolvedUsingTypenameDecl::CreateDeserialized(ASTContext &C, unsigned ID) { return new (C, ID) UnresolvedUsingTypenameDecl( nullptr, SourceLocation(), SourceLocation(), NestedNameSpecifierLoc(), SourceLocation(), nullptr); } void StaticAssertDecl::anchor() { } StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *Message, SourceLocation RParenLoc, bool Failed) { return new (C, DC) StaticAssertDecl(DC, StaticAssertLoc, AssertExpr, Message, RParenLoc, Failed); } StaticAssertDecl *StaticAssertDecl::CreateDeserialized(ASTContext &C, unsigned ID) { return new (C, ID) StaticAssertDecl(nullptr, SourceLocation(), nullptr, nullptr, SourceLocation(), false); } MSPropertyDecl *MSPropertyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter) { return new (C, DC) MSPropertyDecl(DC, L, N, T, TInfo, StartL, Getter, Setter); } MSPropertyDecl *MSPropertyDecl::CreateDeserialized(ASTContext &C, unsigned ID) { return new (C, ID) MSPropertyDecl(nullptr, SourceLocation(), DeclarationName(), QualType(), nullptr, SourceLocation(), nullptr, nullptr); } static const char *getAccessName(AccessSpecifier AS) { switch (AS) { case AS_none: llvm_unreachable("Invalid access specifier!"); case AS_public: return "public"; case AS_private: return "private"; case AS_protected: return "protected"; } llvm_unreachable("Invalid access specifier!"); } const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB, AccessSpecifier AS) { return DB << getAccessName(AS); } const PartialDiagnostic &clang::operator<<(const PartialDiagnostic &DB, AccessSpecifier AS) { return DB << getAccessName(AS); }
s20121035/rk3288_android5.1_repo
external/clang/lib/AST/DeclCXX.cpp
C++
gpl-3.0
87,317
package com.abm.mainet.water.dto; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.codehaus.jackson.annotate.JsonAutoDetect; import org.codehaus.jackson.map.annotate.JsonDeserialize; import org.codehaus.jackson.map.annotate.JsonSerialize; import com.abm.mainet.common.dto.ApplicantDetailDTO; import com.abm.mainet.common.integration.dto.DocumentDetailsVO; @JsonAutoDetect @JsonSerialize @JsonDeserialize public class ChangeOfOwnerRequestDTO implements Serializable { private static final long serialVersionUID = 1900116677228883696L; private long orgnId; private Long csIdn; private Long apmApplicationId; private Date cooApldate; private Long cooNotitle; private String cooNoname; private String cooNomname; private String cooNolname; private Long cooOtitle; private String cooOname; private String cooOomname; private String cooOolname; private String cooRemark; private String cooGranted; private Long userEmpId; private int langId; private String cooNotitleCopy; private String lgIpMac; private Long cooUidNo; private Long conUidNo; private long serviceId; private double amount; private int documentSize; private String onlineOfflineCheck; private List<ChangeOfOwnerResponseDTO> responseDto = new ArrayList<>(0); private ApplicantDetailDTO applicant; private List<String> fileList; private List<DocumentDetailsVO> uploadedDocList; private long departmenttId; private String connectionNo; private Long gender; private List<AdditionalOwnerInfoDTO> additionalOwners; private ChangeOfOwnerResponseDTO oldOwnerInfo; private Long ownerTransferMode; public long getOrgnId() { return orgnId; } public void setOrgnId(final long orgnId) { this.orgnId = orgnId; } public Long getCsIdn() { return csIdn; } public void setCsIdn(final Long csIdn) { this.csIdn = csIdn; } public Long getApmApplicationId() { return apmApplicationId; } public void setApmApplicationId(final Long apmApplicationId) { this.apmApplicationId = apmApplicationId; } public Date getCooApldate() { return cooApldate; } public void setCooApldate(final Date cooApldate) { this.cooApldate = cooApldate; } public Long getCooNotitle() { return cooNotitle; } public void setCooNotitle(final Long cooNotitle) { this.cooNotitle = cooNotitle; } public String getCooNoname() { return cooNoname; } public void setCooNoname(final String cooNoname) { this.cooNoname = cooNoname; } public String getCooNomname() { return cooNomname; } public void setCooNomname(final String cooNomname) { this.cooNomname = cooNomname; } public String getCooNolname() { return cooNolname; } public void setCooNolname(final String cooNolname) { this.cooNolname = cooNolname; } public Long getCooOtitle() { return cooOtitle; } public void setCooOtitle(final Long cooOtitle) { this.cooOtitle = cooOtitle; } public String getCooOname() { return cooOname; } public void setCooOname(final String cooOname) { this.cooOname = cooOname; } public String getCooOomname() { return cooOomname; } public void setCooOomname(final String cooOomname) { this.cooOomname = cooOomname; } public String getCooOolname() { return cooOolname; } public void setCooOolname(final String cooOolname) { this.cooOolname = cooOolname; } public String getCooRemark() { return cooRemark; } public void setCooRemark(final String cooRemark) { this.cooRemark = cooRemark; } public String getCooGranted() { return cooGranted; } public void setCooGranted(final String cooGranted) { this.cooGranted = cooGranted; } public Long getUserEmpId() { return userEmpId; } public void setUserEmpId(final Long userEmpId) { this.userEmpId = userEmpId; } public int getLangId() { return langId; } public void setLangId(final int langId) { this.langId = langId; } public String getCooNotitleCopy() { return cooNotitleCopy; } public void setCooNotitleCopy(final String cooNotitleCopy) { this.cooNotitleCopy = cooNotitleCopy; } public String getLgIpMac() { return lgIpMac; } public void setLgIpMac(final String lgIpMac) { this.lgIpMac = lgIpMac; } public long getServiceId() { return serviceId; } public void setServiceId(final long serviceId) { this.serviceId = serviceId; } public List<ChangeOfOwnerResponseDTO> getResponseDto() { return responseDto; } public void setResponseDto(final List<ChangeOfOwnerResponseDTO> responseDto) { this.responseDto = responseDto; } public Long getCooUidNo() { return cooUidNo; } public void setCooUidNo(final Long cooUidNo) { this.cooUidNo = cooUidNo; } public Long getConUidNo() { return conUidNo; } public void setConUidNo(final Long conUidNo) { this.conUidNo = conUidNo; } public ApplicantDetailDTO getApplicant() { return applicant; } public void setApplicant(final ApplicantDetailDTO applicant) { this.applicant = applicant; } public double getAmount() { return amount; } public void setAmount(final double amount) { this.amount = amount; } public int getDocumentSize() { return documentSize; } public void setDocumentSize(final int documentSize) { this.documentSize = documentSize; } public String getOnlineOfflineCheck() { return onlineOfflineCheck; } public void setOnlineOfflineCheck(final String onlineOfflineCheck) { this.onlineOfflineCheck = onlineOfflineCheck; } public List<String> getFileList() { return fileList; } public void setFileList(final List<String> fileList) { this.fileList = fileList; } public List<DocumentDetailsVO> getUploadedDocList() { return uploadedDocList; } public void setUploadedDocList(final List<DocumentDetailsVO> uploadedDocList) { this.uploadedDocList = uploadedDocList; } public long getDepartmenttId() { return departmenttId; } public void setDepartmenttId(final long departmenttId) { this.departmenttId = departmenttId; } public String getConnectionNo() { return connectionNo; } public void setConnectionNo(final String connectionNo) { this.connectionNo = connectionNo; } public Long getGender() { return gender; } public void setGender(final Long gender) { this.gender = gender; } public List<AdditionalOwnerInfoDTO> getAdditionalOwners() { return additionalOwners; } public void setAdditionalOwners(final List<AdditionalOwnerInfoDTO> additionalOwners) { this.additionalOwners = additionalOwners; } public ChangeOfOwnerResponseDTO getOldOwnerInfo() { return oldOwnerInfo; } public void setOldOwnerInfo(final ChangeOfOwnerResponseDTO oldOwnerInfo) { this.oldOwnerInfo = oldOwnerInfo; } public Long getOwnerTransferMode() { return ownerTransferMode; } public void setOwnerTransferMode(final Long ownerTransferMode) { this.ownerTransferMode = ownerTransferMode; } }
abmindiarepomanager/ABMOpenMainet
Mainet1.1/MainetServiceParent/MainetServiceWater/src/main/java/com/abm/mainet/water/dto/ChangeOfOwnerRequestDTO.java
Java
gpl-3.0
8,179
package com.github.xzzpig.pigutils.plugin.url; import java.util.Map; public class URLPluginInfo { String name; String[] depends; Map<String, String> infos; String mainClass; public URLPluginInfo(String name, String mainClass, String[] depends, Map<String, String> infos) { this.name = name; this.depends = depends; this.infos = infos; this.mainClass = mainClass; } public String getName() { return name; } public URLPluginInfo setName(String name) { this.name = name; return this; } public String[] getDepends() { return depends; } public URLPluginInfo setDepends(String[] depends) { this.depends = depends; return this; } public Map<String, String> getInfos() { return infos; } public URLPluginInfo setInfos(Map<String, String> infos) { this.infos = infos; return this; } public String getMainClass() { return mainClass; } public URLPluginInfo setMainClass(String mainClass) { this.mainClass = mainClass; return this; } }
xzzpig/PigUtils
Plugin/src/main/java/com/github/xzzpig/pigutils/plugin/url/URLPluginInfo.java
Java
gpl-3.0
989
package com.zhilianxinke.schoolinhand.yingshiyun; import android.content.Context; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; /** * Created by Ldb on 2015/10/29. */ public class CustomExceptionHandler implements Thread.UncaughtExceptionHandler { private Thread.UncaughtExceptionHandler defaultUEH; private Context context; public CustomExceptionHandler(Context context) { this.context = context; this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler(); } @Override public void uncaughtException(Thread thread, Throwable ex) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ex.printStackTrace(new PrintStream(bos)); try { bos.flush(); bos.close(); } catch (IOException e) { e.printStackTrace(); } defaultUEH.uncaughtException(thread, ex); ; } }
zhilianxinke/SchoolInHand
app/src/main/java/com/zhilianxinke/schoolinhand/yingshiyun/CustomExceptionHandler.java
Java
gpl-3.0
955
// Renders area for students in the classroom and their status App.StudentsInClassroomView = Backbone.View.extend({ el: "#studentsInClassList", initialize: function() { this.render(); }, // Todo: Will need add functionality to set status state defcon1 - 3 render: function() { this.$el.empty(); console.log("rendering all students status"); this.collection.each(function(model) { App.studentInClassroomView = new App.StudentInClassroomView({ model: model }); }); } }); // Renders each square for students in the classroom and their status App.StudentInClassroomView = Backbone.View.extend({ el: "#studentsInClassList", tagName: 'li', initialize: function() { this.render(); }, // Todo: Will need add functionality to set status state defcon1 - 3 render: function() { console.log("rendering one student's status"); var source = $("#studentInClassroom").html(); var template = Handlebars.compile(source); var html = template(this.model.toJSON()); this.$el.append(html); } }); // Teacher // Renders area for students in the classroom and their status App.StudentsInClassroomViewT = Backbone.View.extend({ el: "#studentsInClassList", initialize: function() { this.render(); }, // Todo: Will need add functionality to set status state defcon1 - 3 render: function() { this.$el.empty(); console.log("rendering all students status"); this.collection.each(function(model) { App.studentInClassroomViewT = new App.StudentInClassroomViewT({ model: model }); }); } }); // Renders each square for students in the classroom and their status App.StudentInClassroomViewT = Backbone.View.extend({ el: "#studentsInClassList", tagName: 'li', initialize: function() { this.render(); }, // Todo: Will need add functionality to set status state defcon1 - 3 render: function() { console.log("rendering one student's status"); var source = $("#studentInClassroom-t").html(); var template = Handlebars.compile(source); var html = template(this.model.toJSON()); this.$el.append(html); } });
RKJuve/class-barometer
js/view/studentInClassroomView.js
JavaScript
gpl-3.0
2,166
from setuptools import setup version = '2.2.dev0' long_description = '\n\n'.join([ open('README.rst').read(), open('TODO.rst').read(), open('CREDITS.rst').read(), open('CHANGES.rst').read(), ]) install_requires = [ 'Django >= 1.6', 'django-extensions', 'lizard-ui >= 5.0', 'lizard-map >= 5.0', 'django-nose', 'pkginfo', 'django-treebeard', 'factory_boy' ], tests_require = [ ] setup(name='lizard-maptree', version=version, description="Provides tree view functionality to lizard-map applications. ", long_description=long_description, # Get strings from http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=['Programming Language :: Python', 'Framework :: Django', ], keywords=[], author='Jack Ha', author_email='jack.ha@nelen-schuurmans.nl', url='', license='GPL', packages=['lizard_maptree'], include_package_data=True, zip_safe=False, install_requires=install_requires, tests_require=tests_require, extras_require = {'test': tests_require}, entry_points={ 'console_scripts': [ ]}, )
lizardsystem/lizard-maptree
setup.py
Python
gpl-3.0
1,230
<?php namespace Omeka\View\Helper; use Laminas\View\Helper\AbstractHelper; /** * View helper for rendering a sortable link. */ class SortLink extends AbstractHelper { /** * The default partial view script. */ const PARTIAL_NAME = 'common/sort-link'; /** * Render a sortable link. * * @param string $label * @param string $sortBy * @param string|null $partialName Name of view script, or a view model * @return string */ public function __invoke($label, $sortBy, $partialName = null) { $params = $this->getView()->params(); $sortByQuery = $params->fromQuery('sort_by'); $sortOrderQuery = $params->fromQuery('sort_order'); if ('asc' === $sortOrderQuery && $sortByQuery === $sortBy) { $sortOrder = 'desc'; $class = 'sorted-asc'; } elseif ('desc' === $sortOrderQuery && $sortByQuery === $sortBy) { $sortOrder = 'asc'; $class = 'sorted-desc'; } else { $sortOrder = 'asc'; $class = 'sortable'; } $partialName = $partialName ?: self::PARTIAL_NAME; $url = $this->getView()->url( null, [], [ 'query' => [ 'sort_by' => $sortBy, 'sort_order' => $sortOrder, ] + $params->fromQuery(), ], true ); return $this->getView()->partial( $partialName, [ 'label' => $label, 'url' => $url, 'class' => $class, 'sortBy' => $sortBy, 'sortOrder' => $sortOrder, ] ); } }
omeka/omeka-s
application/src/View/Helper/SortLink.php
PHP
gpl-3.0
1,712
// IniConfigurator.cc --- Configuration Access // // Copyright (C) 2005, 2006, 2007, 2008, 2012, 2013 Rob Caelers <robc@krandor.nl> // All rights reserved. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "debug.hh" #include <string.h> #include <sstream> #include <assert.h> #include <iostream> #include <fstream> #include "IniConfigurator.hh" using namespace std; IniConfigurator::IniConfigurator() { } IniConfigurator::~IniConfigurator() { } bool IniConfigurator::load(string filename) { TRACE_ENTER_MSG("IniConfigurator::loada", filename); bool ret = false; try { boost::property_tree::ini_parser::read_ini(filename, pt); ret = !pt.empty(); last_filename = filename; } catch (boost::property_tree::ini_parser_error) { } TRACE_EXIT(); return ret; } bool IniConfigurator::save(string filename) { TRACE_ENTER_MSG("IniConfigurator::save", filename); bool ret = false; try { ofstream config_file(filename.c_str()); boost::property_tree::ini_parser::write_ini(config_file, pt); ret = true; } catch (boost::property_tree::ini_parser_error) { } TRACE_EXIT(); return ret; } bool IniConfigurator::save() { return save(last_filename); } bool IniConfigurator::remove_key(const std::string &key) { bool ret = true; TRACE_ENTER_MSG("IniConfigurator::remove_key", key); boost::property_tree::ptree::path_type inikey = path(key); // pt.erase(inikey); TRACE_EXIT(); return ret; } bool IniConfigurator::get_value(const std::string &key, VariantType type, Variant &out) const { TRACE_ENTER_MSG("IniConfigurator::get_value", key); bool ret = true; boost::property_tree::ptree::path_type inikey = path(key); out.type = type; try { switch(type) { case VARIANT_TYPE_INT: out.int_value = pt.get<int>(inikey); break; case VARIANT_TYPE_BOOL: out.bool_value = pt.get<bool>(inikey); break; case VARIANT_TYPE_DOUBLE: out.double_value = pt.get<double>(inikey); break; case VARIANT_TYPE_NONE: out.type = VARIANT_TYPE_STRING; out.string_value = pt.get<string>(inikey); break; case VARIANT_TYPE_STRING: out.string_value = pt.get<string>(inikey); break; } } catch (boost::property_tree::ptree_error) { ret = false; } TRACE_RETURN(ret); return ret; } bool IniConfigurator::set_value(const std::string &key, Variant &value) { bool ret = true; boost::property_tree::ptree::path_type inikey = path(key); try { switch(value.type) { case VARIANT_TYPE_INT: pt.put(inikey, value.int_value); break; case VARIANT_TYPE_BOOL: pt.put(inikey, value.bool_value); break; case VARIANT_TYPE_DOUBLE: pt.put(inikey, value.double_value); break; case VARIANT_TYPE_NONE: case VARIANT_TYPE_STRING: pt.put(inikey, value.string_value); break; } } catch (boost::property_tree::ptree_error) { ret = false; } return ret; } boost::property_tree::ptree::path_type IniConfigurator::path(const string &key) const { string new_key = key; bool first = true; for (auto &c : new_key) { if (c == '/') { if (!first) { c = '.'; } first = false; } } return boost::property_tree::ptree::path_type(new_key, '/'); }
rubo77/workrave
libs/config/src/IniConfigurator.cc
C++
gpl-3.0
4,294
/*! \file \brief Header of the bt_peerpick_casto_t */ #ifndef __NEOIP_BT_PEERPICK_CASTO_HPP__ #define __NEOIP_BT_PEERPICK_CASTO_HPP__ /* system include */ /* local include */ #include "neoip_bt_peerpick_vapi.hpp" #include "neoip_bt_peerpick_casto_profile.hpp" #include "neoip_copy_ctor_checker.hpp" #include "neoip_namespace.hpp" NEOIP_NAMESPACE_BEGIN // list of forward declaration class bt_swarm_t; class bt_err_t; class bt_reqauth_type_t; class delay_t; /** \brief Handle the scheduling for the bt_swarm_t connection */ class bt_peerpick_casto_t : NEOIP_COPY_CTOR_DENY, public bt_peerpick_vapi_t { private: bt_swarm_t * m_bt_swarm; //!< backpointer to the linked bt_swarm_t bt_peerpick_casto_profile_t m_profile; //!< the profile to use /*************** peer selection ***************************************/ bool peer_select_new_fast(const bt_reqauth_type_t &reqauth_type, const delay_t &expire_delay) throw(); bool peer_select_new_rand(const bt_reqauth_type_t &reqauth_type, const delay_t &expire_delay) throw(); void peer_select_update() throw(); public: /*************** ctor/dtor ***************************************/ bt_peerpick_casto_t() throw(); ~bt_peerpick_casto_t() throw(); /*************** Setup function ***************************************/ bt_peerpick_casto_t& profile(const bt_peerpick_casto_profile_t &profile) throw(); bt_err_t start(bt_swarm_t *m_bt_swarm) throw(); /*************** Query function ***************************************/ const bt_peerpick_casto_profile_t & profile() const throw() { return m_profile; } bt_swarm_t * bt_swarm() const throw() { return m_bt_swarm; } /*************** bt_peerpick_vapi_t *******************************/ void peerpick_update() throw(); }; NEOIP_NAMESPACE_END #endif /* __NEOIP_BT_PEERPICK_CASTO_HPP__ */
jeromeetienne/neoip
src/neoip_bt_plugin/peerpick/impl/casto/neoip_bt_peerpick_casto.hpp
C++
gpl-3.0
1,844
Bitrix 17.0.9 Business Demo = b95aa04d19e533ee4f71408404ebb4c2
gohdan/DFC
known_files/hashes/bitrix/modules/sale/install/components/bitrix/sale.products.gift.section/lang/ru/.description.php
PHP
gpl-3.0
63
/***************************************************************************\ * Filename : evaluation.hh * Author : Mario Stanke * Email : stanke@math.uni-goettingen.de * * Copyright: (C) 2002 by Mario Stanke * * Description: * * * Date | Author | Changes *------------+---------------+--------------------------------- * 19.06.2002 | Mario Stanke | Creation of the file * 11.04.2007 | Mario Stanke | Evaluation of the pred. of the transcription termination site (tts) \**************************************************************************/ #ifndef _EVALUATION_HH #define _EVALUATION_HH // project includes #include "types.hh" #include "gene.hh" #include "extrinsicinfo.hh" // standard C/C++ includes #include <list> #include <vector> #define MAXUTRDIST 5000 class Evaluation { public: Evaluation(){ nukTP = nukFP = nukFN = nukFPinside = 0; nucUTP = nucUFP = nucUFN = nucUFPinside = 0; exonTP = exonFP_partial = exonFP_overlapping = exonFP_wrong = 0; exonFN_partial = exonFN_overlapping = exonFN_wrong = 0; UTRexonTP = UTRexonFP = UTRexonFN = 0; UTRoffThresh = 20; geneTP = geneFN = 0; numPredExons = numAnnoExons = 0; numPredUTRExons = numAnnoUTRExons = 0; numUniquePredExons = numUniqueAnnoExons = 0; numUniquePredUTRExons = numUniqueAnnoUTRExons = 0; numPredGenes = numAnnoGenes = 0; numDataSets = 0; longestPredIntronLen = 0; tssDist = new int[MAXUTRDIST+1]; for (int i=0; i<= MAXUTRDIST; i++) tssDist[i] = 0; numTotalPredTSS = numTSS = 0; ttsDist = new int[MAXUTRDIST+1]; for (int i=0; i<= MAXUTRDIST; i++) ttsDist[i] = 0; numTotalPredTTS = numTTS = 0; leftFlankEnd = rightFlankBegin = -1; } ~Evaluation(){ if (tssDist) delete [] tssDist; if (ttsDist) delete [] ttsDist; }; void addToEvaluation(Gene* prediction, Gene *database, Strand strand, Double quotient = -1.0); void addToEvaluation(Gene* predictedGeneList, Gene* annotatedGeneList); void finishEvaluation(); void print(); void printQuotients(); private: /* * Quick evaluation is fast but requires that both gene lists * */ void evaluateQuickOnNucleotideLevel(State* const predictedExon, int curPredBegin, State* const annotatedExon, int curAnnoBegin); void evaluateQuickOnExonLevel(State* predictedExon, State* annotatedExon); void evaluateQuickOnGeneLevel(Gene* const predictedGeneList, Gene* const annotatedGeneList); void evaluateOnNucleotideLevel(list<State> *predictedExon, list<State> *annotatedExon, bool UTR=false); void evaluateOnExonLevel(list<State> *predictedExon, list<State> *annotatedExon, bool UTR=false); void evaluateOnGeneLevel(Gene* const predictedGeneList, Gene* const annotatedGeneList); void evaluateOnUTRLevel(Gene* const predictedGeneList, Gene* const annotatedGeneList); public: // nucleotide level int nukTP, nukFP, nukFN, nukFPinside; // false positive coding base inside gene area (as opposed to in flanking regions) int nucUTP, nucUFP, nucUFN, // UTR bases nucUFPinside; // false positive noncoding base inside gene area (as opposed to in flanking regions) double nukSens, nukSpec; // coding base sensitivity and specifity double nucUSens, nucUSpec; // non-coding base sensitivity and specifity double exonSens, exonSpec; // coding exon sensitivity and specificity double UTRexonSens, UTRexonSpec; // exon sensitivity and specificity double geneSens, geneSpec; // gene sensitivity and specifity private: //TP = true positive, FP = false positive, FN = false negative int leftFlankEnd, rightFlankBegin; list<Double> quotients; int longestPredIntronLen; // exon level int numPredExons, numAnnoExons; int numUniquePredExons, numUniqueAnnoExons; int exonTP, exonFP, exonFP_partial, // predicted exon unequal to but included in an annotated exon exonFP_overlapping, exonFP_wrong, exonFN, exonFN_partial, // annotated exon unequal to but included in a predicted exon exonFN_overlapping, exonFN_wrong; // gene level int geneTP, geneFP, geneFN; int numPredGenes, numAnnoGenes; // UTR level int *tssDist; // array that holds for each distance the number of predicted TSS that is off by this distance int numTSS; // number of gene pairs (anno, pred) with identical translation start and where both have an annotated TSS int numTotalPredTSS; double meanTssDist; int medianTssDist; int *ttsDist; // array that holds for each distance the number of predicted TTS that is off by this distance int numTTS; // number of gene pairs (anno, pred) with identical stop codon and where both have an annotated TTS int numTotalPredTTS; double meanTtsDist; int medianTtsDist; int numPredUTRExons, numAnnoUTRExons; int numUniquePredUTRExons, numUniqueAnnoUTRExons; int UTRexonTP, UTRexonFP, UTRexonFN; int UTRoffThresh; // count UTR exon as correct, if one end is exact and the other end at most this many bp off /* * data members for the "Burge-Karlin"-Method computing first the * specifity and sensitivity for each sequence and then taking their * means afterwards */ int numDataSets; // nukleotide level int nukTPBK, nukFPBK, nukFPBKinside, nukFNBK; double nukSensBK, nukSpecBK; // sensitivity and specifity // exon level int exonTPBK, exonFPBK, exonFNBK; double exonSpecBK, exonSensBK; // exon specifity and sensitivity }; /* * predictAndEvaluate * * Predict genes on the given set of annotated sequences given the current parameters. * Then evaluate the accuracy against the given annotation. */ Evaluation* predictAndEvaluate(vector<AnnoSequence*> trainGeneList, FeatureCollection &extrinsicFeatures); #endif // _EVALUATION_HH
NGSchool2016/ngschool2016-materials
src/augustus-3.0.2/include/evaluation.hh
C++
gpl-3.0
5,852
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using System.Xml.Linq; using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.Configuration; using RoCMS.Base; using RoCMS.Base.Helpers; using RoCMS.Helpers; using RoCMS.Logging; using RoCMS.Shop.Contract.Models; using RoCMS.Shop.Contract.Services; using RoCMS.Shop.Services; using RoCMS.Web.Contract.Models; using RoCMS.Web.Contract.Services; using RoCMS.Web.Services; using Image = System.Drawing.Image; namespace SynWeb.Teaworld.Import { class Program { private static List<ImportGoodsItem> _goods = new List<ImportGoodsItem>(); private static AlbumService _albumService; private static IShopService _shopService; private static IImageService _imageService; private static IPageService _pageService; private static ILogService _logService; public class AltShopService : ShopContextService { public void RemoveHtmlFromDescriptions() { using (var db = Context) { foreach (var goodsItem in db.GoodsSet) { string descr = goodsItem.Description; descr = Regex.Replace(descr, HTML_TAG_PATTERN, string.Empty, RegexOptions.Singleline); descr = HttpUtility.HtmlDecode(descr); if (descr.Contains("<") || descr.Contains("&")) { Console.WriteLine(descr); } else { goodsItem.Description = descr; } } db.SaveChanges(); } } protected override int CacheExpirationInMinutes { get { throw new NotImplementedException(); } } public void FillSearchDescriptions() { IList<GoodsItem> goods; int[] ids; using (var db = Context) { ids = db.GoodsSet.Select(g => g.GoodsId).ToArray(); } ids = ids.Where(x => x > 2000).ToArray(); foreach (var id in ids) { try { using (var db = Context) { var goodsItem = db.GoodsSet.Find(id); goodsItem.SearchDescription = SearchHelper.ToSearchIndexText(goodsItem.HtmlDescription); db.SaveChanges(); } Console.WriteLine("GoodsId: {0} of {1}", id, ids.Length); } catch { } } // foreach (var item in goods) // { // _shopService.UpdateGoods(item); // } } } private static void UpdatePageSearchContent() { IList<PageInfo> pageInfos = _pageService.GetPagesInfo(); IList<Page> pages = new List<Page>(); foreach (var pageInfo in pageInfos) { pages.Add(_pageService.GetPage(pageInfo.RelativeUrl)); } foreach (var page in pages) { _pageService.UpdatePage(page); } } static void Main(string[] args) { InitUnity(); InitServices(); //FillGoods(); //ExportGoodsToDB(); //var service = new AltShopService(); //service.RemoveHtmlFromDescriptions(); //service.FillSearchDescriptions(); //Console.WriteLine("Goods ok!"); //UpdatePageSearchContent(); //ExportImages(); //ExportThumbs(); CreateThumbs(); Console.WriteLine("Everything ok!"); Console.ReadLine(); } static void CreateThumbs() { const string IMAGES_DIR = "Images"; const string THUMBS_DIR = "Thumbnails"; if (!Directory.Exists(THUMBS_DIR)) { Directory.CreateDirectory(THUMBS_DIR); } var jpgs = Directory.GetFiles(IMAGES_DIR, "*.jpg", SearchOption.AllDirectories); var gifs = Directory.GetFiles(IMAGES_DIR, "*.gif", SearchOption.AllDirectories); var pngs = Directory.GetFiles(IMAGES_DIR, "*.png", SearchOption.AllDirectories); foreach (var jpg in jpgs) { CreateThumbnail(jpg, "jpg"); } foreach (var gif in gifs) { CreateThumbnail(gif, "gif"); } foreach (var png in pngs) { CreateThumbnail(png, "png"); } } private static void CreateThumbnail(string path, string extension) { Image thumb = Image.FromFile(path); int thumbnailHeight = 200; int thumbnailWidth = 300; if ((float)thumb.Height <= thumbnailHeight && (float)thumb.Width <= thumbnailWidth) { Image temp = new Bitmap(thumb.Width, thumb.Height); using (var g = Graphics.FromImage(temp)) { g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(thumb, 0, 0, temp.Width, temp.Height); } thumb = (Image)temp.Clone(); } else { // Масштабирование по высоте if ((float)thumb.Height > thumbnailHeight) { float scale = thumbnailHeight / (float)thumb.Height; Image temp = new Bitmap((int)(thumb.Width * scale), thumbnailHeight); using (var g = Graphics.FromImage(temp)) { g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(thumb, 0, 0, temp.Width, temp.Height); } thumb = (Image)temp.Clone(); } // Масштабирование по ширине if ((float)thumb.Width > thumbnailWidth) { float scale = thumbnailWidth / (float)thumb.Width; Image temp = new Bitmap(thumbnailWidth, (int)(thumb.Height * scale)); using (var g = Graphics.FromImage(temp)) { g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(thumb, 0, 0, temp.Width, temp.Height); } thumb = (Image)temp.Clone(); } } ImageFormat format; switch (extension) { case "jpg": format = ImageFormat.Jpeg; break; case "gif": format = ImageFormat.Gif; break; case "png": format = ImageFormat.Png; break; default: throw new ArgumentException("extension"); } string thumbPath = path.Replace("Images", "Thumbnails"); var dirPath = String.Join("\\", thumbPath.Split('\\').Where(x => !x.Contains(".")).ToArray()); if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } thumb.Save(thumbPath, format); } //private static void ExportImages() //{ // const string IMAGES_DIR = "Images"; // if (!Directory.Exists(IMAGES_DIR)) // { // Directory.CreateDirectory(IMAGES_DIR); // } // var imageIds = _imageService.GetAllImageInfos().Select(x => x.ImageId); // foreach (var imageId in imageIds) // { // string first = imageId.Substring(0, 1).ToLower(); // string second = imageId.Substring(1, 1).ToLower(); // var img = _imageService.GetImage(imageId); // if (!Directory.Exists(Path.Combine(IMAGES_DIR, first))) // { // Directory.CreateDirectory(Path.Combine(IMAGES_DIR, first)); // } // string finalDir = Path.Combine(IMAGES_DIR, first, second); // if (!Directory.Exists(finalDir)) // { // Directory.CreateDirectory(finalDir); // } // //const string MIMETYPE_JPG = "image/jpeg"; // //const string MIMETYPE_PNG = "image/png"; // //const string MIMETYPE_GIF = "image/gif"; // string extension = img.ContentType.Replace(@"image/", "").Replace("jpeg", "jpg"); // string fname = imageId.ToLower() + "." + extension; // File.WriteAllBytes(Path.Combine(finalDir, fname), img.Content); // } //} private static void InitServices() { //_shopService = new ShopService(); //_imageService = new ImageService(_logService); //_albumService = new AlbumService(_imageService, _logService); //_pageService = new PageService(); //_articleService = new ArticleService(_pageService); //_logService = new LogService(); } private static void ExportGoodsToDB() { const string albumName = "Импортированные товары"; int albumId; if (_albumService.GetAlbums().Any(x => x.Name.Equals(albumName))) { albumId = _albumService.GetAlbums().First(x => x.Name.Equals(albumName)).AlbumId; } else { albumId = _albumService.CreateAlbum(albumName); } foreach (var goodsItem in _goods) { var i = new GoodsItem() { Article = goodsItem.Article, HtmlDescription = goodsItem.Description, //Description = RemoveHtml(goodsItem.Description), Categories = new[] {new IdNamePair<int>() {ID = goodsItem.CategoryId}}, Name = goodsItem.Name }; i.Description = ""; throw new NotImplementedException("Description"); try { i.Price = int.Parse(goodsItem.Price); } catch { if (goodsItem.Price.Contains(" за 100 г.")) { decimal p = decimal.Parse(goodsItem.Price.Replace(" за 100 г.", "")); i.Price = p; //Пачка i.Packs.Add(new GoodsPack() {PackInfo = new Pack() {PackId = 1}}); i.Packs.Add(new GoodsPack() {PackInfo = new Pack() {PackId = 2}}); i.Packs.Add(new GoodsPack() {PackInfo = new Pack() {PackId = 3}}); i.Packs.Add(new GoodsPack() {PackInfo = new Pack() {PackId = 4}}); } if (goodsItem.Price.Contains(" за 250 г.")) { decimal p = decimal.Parse(goodsItem.Price.Replace(" за 250 г.", "")); p = Decimal.Divide(p, 2.5m); i.Price = p; //Пачка i.Packs.Add(new GoodsPack() {PackInfo = new Pack() {PackId = 1}}); i.Packs.Add(new GoodsPack() {PackInfo = new Pack() {PackId = 2}}); i.Packs.Add(new GoodsPack() {PackInfo = new Pack() {PackId = 3}}); i.Packs.Add(new GoodsPack() {PackInfo = new Pack() {PackId = 4}}); } } try { var img = new RoCMS.Web.Contract.Models.Image(); var fStream = File.OpenRead(goodsItem.PhotoUrl); img.Size = fStream.Length; byte[] bytes = new byte[fStream.Length]; fStream.Read(bytes, 0, (int) fStream.Length); const string MIMETYPE_JPG = "image/jpeg"; const string MIMETYPE_PNG = "image/png"; string fileType = goodsItem.PhotoUrl.Split('.').Last(); img.Content = bytes; img.ContentType = fileType == "jpg" ? MIMETYPE_JPG : MIMETYPE_PNG; var imageId = _imageService.UploadImage(img, goodsItem.PhotoUrl); _albumService.AddImageToAlbum(albumId, imageId); i.MainImageId = imageId; } catch { Console.WriteLine("Failed to find image for {0}", i.Name); } try { _shopService.CreateGoods(i); } catch { Console.WriteLine("Failed to add {0}", i.Name); } } } const string HTML_TAG_PATTERN = "<.*?>"; private static void InitUnity() { IUnityContainer container = new UnityContainer(); //RegisterControllers(container); container.LoadConfiguration(); DependencyResolver.SetResolver(new UnityDependencyResolver(container)); } private static void FillGoods() { XDocument doc = XDocument.Load("../../goods.xml"); XNode node = doc.Root.FirstNode; while (node.NextNode != null) //<Worksheet> { node = node.NextNode; } node = ((XElement)node).FirstNode; //<Table> var rows = ((XElement)node).Elements().Where(x => x.Name.LocalName == "Row"); Console.WriteLine(rows.Count()); foreach (var row in rows) { var item = new ImportGoodsItem(); var n = (XElement)row.FirstNode; //<Cell> var data = (XElement)n.FirstNode; //<Data> item.Id = Convert.ToInt32(data.Value); n = (XElement)n.NextNode; data = (XElement)n.FirstNode; item.Name = data.Value; n = (XElement)n.NextNode; data = (XElement)n.FirstNode; item.Article = data.Value; n = (XElement)n.NextNode; data = (XElement)n.FirstNode; item.Description = data.Value; n = (XElement)n.NextNode; data = (XElement)n.FirstNode; try { item.CategoryId = Convert.ToInt32(data.Value); } catch (FormatException) { continue; } n = (XElement)n.NextNode; data = (XElement)n.FirstNode; item.Price = data.Value; n = (XElement)n.NextNode; data = (XElement)n.FirstNode; item.PhotoUrl = Path.Combine("C:\\", data.Value.Replace('/', '\\')); _goods.Add(item); } } } struct ImportGoodsItem { public int Id; public string Name; public string Article; public string Description; public int CategoryId; public string Price; public string PhotoUrl; } }
synweb/rocms
Shop/SynWeb.Teaworld.Import/Program.cs
C#
gpl-3.0
16,428
package de.gdoeppert.sky.model; /* Android App Sky * * (c) Gerhard Döppert * * SkyReigen.apk is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * SkyReigen.apk is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ public class PlanetPositionEcl { double time; private double longitude; double latitude; private double perihelion; public PlanetPositionEcl(double t, double lo, double la, double ph) { time = t; setLongitude(lo); latitude = la; setPerihelion(ph); } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } public double getPerihelion() { return perihelion; } public void setPerihelion(double perihelion) { this.perihelion = perihelion; } }
gdoepp/skyreigen
src/main/java/de/gdoeppert/sky/model/PlanetPositionEcl.java
Java
gpl-3.0
1,442
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Hashle class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Do not swallow errors in after_commit/after_rollback callbacks. config.active_record.raise_in_transactional_callbacks = true end end
mlterpstra92/Hashle
config/application.rb
Ruby
gpl-3.0
1,113
/* * Copyright 2017 Anton Tananaev (anton@traccar.org) * Copyright 2017 Andrey Kunitsyn (andrey@traccar.org) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ Ext.define('Traccar.view.dialog.SendCommand', { extend: 'Traccar.view.dialog.Base', requires: [ 'Traccar.view.dialog.SendCommandController' ], controller: 'sendCommand', title: Strings.commandTitle, items: [{ xtype: 'combobox', reference: 'commandsComboBox', fieldLabel: Strings.deviceCommand, displayField: 'description', valueField: 'id', store: 'DeviceCommands', queryMode: 'local', editable: false, allowBlank: false, listeners: { select: 'onCommandSelect' } }, { xtype: 'form', listeners: { validitychange: 'onValidityChange' }, items: [{ xtype: 'fieldset', reference: 'newCommandFields', disabled: true, items: [{ xtype: 'checkboxfield', name: 'textChannel', reference: 'textChannelCheckBox', inputValue: true, uncheckedValue: false, fieldLabel: Strings.commandSendSms, listeners: { change: 'onTextChannelChange' } }, { xtype: 'combobox', name: 'type', reference: 'commandType', fieldLabel: Strings.sharedType, store: 'CommandTypes', displayField: 'name', valueField: 'type', editable: false, allowBlank: false, listeners: { change: 'onTypeChange' } }, { xtype: 'fieldcontainer', reference: 'parameters' }] }] }], buttons: [{ xtype: 'tbfill' }, { glyph: 'xf093@FontAwesome', tooltip: Strings.sharedSend, tooltipType: 'title', minWidth: 0, disabled: true, reference: 'sendButton', handler: 'onSendClick' }, { glyph: 'xf00d@FontAwesome', tooltip: Strings.sharedCancel, tooltipType: 'title', minWidth: 0, handler: 'closeView' }] });
tananaev/traccar-web
web/app/view/dialog/SendCommand.js
JavaScript
gpl-3.0
2,976
<?php /** * Argument class * @author Arnia (dev@karybu.org) * @package /classes/xml/xmlquery/argument * @version 0.1 */ class Argument { /** * argument value * @var mixed */ var $value; /** * argument name * @var string */ var $name; /** * argument type * @var string */ var $type; /** * result of argument type check * @var bool */ var $isValid; /** * error message * @var Object */ var $errorMessage; /** * column operation */ var $column_operation; /** * Check if arg value is user submnitted or default * @var mixed */ var $uses_default_value; /** * Caches escaped and toString value so that the parsing won't happen multiple times * @var mixed */ var $_value; // /** * constructor * @param string $name * @param mixed $value * @return void */ function Argument($name, $value) { $this->value = $value; $this->name = $name; $this->isValid = true; } function getType() { if (isset($this->type)) { return $this->type; } if (is_string($this->value)) { return 'column_name'; } return 'number'; } function setColumnType($value) { $this->type = $value; } function setColumnOperation($operation) { $this->column_operation = $operation; } function getName() { return $this->name; } function getValue() { if (!isset($this->_value)) { $value = $this->getEscapedValue(); $this->_value = $this->toString($value); } return $this->_value; } function getColumnOperation() { return $this->column_operation; } function getEscapedValue() { return $this->escapeValue($this->value); } function getUnescapedValue() { if ($this->value === 'null') { return null; } return $this->value; } /** * mixed value to string * @param mixed $value * @return string */ function toString($value) { if (is_array($value)) { if (count($value) === 0) { return ''; } if (count($value) === 1 && $value[0] === '') { return ''; } return '(' . implode(',', $value) . ')'; } return $value; } /** * escape value * @param mixed $value * @return mixed */ function escapeValue($value) { $column_type = $this->getType(); if ($column_type == 'column_name') { $oDB = DB::getInstance(); $dbParser = $oDB->getParser(); return $dbParser->parseExpression($value); } if (!isset($value)) { return null; } $columnTypeList = array('date' => 1, 'varchar' => 1, 'char' => 1, 'text' => 1, 'bigtext' => 1); if (isset($columnTypeList[$column_type])) { if (!is_array($value)) { $value = $this->_escapeStringValue($value); } else { $total = count($value); for ($i = 0; $i < $total; $i++) { $value[$i] = $this->_escapeStringValue($value[$i]); } //$value[$i] = '\''.$value[$i].'\''; } } if ($this->uses_default_value) { return $value; } if ($column_type == 'number') { if (is_array($value)) { foreach ($value AS $key => $val) { if (isset($val) && $val !== '') { $value[$key] = (int)$val; } } } else { $value = (int)$value; } } return $value; } /** * escape string value * @param string $value * @return string */ function _escapeStringValue($value) { // Remove non-utf8 chars. $regex = '@((?:[\x00-\x7F]|[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}){1,100})|([\xF0-\xF7][\x80-\xBF]{3})|([\x80-\xBF])|([\xC0-\xFF])@x'; $value = preg_replace_callback($regex, array($this, 'utf8Replacer'), $value); $db = DB::getInstance(); $value = $db->addQuotes($value); return '\'' . $value . '\''; } function utf8Replacer($captures) { if (!empty($captures[1])) { // Valid byte sequence. Return unmodified. return $captures[1]; } elseif (!empty($captures[2])) { // Remove user defined area if ("\xF3\xB0\x80\x80" <= $captures[2]) { return; } return $captures[2]; } else { return; } } function isValid() { return $this->isValid; } function isColumnName() { $type = $this->getType(); $value = $this->getUnescapedValue(); if ($type == 'column_name') { return true; } if ($type == 'number' && is_null($value)) { return false; } if ($type == 'number' && !is_numeric($value) && $this->uses_default_value) { return true; } return false; } function getErrorMessage() { return $this->errorMessage; } function ensureDefaultValue($default_value) { if (!isset($this->value) || $this->value == '') { $this->value = $default_value; $this->uses_default_value = true; } } /** * check filter by filter type * @param string $filter_type * @return void */ function checkFilter($filter_type) { if (isset($this->value) && $this->value != '') { global $lang; $val = $this->value; $key = $this->name; switch ($filter_type) { case 'email' : case 'email_address' : if (!preg_match('/^[\w-]+((?:\.|\+|\~)[\w-]+)*@[\w-]+(\.[\w-]+)+$/is', $val)) { $this->isValid = false; $this->errorMessage = new Object(-1, sprintf( $lang->filter->invalid_email, $lang->{$key} ? $lang->{$key} : $key )); } break; case 'homepage' : if (!preg_match('/^(http|https)+(:\/\/)+[0-9a-z_-]+\.[^ ]+$/is', $val)) { $this->isValid = false; $this->errorMessage = new Object(-1, sprintf( $lang->filter->invalid_homepage, $lang->{$key} ? $lang->{$key} : $key )); } break; case 'userid' : case 'user_id' : if (!preg_match('/^[a-zA-Z]+([\._0-9a-zA-Z]+)*$/is', $val)) { $this->isValid = false; $this->errorMessage = new Object(-1, sprintf( $lang->filter->invalid_userid, $lang->{$key} ? $lang->{$key} : $key )); } break; case 'number' : case 'numbers' : if (is_array($val)) { $val = join(',', $val); } if (!preg_match('/^(-?)[0-9]+(,\-?[0-9]+)*$/is', $val)) { $this->isValid = false; $this->errorMessage = new Object(-1, sprintf( $lang->filter->invalid_number, !empty($lang->{$key}) ? $lang->{$key} : $key )); } break; case 'alpha' : if (!preg_match('/^[a-z]+$/is', $val)) { $this->isValid = false; $this->errorMessage = new Object(-1, sprintf( $lang->filter->invalid_alpha, $lang->{$key} ? $lang->{$key} : $key )); } break; case 'alpha_number' : if (!preg_match('/^[0-9a-z]+$/is', $val)) { $this->isValid = false; $this->errorMessage = new Object(-1, sprintf( $lang->filter->invalid_alpha_number, $lang->{$key} ? $lang->{$key} : $key )); } break; } } } function checkMaxLength($length) { if ($this->value && (strlen($this->value) > $length)) { global $lang; $this->isValid = false; $key = $this->name; $this->errorMessage = new Object(-1, sprintf( $lang->filter->outofrange, $lang->{$key} ? $lang->{$key} : $key )); } } function checkMinLength($length) { if ($this->value && (strlen($this->value) < $length)) { global $lang; $this->isValid = false; $key = $this->name; $this->errorMessage = new Object(-1, sprintf( $lang->filter->outofrange, $lang->{$key} ? $lang->{$key} : $key )); } } function checkNotNull() { if (!isset($this->value)) { global $lang; $this->isValid = false; $key = $this->name; $this->errorMessage = new Object(-1, sprintf($lang->filter->isnull, !empty($lang->{$key}) ? $lang->{$key} : $key)); } } } ?>
arnia/Karybu
classes/xml/xmlquery/argument/Argument.class.php
PHP
gpl-3.0
9,975
/* --- * Matrix class supporting common operations such as multiplication, inverse, determinant. * Derived from: https://www.cs.rochester.edu/~brown/Crypto/assts/projects/adj.html * and https://www.quantstart.com/articles/Matrix-Classes-in-C-The-Source-File * --- */ #include "TMTrackTrigger/TMTrackFinder/interface/Matrix.h" #include <iostream> #include <cassert> // Parameter Constructor template<typename T> Matrix<T>::Matrix(){ mat.resize(0); rows = 0; cols = 0; } template<typename T> Matrix<T>::Matrix(unsigned _rows, unsigned _cols, const T& _initial) { mat.resize(_rows); for (unsigned i=0; i<mat.size(); i++) { mat[i].resize(_cols, _initial); } rows = _rows; cols = _cols; } // Copy Constructor template<typename T> Matrix<T>::Matrix(const Matrix<T>& rhs) { mat = rhs.mat; rows = rhs.get_rows(); cols = rhs.get_cols(); } // (Virtual) Destructor template<typename T> Matrix<T>::~Matrix() {} // Assignment Operator template<typename T> Matrix<T>& Matrix<T>::operator=(const Matrix<T>& rhs) { if (&rhs == this) return *this; unsigned new_rows = rhs.get_rows(); unsigned new_cols = rhs.get_cols(); mat.resize(new_rows); for (unsigned i=0; i<mat.size(); i++) { mat[i].resize(new_cols); } for (unsigned i=0; i<new_rows; i++) { for (unsigned j=0; j<new_cols; j++) { mat[i][j] = rhs(i, j); } } rows = new_rows; cols = new_cols; return *this; } // Addition of two matrices template<typename T> Matrix<T> Matrix<T>::operator+(const Matrix<T>& rhs) { Matrix result(rows, cols, 0.0); for (unsigned i=0; i<rows; i++) { for (unsigned j=0; j<cols; j++) { result(i,j) = this->mat[i][j] + rhs(i,j); } } return result; } // Cumulative addition of this matrix and another template<typename T> Matrix<T>& Matrix<T>::operator+=(const Matrix<T>& rhs) { unsigned rows = rhs.get_rows(); unsigned cols = rhs.get_cols(); for (unsigned i=0; i<rows; i++) { for (unsigned j=0; j<cols; j++) { this->mat[i][j] += rhs(i,j); } } return *this; } // Subtraction of this matrix and another template<typename T> Matrix<T> Matrix<T>::operator-(const Matrix<T>& rhs) { unsigned rows = rhs.get_rows(); unsigned cols = rhs.get_cols(); Matrix result(rows, cols, 0.0); for (unsigned i=0; i<rows; i++) { for (unsigned j=0; j<cols; j++) { result(i,j) = this->mat[i][j] - rhs(i,j); } } return result; } // Cumulative subtraction of this matrix and another template<typename T> Matrix<T>& Matrix<T>::operator-=(const Matrix<T>& rhs) { unsigned rows = rhs.get_rows(); unsigned cols = rhs.get_cols(); for (unsigned i=0; i<rows; i++) { for (unsigned j=0; j<cols; j++) { this->mat[i][j] -= rhs(i,j); } } return *this; } // Left multiplication of this matrix and another template<typename T> Matrix<T> Matrix<T>::operator*(const Matrix<T>& rhs) { assert(this->cols == rhs.get_rows()); unsigned rRows = rhs.get_rows(); unsigned rCols = rhs.get_cols(); unsigned lRows = this->rows; unsigned lCols = this->cols; Matrix result(lRows, rCols, 0.0); for(unsigned i=0; i < lRows; i++){ for(unsigned j = 0; j < rCols; j++){ for(unsigned k = 0; k < lCols; k++){ result(i,j) += this->mat[i][k] * rhs.mat[k][j]; } } } return result; } // Cumulative left multiplication of this matrix and another template<typename T> Matrix<T>& Matrix<T>::operator*=(const Matrix<T>& rhs) { Matrix result = (*this) * rhs; (*this) = result; return *this; } // Calculate a transpose of this matrix template<typename T> Matrix<T> Matrix<T>::transpose() { Matrix result(cols, rows, 0.0); for (unsigned i=0; i<cols; i++) { for (unsigned j=0; j<rows; j++) { result(i,j) = this->mat[j][i]; } } return result; } // Recursively calculate the determinant template<typename T> T Matrix<T>::determinant(){ T det = 0; if(rows < 1){ std::cerr << "Can't have determinant of matrix with " << rows << " rows." << std::endl; } else if (rows == 1){ det = this->mat[0][0]; } else if (rows == 2){ det = this->mat[0][0] * this->mat[1][1] - this->mat[1][0] * this->mat[0][1]; }else{ for(unsigned i = 0; i < rows; i++){ Matrix m(rows-1, cols-1, 0); for(unsigned j = 1; j < rows; j++){ unsigned k = 0; for(unsigned l =0; l < rows; l++){ if(l == i) continue; m(j-1,k) = this->mat[j][l]; k++; } } T sign; if ((i+2)%2 == 0) sign = 1; else sign = -1; det += sign * this->mat[0][i] * m.determinant(); } } return(det); } template<typename T> Matrix<T> Matrix<T>::cofactor(){ Matrix result(rows, cols, 0); Matrix c(rows-1, cols-1, 0); if(rows != cols){ std::cerr << "Can only compute cofactor of square matrix." << std::endl; return result; } for(unsigned j = 0; j < rows; j++){ for(unsigned i = 0; i < rows; i++){ unsigned i1 = 0; for(unsigned ii = 0; ii < rows; ii++){ if(ii==i) continue; unsigned j1 = 0; for(unsigned jj = 0; jj< rows; jj++){ if(jj == j) continue; c(i1,j1) = this->mat[ii][jj]; j1++; } i1++; } T det = c.determinant(); T sign; if ((i+j+2)%2 == 0) sign = 1; else sign = -1; result(i,j) = sign * det; } } return result; } template<typename T> Matrix<T> Matrix<T>::inverse(){ if(rows != cols){ std::cerr << "Matrix: cannot invert matrix with " << rows << " rows and " << cols << "cols" << std::endl; } if(this->determinant() == 0) std::cerr << "Matrix with 0 determinant has no inverse." << std::endl; Matrix result = this->cofactor().transpose() / this->determinant(); return result; } // Matrix/scalar addition template<typename T> Matrix<T> Matrix<T>::operator+(const T& rhs) { Matrix result(rows, cols, 0.0); for (unsigned i=0; i<rows; i++) { for (unsigned j=0; j<cols; j++) { result(i,j) = this->mat[i][j] + rhs; } } return result; } // Matrix/scalar subtraction template<typename T> Matrix<T> Matrix<T>::operator-(const T& rhs) { Matrix result(rows, cols, 0.0); for (unsigned i=0; i<rows; i++) { for (unsigned j=0; j<cols; j++) { result(i,j) = this->mat[i][j] - rhs; } } return result; } // Matrix/scalar multiplication template<typename T> Matrix<T> Matrix<T>::operator*(const T& rhs) { Matrix result(rows, cols, 0.0); for (unsigned i=0; i<rows; i++) { for (unsigned j=0; j<cols; j++) { result(i,j) = this->mat[i][j] * rhs; } } return result; } // Matrix/scalar division template<typename T> Matrix<T> Matrix<T>::operator/(const T& rhs) { Matrix result(rows, cols, 0.0); for (unsigned i=0; i<rows; i++) { for (unsigned j=0; j<cols; j++) { result(i,j) = this->mat[i][j] / rhs; } } return result; } // Multiply a matrix with a vector template<typename T> std::vector<T> Matrix<T>::operator*(const std::vector<T>& rhs) { std::vector<T> result(this->rows, 0.0); for (unsigned i=0; i<rows; i++) { for (unsigned j=0; j<cols; j++) { result[i] += this->mat[i][j] * rhs[j]; } } return result; } // Obtain a vector of the diagonal elements template<typename T> std::vector<T> Matrix<T>::diag_vec() { std::vector<T> result(rows, 0.0); for (unsigned i=0; i<rows; i++) { result[i] = this->mat[i][i]; } return result; } // Access the individual elements template<typename T> T& Matrix<T>::operator()(const unsigned& row, const unsigned& col) { return this->mat[row][col]; } // Access the individual elements (const) template<typename T> const T& Matrix<T>::operator()(const unsigned& row, const unsigned& col) const { return this->mat[row][col]; } // Get the number of rows of the matrix template<typename T> unsigned Matrix<T>::get_rows() const { return this->rows; } // Get the number of columns of the matrix template<typename T> unsigned Matrix<T>::get_cols() const { return this->cols; } template<typename T> void Matrix<T>::print(){ for(unsigned i=0; i < this->rows; i++){ for(unsigned j=0; j < this->cols; j++){ std::cout << this->mat[i][j] << ", "; } std::cout << std::endl; } } template class Matrix<double>; template class Matrix<float>; template class Matrix<int>;
luigicalligaris/uk-track-trigger
TMTrackTrigger/TMTrackFinder/src/Matrix.cc
C++
gpl-3.0
11,371
<?php $menu_asincrono = true; ?> <?php if (!in_array("menus", $array_help_close)): ?> <div class="help" data-name="menus"> <h4>Información</h4> <p>Dependiendo de la plantilla instalada podrás editar los <strong>Menús</strong> y sus elementos.</p> </div> <?php endif ?> <script> $(document).ready(function() { // SELECT ALL ITEMS CHECKBOXS $('#select_all').change(function(){ var checkboxes = $(this).closest('table').find(':checkbox'); if($(this).prop('checked')) { checkboxes.prop('checked', true); } else { checkboxes.prop('checked', false); } }); // DELETE all $('#delete').click(function( event ){ var len = $('input:checkbox[name=items]:checked').length; if(len==0){ alert("[!] Seleccione un elemento a eliminar"); return; } var url; var eliminar = confirm("[?] Esta seguro de eliminar los "+len+ " items?"); if ( eliminar ) { $('input:checkbox[name=items]:checked').each(function(){ item_id = $(this).val(); url = 'core/menu/menu-del.php?id='+item_id; $.ajax({ url: url, cache: false, type: "GET" }).done(function( data ) { if(data.result==0){ notify('Ocurrio un error inesperado. Intente luego.'); return false; } }); }); notify('Los datos seleccionados fueron eliminados correctamente.'); setTimeout(function(){ window.location.href = '<?= G_SERVER ?>rb-admin/index.php?pag=menus'; }, 1000); } }); // DELETE ITEM $('.del-item').click(function( event ){ var item_id = $(this).attr('data-id'); var eliminar = confirm("[?] Esta a punto de eliminar este dato. Continuar?"); if ( eliminar ) { $.ajax({ url: 'core/menu/menu-del.php?id='+item_id, cache: false, type: "GET", success: function(data){ if(data.result = 1){ notify('El dato fue eliminado correctamente.'); setTimeout(function(){ window.location.href = '<?= G_SERVER ?>rb-admin/index.php?pag=menus'; }, 1000); }else{ notify('Ocurrio un error inesperado. Intente luego.'); } } }); } }); }); </script> <div class="wrap-content-list"> <section class="seccion"> <div class="seccion-header"> <h2>Menus</h2> <ul class="buttons"> <li><a class="fancyboxForm fancybox.ajax button btn-primary" href="<?= G_SERVER ?>rb-admin/core/menu/menu-edit.php?id=0"><i class="fa fa-plus-circle"></i> <span class="button-label">Nuevo</span></a></li> </ul> </div> <div class="seccion-body"> <div id="content-list"> <div id="resultado"> <script> $(document).ready(function() { $('#table').DataTable({ "language": { "url": "resource/datatables/Spanish.json" } }); } ); </script> <table id="table" class="tables table-striped"> <thead> <tr> <th width="30px"><input type="checkbox" value="all" id="select_all" /></th> <th>Nombre</th> <th>Shortcode</th> <th>Tipo</th> <th>Acciones</th> </tr> </thead> <tbody id="itemstable"> <?php include('menu-list.php') ?> </tbody> </table> </div> </div> </div> </section> </div>
jesusvld/pyro2
rb-admin/core/menu/menu-init.php
PHP
gpl-3.0
3,475
package sequencemining.main; import static java.util.function.Function.identity; import static java.util.stream.Collectors.counting; import static java.util.stream.Collectors.groupingBy; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.collect.HashBasedTable; import com.google.common.collect.Multiset; import com.google.common.collect.Table; import sequencemining.main.InferenceAlgorithms.InferenceAlgorithm; import sequencemining.sequence.Sequence; import sequencemining.transaction.Transaction; import sequencemining.transaction.TransactionDatabase; import sequencemining.util.Tuple2; /** Class to hold the various transaction EM Steps */ public class EMStep { /** Initialize cached sequences */ static void initializeCachedSequences(final TransactionDatabase transactions, final Table<Sequence, Integer, Double> initProbs) { transactions.getTransactionList().parallelStream().forEach(t -> t.initializeCachedSequences(initProbs)); } /** EM-step for hard EM */ static Table<Sequence, Integer, Double> hardEMStep(final List<Transaction> transactions, final InferenceAlgorithm inferenceAlgorithm) { final double noTransactions = transactions.size(); // E-step final Map<Multiset.Entry<Sequence>, Long> coveringWithCounts = transactions.parallelStream().map(t -> { final Multiset<Sequence> covering = inferenceAlgorithm.infer(t); t.setCachedCovering(covering); return covering.entrySet(); }).flatMap(Set::stream).collect(groupingBy(identity(), counting())); // M-step final Table<Sequence, Integer, Double> newSequences = coveringWithCounts.entrySet().parallelStream().collect( HashBasedTable::create, (t, e) -> t.put(e.getKey().getElement(), e.getKey().getCount(), e.getValue() / noTransactions), Table::putAll); newSequences.rowKeySet().parallelStream().forEach(seq -> { // Pad with zero counts for non-occurrences final int maxOccur = Collections.max(newSequences.row(seq).keySet()); for (int occur = 1; occur <= maxOccur; occur++) { if (!newSequences.contains(seq, occur)) newSequences.put(seq, occur, 0.); } // Add probabilities for zero occurrences double rowSum = 0; for (final Double count : newSequences.row(seq).values()) rowSum += count; newSequences.put(seq, 0, 1 - rowSum); }); // Update cached sequences transactions.parallelStream().forEach(t -> t.updateCachedSequences(newSequences)); return newSequences; } /** Get average cost of last EM-step */ static double calculateAverageCost(final TransactionDatabase transactions) { final double noTransactions = transactions.size(); return transactions.getTransactionList().parallelStream().mapToDouble(Transaction::getCachedCost).sum() / noTransactions; } /** EM-step for structural EM */ static Tuple2<Double, Map<Integer, Double>> structuralEMStep(final TransactionDatabase transactions, final InferenceAlgorithm inferenceAlgorithm, final Sequence candidate) { final double noTransactions = transactions.size(); // Calculate max. no. of candidate occurrences final int maxReps = transactions.getTransactionList().parallelStream().mapToInt(t -> t.repetitions(candidate)) .max().getAsInt(); final Map<Integer, Double> initProb = new HashMap<>(); initProb.put(0, 0.); for (int occur = 1; occur <= maxReps; occur++) initProb.put(occur, 1.); // E-step (adding candidate to transactions that support it) final Map<Multiset.Entry<Sequence>, Long> coveringWithCounts = transactions.getTransactionList() .parallelStream().map(t -> { if (t.contains(candidate)) { t.addSequenceCache(candidate, initProb); final Multiset<Sequence> covering = inferenceAlgorithm.infer(t); t.setTempCachedCovering(covering); return covering.entrySet(); } return t.getCachedCovering().entrySet(); }).flatMap(Set::stream).collect(groupingBy(identity(), counting())); // M-step final Table<Sequence, Integer, Double> newSequences = coveringWithCounts.entrySet().parallelStream().collect( HashBasedTable::create, (t, e) -> t.put(e.getKey().getElement(), e.getKey().getCount(), e.getValue() / noTransactions), Table::putAll); newSequences.rowKeySet().parallelStream().forEach(seq -> { // Pad with zero counts for non-occurrences final int maxOccur = Collections.max(newSequences.row(seq).keySet()); for (int occur = 1; occur <= maxOccur; occur++) { if (!newSequences.contains(seq, occur)) newSequences.put(seq, occur, 0.); } // Add probabilities for zero occurrences double rowSum = 0; for (final Double count : newSequences.row(seq).values()) rowSum += count; newSequences.put(seq, 0, 1 - rowSum); }); // Get average cost (removing candidate from supported transactions) final double averageCost = transactions.getTransactionList().parallelStream().mapToDouble(t -> { double cost; if (t.contains(candidate)) cost = t.getTempCachedCost(newSequences); else cost = t.getCachedCost(newSequences); t.removeSequenceCache(candidate); return cost; }).sum() / noTransactions; // Get candidate prob final Map<Integer, Double> prob = newSequences.row(candidate); return new Tuple2<Double, Map<Integer, Double>>(averageCost, prob); } /** Add accepted candidate itemset to cache */ static Table<Sequence, Integer, Double> addAcceptedCandidateCache(final TransactionDatabase transactions, final Sequence candidate, final Map<Integer, Double> prob) { final double noTransactions = transactions.size(); // Cached E-step (adding candidate to transactions that support it) final Map<Multiset.Entry<Sequence>, Long> coveringWithCounts = transactions.getTransactionList() .parallelStream().map(t -> { if (t.contains(candidate)) { t.addSequenceCache(candidate, prob); final Multiset<Sequence> covering = t.getTempCachedCovering(); t.setCachedCovering(covering); return covering.entrySet(); } return t.getCachedCovering().entrySet(); }).flatMap(Set::stream).collect(groupingBy(identity(), counting())); // M-step final Table<Sequence, Integer, Double> newSequences = coveringWithCounts.entrySet().parallelStream().collect( HashBasedTable::create, (t, e) -> t.put(e.getKey().getElement(), e.getKey().getCount(), e.getValue() / noTransactions), Table::putAll); newSequences.rowKeySet().parallelStream().forEach(seq -> { // Pad with zero counts for non-occurrences final int maxOccur = Collections.max(newSequences.row(seq).keySet()); for (int occur = 1; occur <= maxOccur; occur++) { if (!newSequences.contains(seq, occur)) newSequences.put(seq, occur, 0.); } // Add probabilities for zero occurrences double rowSum = 0; for (final Double count : newSequences.row(seq).values()) rowSum += count; newSequences.put(seq, 0, 1 - rowSum); }); // Update cached itemsets transactions.getTransactionList().parallelStream().forEach(t -> t.updateCachedSequences(newSequences)); return newSequences; } /** Get the support of given sequences */ static Map<Sequence, Long> getSupportsOfSequences(final TransactionDatabase transactions, final Set<Sequence> sequences) { return transactions.getTransactionList().parallelStream().map(t -> { final HashSet<Sequence> supportedSeqs = new HashSet<>(); for (final Sequence seq : sequences) { if (t.contains(seq)) supportedSeqs.add(seq); } return supportedSeqs; }).flatMap(Set::stream).collect(groupingBy(identity(), counting())); } private EMStep() { } }
mast-group/sequence-mining
sequence-miner/src/main/java/sequencemining/main/EMStep.java
Java
gpl-3.0
7,657
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.launcher3.model; import static android.content.ContentResolver.SCHEME_CONTENT; import static com.android.launcher3.util.Executors.MAIN_EXECUTOR; import static com.android.launcher3.util.Executors.createAndStartNewLooper; import android.annotation.TargetApi; import android.app.RemoteAction; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.LauncherApps; import android.database.ContentObserver; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.DeadObjectException; import android.os.Handler; import android.os.Message; import android.os.Process; import android.os.UserHandle; import android.text.TextUtils; import android.util.ArrayMap; import android.util.Log; import androidx.annotation.MainThread; import androidx.annotation.NonNull; import androidx.annotation.WorkerThread; import com.android.launcher3.BaseDraggingActivity; import com.android.launcher3.InvariantDeviceProfile; import com.android.launcher3.LauncherProvider; import com.android.launcher3.LauncherSettings; import com.android.launcher3.R; import com.android.launcher3.config.FeatureFlags; import com.android.launcher3.model.data.ItemInfo; import com.android.launcher3.popup.RemoteActionShortcut; import com.android.launcher3.popup.SystemShortcut; import com.android.launcher3.util.MainThreadInitializedObject; import com.android.launcher3.util.PackageManagerHelper; import com.android.launcher3.util.Preconditions; import com.android.launcher3.util.SimpleBroadcastReceiver; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; /** * Data model for digital wellbeing status of apps. */ @TargetApi(Build.VERSION_CODES.Q) public final class WellbeingModel { private static final String TAG = "WellbeingModel"; private static final int[] RETRY_TIMES_MS = {5000, 15000, 30000}; private static final boolean DEBUG = false; private static final int MSG_PACKAGE_ADDED = 1; private static final int MSG_PACKAGE_REMOVED = 2; private static final int MSG_FULL_REFRESH = 3; private static final int UNKNOWN_MINIMAL_DEVICE_STATE = 0; private static final int IN_MINIMAL_DEVICE = 2; // Welbeing contract private static final String PATH_ACTIONS = "actions"; private static final String PATH_MINIMAL_DEVICE = "minimal_device"; private static final String METHOD_GET_MINIMAL_DEVICE_CONFIG = "get_minimal_device_config"; private static final String METHOD_GET_ACTIONS = "get_actions"; private static final String EXTRA_ACTIONS = "actions"; private static final String EXTRA_ACTION = "action"; private static final String EXTRA_MAX_NUM_ACTIONS_SHOWN = "max_num_actions_shown"; private static final String EXTRA_PACKAGES = "packages"; private static final String EXTRA_SUCCESS = "success"; private static final String EXTRA_MINIMAL_DEVICE_STATE = "minimal_device_state"; private static final String DB_NAME_MINIMAL_DEVICE = "minimal.db"; public static final MainThreadInitializedObject<WellbeingModel> INSTANCE = new MainThreadInitializedObject<>(WellbeingModel::new); private final Context mContext; private final String mWellbeingProviderPkg; private final Handler mWorkerHandler; private final ContentObserver mContentObserver; private final Object mModelLock = new Object(); // Maps the action Id to the corresponding RemoteAction private final Map<String, RemoteAction> mActionIdMap = new ArrayMap<>(); private final Map<String, String> mPackageToActionId = new HashMap<>(); private boolean mIsInTest; private WellbeingModel(final Context context) { mContext = context; mWorkerHandler = new Handler(createAndStartNewLooper("WellbeingHandler"), this::handleMessage); mWellbeingProviderPkg = mContext.getString(R.string.wellbeing_provider_pkg); mContentObserver = new ContentObserver(MAIN_EXECUTOR.getHandler()) { @Override public void onChange(boolean selfChange, Uri uri) { if (DEBUG || mIsInTest) { Log.d(TAG, "ContentObserver.onChange() called with: selfChange = [" + selfChange + "], uri = [" + uri + "]"); } Preconditions.assertUIThread(); if (uri.getPath().contains(PATH_ACTIONS)) { // Wellbeing reports that app actions have changed. updateWellbeingData(); } else if (uri.getPath().contains(PATH_MINIMAL_DEVICE)) { // Wellbeing reports that minimal device state or config is changed. updateLauncherModel(context); } } }; FeatureFlags.ENABLE_MINIMAL_DEVICE.addChangeListener(mContext, () -> updateLauncherModel(context)); if (!TextUtils.isEmpty(mWellbeingProviderPkg)) { context.registerReceiver( new SimpleBroadcastReceiver(this::onWellbeingProviderChanged), PackageManagerHelper.getPackageFilter(mWellbeingProviderPkg, Intent.ACTION_PACKAGE_ADDED, Intent.ACTION_PACKAGE_CHANGED, Intent.ACTION_PACKAGE_REMOVED, Intent.ACTION_PACKAGE_DATA_CLEARED, Intent.ACTION_PACKAGE_RESTARTED)); IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED); filter.addAction(Intent.ACTION_PACKAGE_REMOVED); filter.addDataScheme("package"); context.registerReceiver(new SimpleBroadcastReceiver(this::onAppPackageChanged), filter); restartObserver(); } } public void setInTest(boolean inTest) { mIsInTest = inTest; } protected void onWellbeingProviderChanged(Intent intent) { if (DEBUG || mIsInTest) { Log.d(TAG, "Changes to Wellbeing package: intent = [" + intent + "]"); } restartObserver(); } private void restartObserver() { final ContentResolver resolver = mContext.getContentResolver(); resolver.unregisterContentObserver(mContentObserver); Uri actionsUri = apiBuilder().path(PATH_ACTIONS).build(); Uri minimalDeviceUri = apiBuilder().path(PATH_MINIMAL_DEVICE).build(); try { resolver.registerContentObserver( actionsUri, true /* notifyForDescendants */, mContentObserver); resolver.registerContentObserver( minimalDeviceUri, true /* notifyForDescendants */, mContentObserver); } catch (Exception e) { Log.e(TAG, "Failed to register content observer for " + actionsUri + ": " + e); if (mIsInTest) throw new RuntimeException(e); } updateWellbeingData(); } @MainThread private SystemShortcut getShortcutForApp(String packageName, int userId, BaseDraggingActivity activity, ItemInfo info) { Preconditions.assertUIThread(); // Work profile apps are not recognized by digital wellbeing. if (userId != UserHandle.myUserId()) { if (DEBUG || mIsInTest) { Log.d(TAG, "getShortcutForApp [" + packageName + "]: not current user"); } return null; } synchronized (mModelLock) { String actionId = mPackageToActionId.get(packageName); final RemoteAction action = actionId != null ? mActionIdMap.get(actionId) : null; if (action == null) { if (DEBUG || mIsInTest) { Log.d(TAG, "getShortcutForApp [" + packageName + "]: no action"); } return null; } if (DEBUG || mIsInTest) { Log.d(TAG, "getShortcutForApp [" + packageName + "]: action: '" + action.getTitle() + "'"); } return new RemoteActionShortcut(action, activity, info); } } private void updateWellbeingData() { mWorkerHandler.sendEmptyMessage(MSG_FULL_REFRESH); } private void updateLauncherModel(@NonNull final Context context) { if (!FeatureFlags.ENABLE_MINIMAL_DEVICE.get()) { reloadLauncherInNormalMode(context); return; } runWithMinimalDeviceConfigs((bundle) -> { if (bundle.getInt(EXTRA_MINIMAL_DEVICE_STATE, UNKNOWN_MINIMAL_DEVICE_STATE) == IN_MINIMAL_DEVICE) { reloadLauncherInMinimalMode(context); } else { reloadLauncherInNormalMode(context); } }); } private void reloadLauncherInNormalMode(@NonNull final Context context) { LauncherSettings.Settings.call(context.getContentResolver(), LauncherSettings.Settings.METHOD_SWITCH_DATABASE, InvariantDeviceProfile.INSTANCE.get(context).dbFile); } private void reloadLauncherInMinimalMode(@NonNull final Context context) { final Bundle extras = new Bundle(); extras.putString(LauncherProvider.KEY_LAYOUT_PROVIDER_AUTHORITY, mWellbeingProviderPkg + ".api"); LauncherSettings.Settings.call(context.getContentResolver(), LauncherSettings.Settings.METHOD_SWITCH_DATABASE, DB_NAME_MINIMAL_DEVICE, extras); } private Uri.Builder apiBuilder() { return new Uri.Builder() .scheme(SCHEME_CONTENT) .authority(mWellbeingProviderPkg + ".api"); } /** * Fetch most up-to-date minimal device config. */ @WorkerThread private void runWithMinimalDeviceConfigs(Consumer<Bundle> consumer) { if (!FeatureFlags.ENABLE_MINIMAL_DEVICE.get()) { return; } if (DEBUG || mIsInTest) { Log.d(TAG, "runWithMinimalDeviceConfigs() called"); } Preconditions.assertNonUiThread(); final Uri contentUri = apiBuilder().build(); final Bundle remoteBundle; try (ContentProviderClient client = mContext.getContentResolver() .acquireUnstableContentProviderClient(contentUri)) { remoteBundle = client.call( METHOD_GET_MINIMAL_DEVICE_CONFIG, null /* args */, null /* extras */); consumer.accept(remoteBundle); } catch (Exception e) { Log.e(TAG, "Failed to retrieve data from " + contentUri + ": " + e); if (mIsInTest) throw new RuntimeException(e); } if (DEBUG || mIsInTest) Log.i(TAG, "runWithMinimalDeviceConfigs(): finished"); } private boolean updateActions(String... packageNames) { if (packageNames.length == 0) { return true; } if (DEBUG || mIsInTest) { Log.d(TAG, "retrieveActions() called with: packageNames = [" + String.join(", ", packageNames) + "]"); } Preconditions.assertNonUiThread(); Uri contentUri = apiBuilder().build(); final Bundle remoteActionBundle; try (ContentProviderClient client = mContext.getContentResolver() .acquireUnstableContentProviderClient(contentUri)) { if (client == null) { if (DEBUG || mIsInTest) Log.i(TAG, "retrieveActions(): null provider"); return false; } // Prepare wellbeing call parameters. final Bundle params = new Bundle(); params.putStringArray(EXTRA_PACKAGES, packageNames); params.putInt(EXTRA_MAX_NUM_ACTIONS_SHOWN, 1); // Perform wellbeing call . remoteActionBundle = client.call(METHOD_GET_ACTIONS, null, params); if (!remoteActionBundle.getBoolean(EXTRA_SUCCESS, true)) return false; synchronized (mModelLock) { // Remove the entries for requested packages, and then update the fist with what we // got from service Arrays.stream(packageNames).forEach(mPackageToActionId::remove); // The result consists of sub-bundles, each one is per a remote action. Each // sub-bundle has a RemoteAction and a list of packages to which the action applies. for (String actionId : remoteActionBundle.getStringArray(EXTRA_ACTIONS)) { final Bundle actionBundle = remoteActionBundle.getBundle(actionId); mActionIdMap.put(actionId, actionBundle.getParcelable(EXTRA_ACTION)); final String[] packagesForAction = actionBundle.getStringArray(EXTRA_PACKAGES); if (DEBUG || mIsInTest) { Log.d(TAG, "....actionId: " + actionId + ", packages: " + String.join(", ", packagesForAction)); } for (String packageName : packagesForAction) { mPackageToActionId.put(packageName, actionId); } } } } catch (DeadObjectException e) { Log.i(TAG, "retrieveActions(): DeadObjectException"); return false; } catch (Exception e) { Log.e(TAG, "Failed to retrieve data from " + contentUri + ": " + e); if (mIsInTest) throw new RuntimeException(e); return true; } if (DEBUG || mIsInTest) Log.i(TAG, "retrieveActions(): finished"); return true; } private boolean handleMessage(Message msg) { switch (msg.what) { case MSG_PACKAGE_REMOVED: { String packageName = (String) msg.obj; mWorkerHandler.removeCallbacksAndMessages(packageName); synchronized (mModelLock) { mPackageToActionId.remove(packageName); } return true; } case MSG_PACKAGE_ADDED: { String packageName = (String) msg.obj; mWorkerHandler.removeCallbacksAndMessages(packageName); if (!updateActions(packageName)) { scheduleRefreshRetry(msg); } return true; } case MSG_FULL_REFRESH: { // Remove all existing messages mWorkerHandler.removeCallbacksAndMessages(null); final String[] packageNames = mContext.getSystemService(LauncherApps.class) .getActivityList(null, Process.myUserHandle()).stream() .map(li -> li.getApplicationInfo().packageName).distinct() .toArray(String[]::new); if (!updateActions(packageNames)) { scheduleRefreshRetry(msg); } return true; } } return false; } private void scheduleRefreshRetry(Message originalMsg) { int retryCount = originalMsg.arg1; if (retryCount >= RETRY_TIMES_MS.length) { // To many retries, skip return; } Message msg = Message.obtain(originalMsg); msg.arg1 = retryCount + 1; mWorkerHandler.sendMessageDelayed(msg, RETRY_TIMES_MS[retryCount]); } private void onAppPackageChanged(Intent intent) { if (DEBUG || mIsInTest) Log.d(TAG, "Changes in apps: intent = [" + intent + "]"); Preconditions.assertUIThread(); final String packageName = intent.getData().getSchemeSpecificPart(); if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { Message.obtain(mWorkerHandler, MSG_PACKAGE_REMOVED, packageName).sendToTarget(); } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { Message.obtain(mWorkerHandler, MSG_PACKAGE_ADDED, packageName).sendToTarget(); } } /** * Shortcut factory for generating wellbeing action */ public static final SystemShortcut.Factory SHORTCUT_FACTORY = (activity, info) -> (info.getTargetComponent() == null) ? null : INSTANCE.get(activity) .getShortcutForApp( info.getTargetComponent().getPackageName(), info.user.getIdentifier(), activity, info); }
Deletescape-Media/Lawnchair
quickstep/src/com/android/launcher3/model/WellbeingModel.java
Java
gpl-3.0
17,443
/** */ package org.tetrabox.example.minitl.minitl.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.EObjectImpl; import org.eclipse.emf.ecore.util.EcoreUtil; import org.tetrabox.example.minitl.minitl.Binding; import org.tetrabox.example.minitl.minitl.MinitlPackage; import org.tetrabox.example.minitl.minitl.ObjectTemplate; import org.tetrabox.example.minitl.minitl.Value; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Binding</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.tetrabox.example.minitl.minitl.impl.BindingImpl#getFeature <em>Feature</em>}</li> * <li>{@link org.tetrabox.example.minitl.minitl.impl.BindingImpl#getValue <em>Value</em>}</li> * <li>{@link org.tetrabox.example.minitl.minitl.impl.BindingImpl#getObjectTemplate <em>Object Template</em>}</li> * </ul> * * @generated */ public class BindingImpl extends EObjectImpl implements Binding { /** * The cached value of the '{@link #getFeature() <em>Feature</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFeature() * @generated * @ordered */ protected EStructuralFeature feature; /** * The cached value of the '{@link #getValue() <em>Value</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getValue() * @generated * @ordered */ protected Value value; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected BindingImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return MinitlPackage.Literals.BINDING; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EStructuralFeature getFeature() { if (feature != null && feature.eIsProxy()) { InternalEObject oldFeature = (InternalEObject)feature; feature = (EStructuralFeature)eResolveProxy(oldFeature); if (feature != oldFeature) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, MinitlPackage.BINDING__FEATURE, oldFeature, feature)); } } return feature; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EStructuralFeature basicGetFeature() { return feature; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFeature(EStructuralFeature newFeature) { EStructuralFeature oldFeature = feature; feature = newFeature; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MinitlPackage.BINDING__FEATURE, oldFeature, feature)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Value getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetValue(Value newValue, NotificationChain msgs) { Value oldValue = value; value = newValue; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MinitlPackage.BINDING__VALUE, oldValue, newValue); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setValue(Value newValue) { if (newValue != value) { NotificationChain msgs = null; if (value != null) msgs = ((InternalEObject)value).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - MinitlPackage.BINDING__VALUE, null, msgs); if (newValue != null) msgs = ((InternalEObject)newValue).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - MinitlPackage.BINDING__VALUE, null, msgs); msgs = basicSetValue(newValue, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MinitlPackage.BINDING__VALUE, newValue, newValue)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ObjectTemplate getObjectTemplate() { if (eContainerFeatureID() != MinitlPackage.BINDING__OBJECT_TEMPLATE) return null; return (ObjectTemplate)eInternalContainer(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetObjectTemplate(ObjectTemplate newObjectTemplate, NotificationChain msgs) { msgs = eBasicSetContainer((InternalEObject)newObjectTemplate, MinitlPackage.BINDING__OBJECT_TEMPLATE, msgs); return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setObjectTemplate(ObjectTemplate newObjectTemplate) { if (newObjectTemplate != eInternalContainer() || (eContainerFeatureID() != MinitlPackage.BINDING__OBJECT_TEMPLATE && newObjectTemplate != null)) { if (EcoreUtil.isAncestor(this, newObjectTemplate)) throw new IllegalArgumentException("Recursive containment not allowed for " + toString()); NotificationChain msgs = null; if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); if (newObjectTemplate != null) msgs = ((InternalEObject)newObjectTemplate).eInverseAdd(this, MinitlPackage.OBJECT_TEMPLATE__BINDINGS, ObjectTemplate.class, msgs); msgs = basicSetObjectTemplate(newObjectTemplate, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MinitlPackage.BINDING__OBJECT_TEMPLATE, newObjectTemplate, newObjectTemplate)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean check(EObject o) { // TODO: implement this method // Ensure that you remove @generated or mark it @generated NOT throw new UnsupportedOperationException(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void assign() { // TODO: implement this method // Ensure that you remove @generated or mark it @generated NOT throw new UnsupportedOperationException(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case MinitlPackage.BINDING__OBJECT_TEMPLATE: if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); return basicSetObjectTemplate((ObjectTemplate)otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case MinitlPackage.BINDING__VALUE: return basicSetValue(null, msgs); case MinitlPackage.BINDING__OBJECT_TEMPLATE: return basicSetObjectTemplate(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) { switch (eContainerFeatureID()) { case MinitlPackage.BINDING__OBJECT_TEMPLATE: return eInternalContainer().eInverseRemove(this, MinitlPackage.OBJECT_TEMPLATE__BINDINGS, ObjectTemplate.class, msgs); } return super.eBasicRemoveFromContainerFeature(msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case MinitlPackage.BINDING__FEATURE: if (resolve) return getFeature(); return basicGetFeature(); case MinitlPackage.BINDING__VALUE: return getValue(); case MinitlPackage.BINDING__OBJECT_TEMPLATE: return getObjectTemplate(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case MinitlPackage.BINDING__FEATURE: setFeature((EStructuralFeature)newValue); return; case MinitlPackage.BINDING__VALUE: setValue((Value)newValue); return; case MinitlPackage.BINDING__OBJECT_TEMPLATE: setObjectTemplate((ObjectTemplate)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case MinitlPackage.BINDING__FEATURE: setFeature((EStructuralFeature)null); return; case MinitlPackage.BINDING__VALUE: setValue((Value)null); return; case MinitlPackage.BINDING__OBJECT_TEMPLATE: setObjectTemplate((ObjectTemplate)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case MinitlPackage.BINDING__FEATURE: return feature != null; case MinitlPackage.BINDING__VALUE: return value != null; case MinitlPackage.BINDING__OBJECT_TEMPLATE: return getObjectTemplate() != null; } return super.eIsSet(featureID); } } //BindingImpl
tetrabox/minitl
plugins/org.tetrabox.example.minitl/src/org/tetrabox/example/minitl/minitl/impl/BindingImpl.java
Java
gpl-3.0
9,712
package levenshtein import ( "math" "strings" ) var lookUpTable map[string]int func init() { lookUpTable = make(map[string]int) } func min(a, b, c int) int { return int(math.Min(math.Min(float64(a), float64(b)), float64(c))) } // Distance calculates the levenshtein distance func Distance(a, b string, caseInsensitive bool) int { var cost int lenA := len(a) lenB := len(b) if lenA == 0 { return lenB } if lenB == 0 { return lenA } if d, ok := lookUpTable[a+b]; ok { return d } if caseInsensitive { a = strings.ToLower(a) b = strings.ToLower(b) } if a[lenA-1] != b[lenB-1] { cost = 1 } d := min(Distance(a[:lenA-1], b, caseInsensitive)+1, Distance(a, b[:lenB-1], caseInsensitive)+1, Distance(a[:lenA-1], b[:lenB-1], caseInsensitive)+cost) lookUpTable[a+b] = d return d }
AndersonQ/100-days-of-algorithms
002.Levenshtein_distance/levenshtein/levenshtein.go
GO
gpl-3.0
819
require_relative '../spec_helper' def silence_stream(stream) old_stream = stream.dup stream.reopen(RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ? 'NUL:' : '/dev/null') stream.sync = true yield ensure stream.reopen(old_stream) old_stream.close end describe TypedRb::Language do let(:language) { described_class.new } let(:file) { File.join(File.dirname(__FILE__), 'examples', example) } context 'with valid source code' do let(:example) { 'counter.rb' } it 'should be possible to type check the code' do silence_stream(STDOUT) do language.check_file(file, true) end expect_binding(language, Counter, '@counter', Integer) end end context 'with valid source code including conditionals' do let(:example) { 'if.rb' } it 'should be possible to type check the code' do silence_stream(STDOUT) do language.check_file(file, true) end expect_binding(language, TestIf, '@state', String) end end context 'with valid source code generic arrays' do let(:example) { 'animals.rb' } it 'should be possible to type check errors about array invariance' do expect { silence_stream(STDOUT) do language.check_file(file, true) end }.to raise_error(TypedRb::TypeCheckError, /Error type checking message sent 'mindless_func': Array\[Animal1\] expected, Array\[Cat1\] found/) end end context 'with monoid example' do let(:example) { 'monoid.rb' } it 'should be possible to type check the example correctly' do expect { silence_stream(STDOUT) do language.check_file(file, true) end }.not_to raise_error end end context 'with monoid error example 1, inconsistent type annotation' do let(:example) { 'monoid/monoid_error1.rb' } it 'should be possible to type check the example correctly' do expect { silence_stream(STDOUT) do language.check_file(file, true) end }.to raise_error(TypedRb::Types::UncomparableTypes) end end context 'with monoid error example 2, inconsistent type annotation' do let(:example) { 'monoid/monoid_error2.rb' } it 'should be possible to type check the example correctly' do expect { silence_stream(STDOUT) do language.check_file(file, true) end }.to raise_error(TypedRb::Types::UncomparableTypes) end end context 'with monoid error example 3, inconsistent type annotation' do let(:example) { 'monoid/monoid_error3.rb' } it 'should be possible to type check the example correctly' do expect { silence_stream(STDOUT) do language.check_file(file, true) end }.to raise_error(TypedRb::Types::UncomparableTypes) end end context 'with monoid error example 4, inconsistent type annotation' do let(:example) { 'monoid/monoid_error4.rb' } it 'should be possible to type check the example correctly' do expect { silence_stream(STDOUT) do language.check_file(file, true) end }.to raise_error(TypedRb::Types::Polymorphism::UnificationError) end end context 'with monoid2 example, type checks correctly' do let(:example) { 'monoid2.rb' } it 'should be possible to type check the example correctly' do expect { silence_stream(STDOUT) do language.check_file(file, true) end }.to_not raise_error end end context 'with monoid2 error example 1, inconsistent type' do let(:example) { 'monoid2/monoid2_error1.rb' } it 'should be possible to type check the example correctly' do expect { silence_stream(STDOUT) do language.check_file(file, true) end }.to raise_error(TypedRb::Types::UncomparableTypes) end end context 'with equality example, type checks correctly' do let(:example) { 'equality.rb' } it 'should be possible to type check the example correctly' do expect { silence_stream(STDOUT) do language.check_file(file, true) end }.to_not raise_error end end context 'with enum example, type checks correctly' do let(:example) { 'enum.rb' } it 'should be possible to type check the example correctly' do expect { expr = File.new(file, 'r').read result = language.check(expr) expect(result.to_s).to eq('Array[Integer]') }.to_not raise_error end end context 'with enum example error1, type checks correctly' do let(:example) { 'enum/enum_error1.rb' } it 'should be possible to type check the example correctly' do expect { expr = File.new(file, 'r').read language.check(expr) }.to raise_error(TypedRb::Types::Polymorphism::UnificationError) end end end
antoniogarrote/typed.rb
spec/lib/language_spec.rb
Ruby
gpl-3.0
4,865
<?php /* ---------------------------------------------------------------------- * app/views/admin/access/user_list_html.php : * ---------------------------------------------------------------------- * CollectiveAccess * Open-source collections management software * ---------------------------------------------------------------------- * * Software by Whirl-i-Gig (http://www.whirl-i-gig.com) * Copyright 2008-2016 Whirl-i-Gig * * For more information visit http://www.CollectiveAccess.org * * This program is free software; you may redistribute it and/or modify it under * the terms of the provided license as published by Whirl-i-Gig * * CollectiveAccess is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * This source code is free and modifiable under the terms of * GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See * the "license.txt" file for details, or visit the CollectiveAccess web site at * http://www.CollectiveAccess.org * * ---------------------------------------------------------------------- */ $va_user_list = $this->getVar('user_list'); ?> <script language="JavaScript" type="text/javascript"> /* <![CDATA[ */ $(document).ready(function(){ $('#caItemList').caFormatListTable(); }); /* ]]> */ </script> <div class="sectionBox"> <?php print caFormTag($this->request, 'ListUsers', 'caUserListForm', null, 'post', 'multipart/form-data', '_top', array('disableUnsavedChangesWarning' => true)); print caFormControlBox( '<div class="list-filter">'._t('Filter').': <input type="text" name="filter" value="" onkeyup="$(\'#caItemList\').caFilterTable(this.value); return false;" size="20"/></div>', ''._t('Show %1 users', caHTMLSelect('userclass', $this->request->user->getFieldInfo('userclass', 'BOUNDS_CHOICE_LIST'), array('onchange' => 'jQuery("#caUserListForm").submit();'), array('value' => $this->getVar('userclass')))), caNavHeaderButton($this->request, __CA_NAV_ICON_ADD__, _t("New user"), 'administrate/access', 'Users', 'Edit', array('user_id' => 0), [], ['size' => '30px']) ); ?> <h1 style='float:left; margin:10px 0px 10px 0px;'><?php print _t('%1 users', ucfirst($this->getVar('userclass_displayname'))); ?></h1> <?php if(sizeof($va_user_list)){ ?> <a href='#' id='showTools' style="float:left;margin-top:10px;" onclick='jQuery("#searchToolsBox").slideDown(250); jQuery("#showTools").hide(); return false;'><?php print caNavIcon(__CA_NAV_ICON_SETTINGS__, "24px");?></a> <?php print $this->render('user_tools_html.php'); } ?> <table id="caItemList" class="listtable" width="100%" border="0" cellpadding="0" cellspacing="1"> <thead> <tr> <th class="list-header-unsorted"> <?php print _t('Login name'); ?> </th> <th class="list-header-unsorted"> <?php print _t('Name'); ?> </th> <th class="list-header-unsorted"> <?php print _t('Email'); ?> </th> <th class="list-header-unsorted"> <?php print _t('Active?'); ?> </th> <th class="list-header-unsorted"> <?php print _t('Last login'); ?> </th> <th class="{sorter: false} list-header-nosort listtableEditDelete"></th> </tr> </thead> <tbody> <?php $o_tep = new TimeExpressionParser(); foreach($va_user_list as $va_user) { if ($va_user['last_login'] > 0) { $o_tep->setUnixTimestamps($va_user['last_login'], $va_user['last_login']); } ?> <tr> <td> <?php print $va_user['user_name']; ?> </td> <td> <?php print $va_user['lname'].', '.$va_user['fname']; ?> </td> <td> <?php print $va_user['email']; ?> </td> <td> <?php print $va_user['active'] ? _t('Yes') : _t('No'); ?> </td> <td> <?php print ($va_user['last_login'] > 0) ? $o_tep->getText() : '-'; ?> </td> <td class="listtableEditDelete"> <?php print caNavButton($this->request, __CA_NAV_ICON_EDIT__, _t("Edit"), '', 'administrate/access', 'Users', 'Edit', array('user_id' => $va_user['user_id']), array(), array('icon_position' => __CA_NAV_ICON_ICON_POS_LEFT__, 'use_class' => 'list-button', 'no_background' => true, 'dont_show_content' => true)); ?> <?php print caNavButton($this->request, __CA_NAV_ICON_DELETE__, _t("Delete"), '', 'administrate/access', 'Users', 'Delete', array('user_id' => $va_user['user_id']), array(), array('icon_position' => __CA_NAV_ICON_ICON_POS_LEFT__, 'use_class' => 'list-button', 'no_background' => true, 'dont_show_content' => true)); ?> </td> </tr> <?php TooltipManager::add('.deleteIcon', _t("Delete")); TooltipManager::add('.editIcon', _t("Edit")); TooltipManager::add('#showTools', _t("Tools")); } ?> </tbody> </table> </form> </div> <div class="editorBottomPadding"><!-- empty --></div>
perryrothjohnson/artifact-database
themes/default/views/administrate/access/user_list_html.php
PHP
gpl-3.0
4,869
# Copyright (C) 2012 David Morton # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from collections import defaultdict import random from scipy.cluster.vq import kmeans, vq import numpy def sample_data(data, num_samples): ''' Return a 'representative' sample of the data. Inputs: data: (samples, features) numpy array num_samples: integer > 0 Returns: result: (min(<num_samples>, len(<data>), features) numpy array ''' if num_samples >= len(data): return data else: # determine k k = min(25, num_samples) # cluster data clusters = vq(data, kmeans(data, k, iter=1)[0])[0] clustered_index_list = defaultdict(list) for i, c in enumerate(clusters): clustered_index_list[c].append(i) # pull data from clusters randomly. result = numpy.empty((num_samples, data.shape[1]), dtype=data.dtype) # -- guarantee at least one element from each cluster -- sample_index_set = set() for index_list in clustered_index_list.values(): index = random.choice(index_list) result[len(sample_index_set)] = data[index] sample_index_set.add(index) while len(sample_index_set) < num_samples: cluster = random.choice(clustered_index_list.keys()) index = random.choice(clustered_index_list[cluster]) if index not in sample_index_set: result[len(sample_index_set)] = data[index] sample_index_set.add(index) return result
davidlmorton/spikepy
spikepy/plotting_utils/sampler.py
Python
gpl-3.0
2,180
package main import ( "github.com/gin-gonic/gin" "http" ) func main() { server := gin.Default() server.LoadHTMLGlob("templates/**/*") r := new(http.Router) r.Disparch(server) server.Run() }
summer7c/WebGo
src/main/main.go
GO
gpl-3.0
199
// Copyright (C) 2012 Mark Burnett // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #include <gtest/gtest.h> #include "concentrations/concentration.h" #include "concentrations/fixed_concentration.h" #include "concentrations/fixed_reagent.h" TEST(Concentrations, ZeroConcentration) { stochastic::concentrations::ZeroConcentration c; EXPECT_DOUBLE_EQ(0, c.value()); EXPECT_EQ(0, c.monomer_count()); c.remove_monomer(); EXPECT_DOUBLE_EQ(0, c.value()); EXPECT_EQ(0, c.monomer_count()); c.add_monomer(); EXPECT_DOUBLE_EQ(0, c.value()); EXPECT_EQ(0, c.monomer_count()); } TEST(Concentrations, FixedConcentration) { stochastic::concentrations::FixedConcentration c(3.1); EXPECT_DOUBLE_EQ(3.1, c.value()); c.remove_monomer(); EXPECT_DOUBLE_EQ(3.1, c.value()); c.add_monomer(); EXPECT_DOUBLE_EQ(3.1, c.value()); } TEST(Concentrations, FixedReagent) { stochastic::concentrations::FixedReagent c(4.8, 1.2); EXPECT_DOUBLE_EQ(4.8, c.value()); c.remove_monomer(); EXPECT_DOUBLE_EQ(3.6, c.value()); c.add_monomer(); c.add_monomer(); EXPECT_DOUBLE_EQ(6, c.value()); }
mark-burnett/filament-dynamics
cpp_stochastic/tests/test_concentrations.cpp
C++
gpl-3.0
1,790
package com.leetcode.submissions; /** * Create by ranzd on 2018/11/13 * * @author cm.zdran@foxmail.com */ public class MaximumSubarray { public static int maxSubArray(int[] nums) { int max = Integer.MIN_VALUE; int ans = max; for (int num : nums) { max = max < 0 ? num : max + num; ans = max > ans ? max : ans; } return ans; } }
zdRan/leetcode
src/com/leetcode/submissions/MaximumSubarray.java
Java
gpl-3.0
407
/* * Copyright (C) 2015,�������, * All Rights Reserved * Description: TODO What the class does. * * @project ���� * @author Administrator * @date 2016��1��10��-����11:30:54 * * Modification History: ********************************************************** * Date Author Comments * 2016��1��10�� Administrator Create ********************************************************** */ package com.liuhaozzu.mybatis.dao; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import com.liuhaozzu.mybatis.po.User; /** * TODO What the class does * <p>Title:com.liuhaozzu.mybatis.dao.UserDaoImpl.java</p> * <p>Description: </p> * <p>Company:www.richfit.com</p> * @author liuhaozzu * @date 2016��1��10��-����11:30:54 * @version 1.0 */ public class UserDaoImpl implements UserDao { private SqlSessionFactory sqlSessionFactory; public UserDaoImpl(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory = sqlSessionFactory; } /* (non-Javadoc) * @see com.liuhaozzu.mybatis.dao.UserDao#findUserById(int) */ @Override public User findUserById(int id) throws Exception { SqlSession sqlSession=sqlSessionFactory.openSession(); User user = sqlSession.selectOne("test.findUserById", id); sqlSession.commit(); sqlSession.close(); return user; } /* (non-Javadoc) * @see com.liuhaozzu.mybatis.dao.UserDao#insertUser(com.liuhaozzu.mybatis.po.User) */ @Override public void insertUser(User user) throws Exception { SqlSession sqlSession=sqlSessionFactory.openSession(); sqlSession.insert("test.insertUser", user); sqlSession.commit(); sqlSession.close(); } /* (non-Javadoc) * @see com.liuhaozzu.mybatis.dao.UserDao#deleteUser(int) */ @Override public void deleteUser(int id) throws Exception { SqlSession sqlSession=sqlSessionFactory.openSession(); sqlSession.delete("test.deleteUser", id); sqlSession.commit(); sqlSession.close(); } }
liuhaozzu/mybatis_demo
src/com/liuhaozzu/mybatis/dao/UserDaoImpl.java
Java
gpl-3.0
2,143
<?php require_once ('MyAbstractClass.php'); class MyAbstractClassTest extends PHPUnit_Framework_TestCase { public function testMockMultiple() { $interface = $this->getMockBuilder('MyInterface') ->setMethods([ 'doSomething' ]) ->getMockForAbstractClass(); $interface->expects($this->once()) ->method('doSomething'); $my = $this->getMockBuilder('MyAbstractClass') ->getMockForAbstractClass(); $my->setValue($interface); } }
rebel-l/workshops
AutomatedTests/examples/php/12/good/MyAbstractClassTest.php
PHP
gpl-3.0
543
from django.conf import settings from django.db import models from django.forms.models import model_to_dict import json import requests class Character(models.Model): name = models.CharField(max_length=250) server_name = models.CharField(max_length=250) head = models.TextField(blank=True, null=True) neck = models.TextField(blank=True, null=True) back = models.TextField(blank=True, null=True) chest = models.TextField(blank=True, null=True) wrist = models.TextField(blank=True, null=True) hands = models.TextField(blank=True, null=True) waist = models.TextField(blank=True, null=True) legs = models.TextField(blank=True, null=True) feet = models.TextField(blank=True, null=True) finger1 = models.TextField(blank=True, null=True) finger2 = models.TextField(blank=True, null=True) trinket1 = models.TextField(blank=True, null=True) trinket2 = models.TextField(blank=True, null=True) mainHand = models.TextField(blank=True, null=True) artifactTraits = models.TextField(blank=True, null=True) def __unicode__(self): return '{server_name} - {name}'.format( server_name=self.server_name, name=self.name ) def fetch_from_battlenet(self): api_key = settings.BN_APIKEY url = 'https://us.api.battle.net/wow/character/{server_name}/{char_name}?'\ 'fields=items+talents&locale=en_US&apikey={api_key}'.format( server_name=self.server_name, char_name=self.name, api_key=api_key ) response = requests.get(url) data = json.loads(response.content) positions = [ 'head', 'neck', 'back', 'chest', 'wrist', 'hands', 'waist', 'legs', 'feet', 'finger1', 'finger2', 'trinket1', 'trinket2', 'mainHand' ] for position in positions: setattr( self, position, str(data['items'][position]['id']) + str(data['items'][position]['itemLevel']) ) self.save() return self def to_dict(self): return model_to_dict(self) class SimcRank(models.Model): character = models.ForeignKey(Character) dps_rank = models.IntegerField() rating_time = models.DateTimeField(auto_now_add=True) def __unicode__(self): return '{name} - {dps_rank}'.format( name=self.character.name, dps_rank=self.dps_rank )
tinyx/crabfactory
wow_monitor/models.py
Python
gpl-3.0
2,497
using UnityEngine; using System.Collections; public class LetterPickup_JnS : MonoBehaviour { [SerializeField] private char letter; public char Letter { get { return letter; } set { letter = value; } } public void OnTriggerEnter2D(Collider2D other) { var player = other.GetComponent<Player>(); if (player == null) return; gameObject.SetActive(false); Debug.Log(string.Format("{0} was picked up.", letter)); WordManager_JnS let = other.GetComponent<WordManager_JnS>(); let.AddLetter(letter); } }
GenericEntity/JumpNSpell
Jump & Spell/Assets/scripts/Items/LetterPickup_JnS.cs
C#
gpl-3.0
530
class RemoveNonreportingReponses < ActiveRecord::Migration def self.up load 'db/fixes/20120424_remove_dead_responses.rb' end def self.down puts 'irreversible' end end
siyelo/hrt
db/migrate/20120427174355_remove_nonreporting_reponses.rb
Ruby
gpl-3.0
182
/* gvSIG. Sistema de Información Geográfica de la Generalitat Valenciana * * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,USA. * * For more information, contact: * * Generalitat Valenciana * Conselleria d'Infraestructures i Transport * Av. Blasco Ibáñez, 50 * 46010 VALENCIA * SPAIN * * +34 963862235 * gvsig@gva.es * www.gvsig.gva.es * * or * * IVER T.I. S.A * Salamanca 50 * 46005 Valencia * Spain * * +34 963163400 * dac@iver.es */ package com.iver.cit.gvsig; import java.awt.Dimension; import java.io.IOException; import com.hardcode.driverManager.DriverLoadException; import com.hardcode.gdbms.driver.exceptions.ReadDriverException; import com.hardcode.gdbms.engine.data.DataSource; import com.hardcode.gdbms.engine.data.DataSourceFactory; import com.hardcode.gdbms.engine.instruction.EvaluationException; import com.hardcode.gdbms.engine.instruction.SemanticException; import com.hardcode.gdbms.parser.ParseException; import com.iver.andami.PluginServices; import com.iver.andami.messages.NotificationManager; import com.iver.andami.plugins.Extension; import com.iver.andami.ui.mdiManager.IWindow; import com.iver.cit.gvsig.fmap.drivers.FieldDescription; import com.iver.cit.gvsig.fmap.edition.EditableAdapter; import com.iver.cit.gvsig.fmap.layers.FBitSet; import com.iver.cit.gvsig.fmap.layers.LayerFactory; import com.iver.cit.gvsig.fmap.layers.SelectableDataSource; import com.iver.cit.gvsig.fmap.operations.arcview.ArcJoinDataSource; import com.iver.cit.gvsig.gui.filter.ExpressionListener; import com.iver.cit.gvsig.project.Project; import com.iver.cit.gvsig.project.documents.table.FieldSelectionModel; import com.iver.cit.gvsig.project.documents.table.ObjectSelectionStep; import com.iver.cit.gvsig.project.documents.table.ProjectTable; import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory; import com.iver.cit.gvsig.project.documents.table.TableSelectionModel; import com.iver.cit.gvsig.project.documents.table.gui.AndamiWizard; import com.iver.cit.gvsig.project.documents.table.gui.JoinWizardController; import com.iver.cit.gvsig.project.documents.table.gui.Table; import com.iver.utiles.swing.objectSelection.SelectionException; import com.iver.utiles.swing.wizard.WizardControl; import com.iver.utiles.swing.wizard.WizardEvent; import com.iver.utiles.swing.wizard.WizardListener; /** * Extensión que controla las operaciones realizadas sobre las tablas. * * @author Fernando González Cortés */ public class TableOperations extends Extension implements ExpressionListener { private SelectableDataSource dataSource = null; //private Table vista; /** * @see com.iver.mdiApp.plugins.IExtension#updateUI(java.lang.String) */ public void execute(String actionCommand) { ProjectExtension pe = (ProjectExtension) PluginServices.getExtension(ProjectExtension.class); Project project=pe.getProject(); ProjectTable[] pts = (ProjectTable[]) project.getDocumentsByType(ProjectTableFactory.registerName) .toArray(new ProjectTable[0]); if ("JOIN".equals(actionCommand)) { JoinWizardController wizardController = new JoinWizardController(this); wizardController.runWizard(pts); }else if ("LINK".equals(actionCommand)) { try { final ObjectSelectionStep sourceTable = new ObjectSelectionStep(); sourceTable.setModel(new TableSelectionModel(pts, PluginServices.getText(this, "seleccione_tabla_origen"))); final ObjectSelectionStep targetTable = new ObjectSelectionStep(); targetTable.setModel(new TableSelectionModel(pts, PluginServices.getText(this, "seleccione_tabla_a_enlazar"))); final ObjectSelectionStep firstTableField = new ObjectSelectionStep(); final ObjectSelectionStep secondTableField = new ObjectSelectionStep(); final AndamiWizard wiz = new AndamiWizard(PluginServices.getText(this, "back"), PluginServices.getText(this, "next"), PluginServices.getText(this, "finish"), PluginServices.getText(this, "cancel")); wiz.setSize(new Dimension(450,200)); wiz.addStep(sourceTable); wiz.addStep(firstTableField); wiz.addStep(targetTable); wiz.addStep(secondTableField); wiz.addWizardListener(new WizardListener() { public void cancel(WizardEvent w) { PluginServices.getMDIManager().closeWindow(wiz); } public void finished(WizardEvent w) { PluginServices.getMDIManager().closeWindow(wiz); ProjectTable sourceProjectTable = (ProjectTable) sourceTable.getSelected(); SelectableDataSource sds1=null;; try { sds1 = sourceProjectTable.getModelo().getRecordset(); } catch (ReadDriverException e) { e.printStackTrace(); } //String tableName1 = sds1.getName(); ProjectTable targetProjectTable = (ProjectTable) targetTable.getSelected(); SelectableDataSource sds2=null; try { sds2 = targetProjectTable.getModelo().getRecordset(); } catch (ReadDriverException e) { e.printStackTrace(); } //String tableName2 = sds2.getName(); String field1 = (String) firstTableField.getSelected(); String field2 = (String) secondTableField.getSelected(); sourceProjectTable.setLinkTable(sds2.getName(),field1,field2); ((ProjectExtension)PluginServices.getExtension(ProjectExtension.class)).getProject().setLinkTable(); } public void next(WizardEvent w) { WizardControl wiz = w.wizard; wiz.enableBack(true); wiz.enableNext(((ObjectSelectionStep) wiz.getCurrentStep()).getSelectedItem() != null); if (w.currentStep == 1) { ProjectTable pt = (ProjectTable) sourceTable.getSelected(); try { firstTableField.setModel(new FieldSelectionModel( pt.getModelo().getRecordset(), PluginServices.getText(this, "seleccione_campo_enlace"), -1)); } catch (SelectionException e) { NotificationManager.addError("Error obteniendo los campos de la tabla", e); } catch (ReadDriverException e) { e.printStackTrace(); } } else if (w.currentStep == 3) { try { //tabla ProjectTable pt = (ProjectTable) sourceTable.getSelected(); //índice del campo SelectableDataSource sds = pt.getModelo().getRecordset(); String fieldName = (String) firstTableField.getSelected(); int fieldIndex = sds.getFieldIndexByName(fieldName); int type = sds.getFieldType(fieldIndex); secondTableField.setModel(new FieldSelectionModel( ((ProjectTable) targetTable.getSelected()).getModelo().getRecordset(), PluginServices.getText(this, "seleccione_campo_enlace"), type)); } catch (SelectionException e) { NotificationManager.addError("Error obteniendo los campos de la tabla", e); } catch (ReadDriverException e) { NotificationManager.addError("Error obteniendo los campos de la tabla", e); } } } public void back(WizardEvent w) { WizardControl wiz = w.wizard; wiz.enableBack(true); wiz.enableNext(((ObjectSelectionStep) wiz.getCurrentStep()).getSelectedItem() != null); } }); project.setModified(true); PluginServices.getMDIManager().addWindow(wiz); } catch (SelectionException e) { NotificationManager.addError("Error abriendo el asistente", e); } } } /** * @see com.iver.cit.gvsig.gui.filter.ExpressionListener#newSet(java.lang.String) */ public void newSet(String expression) { // By Pablo: if no expression -> no element selected if (! this.filterExpressionFromWhereIsEmpty(expression)) { long[] sel = doSet(expression); if (sel == null) { throw new RuntimeException("Not a 'where' clause?"); } FBitSet selection = new FBitSet(); for (int i = 0; i < sel.length; i++) { selection.set((int) sel[i]); } dataSource.clearSelection(); dataSource.setSelection(selection); } else { // By Pablo: if no expression -> no element selected dataSource.clearSelection(); } } /** * @see com.iver.cit.gvsig.gui.filter.ExpressionListener#newSet(java.lang.String) */ private long[] doSet(String expression) { try { DataSource ds = LayerFactory.getDataSourceFactory().executeSQL(expression, DataSourceFactory.MANUAL_OPENING); return ds.getWhereFilter(); } catch (DriverLoadException e) { NotificationManager.addError("Error cargando el driver", e); } catch (ReadDriverException e) { NotificationManager.addError("Error accediendo al driver", e); } catch (ParseException e) { NotificationManager.addError("Parse error", e); } catch (SemanticException e) { NotificationManager.addError(e.getMessage(), e); } catch (IOException e) { NotificationManager.addError("GDBMS internal error", e); } catch (EvaluationException e) { NotificationManager.addError("Error con la expresión", e); } return null; } /** * @see com.iver.cit.gvsig.gui.filter.ExpressionListener#addToSet(java.lang.String) */ public void addToSet(String expression) { // By Pablo: if no expression -> don't add more elements to set if (! this.filterExpressionFromWhereIsEmpty(expression)) { long[] sel = doSet(expression); if (sel == null) { throw new RuntimeException("Not a 'where' clause?"); } FBitSet selection = new FBitSet(); for (int i = 0; i < sel.length; i++) { selection.set((int) sel[i]); } FBitSet fbs = dataSource.getSelection(); fbs.or(selection); dataSource.setSelection(fbs); } } /** * @see com.iver.cit.gvsig.gui.filter.ExpressionListener#fromSet(java.lang.String) */ public void fromSet(String expression) { // By Pablo: if no expression -> no element selected if (! this.filterExpressionFromWhereIsEmpty(expression)) { long[] sel = doSet(expression); if (sel == null) { throw new RuntimeException("Not a 'where' clause?"); } FBitSet selection = new FBitSet(); for (int i = 0; i < sel.length; i++) { selection.set((int) sel[i]); } FBitSet fbs = dataSource.getSelection(); fbs.and(selection); dataSource.setSelection(fbs); } else { // By Pablo: if no expression -> no element selected dataSource.clearSelection(); } } /** * Returns true if the WHERE subconsultation of the filterExpression is empty ("") * * @author Pablo Piqueras Bartolomé (p_queras@hotmail.com) * @param expression An string * @return A boolean value */ private boolean filterExpressionFromWhereIsEmpty(String expression) { String subExpression = expression.trim(); int pos; // Remove last ';' if exists if (subExpression.charAt(subExpression.length() -1) == ';') subExpression = subExpression.substring(0, subExpression.length() -1).trim(); // If there is no 'where' clause if ((pos = subExpression.indexOf("where")) == -1) return false; // If there is no subexpression in the WHERE clause -> true subExpression = subExpression.substring(pos + 5, subExpression.length()).trim(); // + 5 is the length of 'where' if ( subExpression.length() == 0 ) return true; else return false; } /** * @see com.iver.mdiApp.plugins.IExtension#isVisible() */ public boolean isVisible() { IWindow v = PluginServices.getMDIManager().getActiveWindow(); if (v == null) { return false; } if (v instanceof Table) { if (!((Table)v).getModel().getModelo().isEditing()) return true; } /*else { if (v instanceof com.iver.cit.gvsig.gui.View) { com.iver.cit.gvsig.gui.View view = (com.iver.cit.gvsig.gui.View) v; ProjectView pv = view.getModel(); FLayer[] seleccionadas = pv.getMapContext().getLayers() .getActives(); if (seleccionadas.length == 1) { if (seleccionadas[0] instanceof AlphanumericData) { return true; } } } */ return false; //} } /** * @see com.iver.andami.plugins.IExtension#initialize() */ public void initialize() { registerIcons(); } private void registerIcons(){ PluginServices.getIconTheme().registerDefault( "table-join", this.getClass().getClassLoader().getResource("images/tablejoin.png") ); PluginServices.getIconTheme().registerDefault( "table-link", this.getClass().getClassLoader().getResource("images/tablelink.png") ); } /** * @see com.iver.andami.plugins.IExtension#isEnabled() */ public boolean isEnabled() { return true; } public void execJoin(ProjectTable sourceProjectTable, String field1, String prefix1, ProjectTable targetProjectTable, String field2, String prefix2) { // get source table and source field SelectableDataSource sds=null; try { sds = sourceProjectTable.getModelo().getRecordset(); } catch (ReadDriverException e) { e.printStackTrace(); } String tableName1 = sds.getName(); // get target table and target field SelectableDataSource tds=null; try { tds = targetProjectTable.getModelo().getRecordset(); } catch (ReadDriverException e) { e.printStackTrace(); } String tableName2 = tds.getName(); // compute the join String sql = "custom com_iver_cit_gvsig_arcjoin tables '" + tableName1 + "', '" + tableName2 + "' values(" + field1 + ", " + field2 + ");"; PluginServices.getLogger().debug(sql); try { SelectableDataSource result = new SelectableDataSource(LayerFactory.getDataSourceFactory() .executeSQL(sql, DataSourceFactory.MANUAL_OPENING)); // Lo ponemos manual porque como automático al final se crea un nombre no registrado EditableAdapter auxea=new EditableAdapter(); auxea.setOriginalDataSource(result); String[] currentJoinedTables = sourceProjectTable.getJoinedTables(); String[] joinedTables; if (currentJoinedTables!=null) { joinedTables = new String[currentJoinedTables.length+1]; System.arraycopy(currentJoinedTables, 0, joinedTables, 0, currentJoinedTables.length); } else { joinedTables = new String[1]; } joinedTables[joinedTables.length-1] = targetProjectTable.getName(); sourceProjectTable.setJoinTable(joinedTables); sourceProjectTable.replaceDataSource(auxea); renameFields(sourceProjectTable, sds, sanitizeFieldName(prefix1), tds, sanitizeFieldName(prefix2)); } catch (ParseException e) { throw new RuntimeException(e); } catch (DriverLoadException e) { NotificationManager.addError(PluginServices.getText(this, "Error_loading_driver"), e); } catch (ReadDriverException e) { NotificationManager.addError(PluginServices.getText(this, "Error_reading_from_the_driver"), e); } catch (SemanticException e) { throw new RuntimeException(e); } catch (EvaluationException e) { NotificationManager.addError(PluginServices.getText(this, "Error_evaluationg_expression"), e); } } // // /** // * Renames fields in a JOIN, so that fields from TABLE1 // * become sourcePrefix.field1, sourcePrefix.field2, etc, and fields // * from TABLE2 become targetPrefix.field1, targetPrefix.field2, etc. // * @param eds // * @param pt1 // * @param pt1 // */ /** * <p>Renames fields in a JOIN, so that fields from DataSource1 * become sourcePrefix_field1, sourcePrefix_field2, etc, and fields * from TABLE2 become targetPrefix_field1, targetPrefix_field2, etc. * ProjectTable aliases are used to rename fields.</p> * * @param targetPt The ProjectTable whose fields are to be renamed * @param ds1 The first datasource in the join * @param prefix1 The prefix to apply to fields in ds1 * @param ds2 The second datasource in the join * @param prefix2 The prefix to apply to fields in ds2 */ private void renameFields(ProjectTable targetPt, DataSource ds1, String prefix1, DataSource ds2, String prefix2) { try { SelectableDataSource sds = targetPt.getModelo().getRecordset(); // FieldDescription[] fields = sds.getFieldsDescription(); String[] aliases = new String[sds.getFieldCount()]; int i=0; while (i<aliases.length && i<ds1.getFieldCount()){ if (!prefix1.equals("")) aliases[i] = prefix1+"_"+sds.getFieldName(i); else aliases[i] = sds.getFieldName(i); sds.setFieldAlias(i, aliases[i]); i++; } while (i<aliases.length) { if (!prefix2.equals("")) aliases[i] = prefix2 + "_" + sds.getFieldName(i).substring(ArcJoinDataSource.prefix.length()); else aliases[i] = sds.getFieldName(i).substring(ArcJoinDataSource.prefix.length()); sds.setFieldAlias(i,aliases[i]); i++; } targetPt.setAliases(aliases); } catch (ReadDriverException e) { //just log the error, it's not bad if fields couldn't be renamed PluginServices.getLogger().error("Error renaming fields in a JOIN", e); } catch (Exception e) { //just log the error, it's not bad if fields couldn't be renamed PluginServices.getLogger().error("Error renaming fields in a JOIN", e); } } /** * Ensure that field name only has 'safe' characters * (no spaces, special characters, etc). */ public String sanitizeFieldName(String fieldName) { return fieldName.replaceAll("\\W", "_"); // replace any non-word character by an underscore } }
iCarto/siga
appgvSIG/src/com/iver/cit/gvsig/TableOperations.java
Java
gpl-3.0
17,909
# Flexlay - A Generic 2D Game Editor # Copyright (C) 2014 Ingo Ruhnke <grumbel@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from flexlay import Config class SuperTuxMenuBar: def __init__(self, gui_manager, editor): self.gui_manager = gui_manager # Create Menu self.menubar = self.gui_manager.create_menubar() file_menu = self.menubar.add_menu("&File") submenu_new = file_menu.add_menu("New") submenu_new.add_item("Level...", editor.gui_level_new) submenu_new.add_item("Add-on...", editor.gui_addon_new) file_menu.add_item("Open...", editor.gui_level_load) self.recent_files_menu = file_menu.add_menu("Open Recent") for filename in Config.current.recent_files: self.recent_files_menu.add_item(filename, lambda filename=filename: editor.load_level(filename)) file_menu.add_item("Save...", editor.gui_level_save) # file_menu.add_item("Save Commands...", menu_file_save_commands) file_menu.add_item("Save As...", editor.gui_level_save_as) file_menu.add_item("Properties...", editor.gui_edit_level) file_menu.add_item("Quit", editor.gui.quit) edit_menu = self.menubar.add_menu("&Edit") edit_menu.add_item("Smooth Selection", editor.gui_smooth_level_struct) edit_menu.add_item("Resize", editor.gui_resize_sector) edit_menu.add_item("Resize to selection", editor.gui_resize_sector_to_selection) edit_menu.add_item("Change Tileset", editor.gui_change_tileset) zoom_menu = self.menubar.add_menu("&Zoom") zoom_menu.add_item("1:4 (25%) ", lambda: editor.gui_set_zoom(0.25)) zoom_menu.add_item("1:2 (50%) ", lambda: editor.gui_set_zoom(0.5)) zoom_menu.add_item("1:1 (100%) ", lambda: editor.gui_set_zoom(1.0)) zoom_menu.add_item("2:1 (200%) ", lambda: editor.gui_set_zoom(2.0)) zoom_menu.add_item("4:1 (400%) ", lambda: editor.gui_set_zoom(4.0)) layer_menu = self.menubar.add_menu("&Layer") layer_menu.add_item("Show All", editor.layer_selector.show_all) layer_menu.add_item("Hide All", editor.layer_selector.show_all) # layer_menu.add_item("Show Only Selected", (lambda: print("\"Show Only Selected\" is not implemented"))) sector_menu = self.menubar.add_menu("&Sector") # sector = editor.workspace.get_map().metadata # for i in sector.parent.get_sectors(): # if sector.name == i: # current = " [current]" # else: # current = "" # # def on_sector_callback(): # print("Switching to %s" % i) # editor.workspace.get_map().metadata.parent.activate_sector(i, editor.workspace) # # mymenu.add_item(mysprite, ("Sector (%s)%s" % [i, current]), on_sector_callback) sector_menu.add_item("Create New Sector", editor.gui_add_sector) sector_menu.add_item("Remove Current Sector", editor.gui_remove_sector) sector_menu.add_item("Edit Sector Properties", editor.gui_edit_sector) run_menu = self.menubar.add_menu("&Run") run_menu.add_item("Run Level", editor.gui_run_level) run_menu.add_item("Record Level Playthrough", editor.gui_record_level) run_menu.add_item("Play A Demo", editor.gui_play_demo) run_menu.add_item("Play Example Demo", editor.gui_watch_example) self.editor = editor def update_recent_files(self): self.recent_files_menu.menu.clear() for filename in Config.current.recent_files: self.recent_files_menu.add_item(filename, lambda filename=filename: self.editor.load_level(filename)) # EOF #
SuperTux/flexlay
supertux/menubar.py
Python
gpl-3.0
4,310
package com.mystrive.products; public interface ProductCatalogsLoader { void load(ProductCatalogsManager manager) throws Exception; }
AtHomesoft/MyStrive-ProductCatalogs
src/main/java/com/mystrive/products/ProductCatalogsLoader.java
Java
gpl-3.0
139
/* * ColorSchemeNucleotidesDefault.java Copyright (C) 2021. Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package megan.alignment.gui.colors; import java.awt.*; /** * amino acid color scheme * Daniel Huson, 9.2011 */ public class ColorSchemeNucleotidesDefault extends ColorSchemeBase implements IColorScheme { /** * gets the background color for the amino-acid * * @param ch * @return color */ public Color getBackground(int ch) { switch (ch) { case 'a': case 'A': return getDefinedColor(ch, 0x64F73F); // green case 'c': case 'C': return getDefinedColor(ch, 0xFFB340); // orange case 'g': case 'G': return getDefinedColor(ch, 0xEB413C); // red case 't': case 'T': case 'u': case 'U': return getDefinedColor(ch, 0x3C88EE); // blue case '-': return getDefinedColor(ch, 0x778899); // Light Slate Gray default: return Color.LIGHT_GRAY; } } }
danielhuson/megan-ce
src/megan/alignment/gui/colors/ColorSchemeNucleotidesDefault.java
Java
gpl-3.0
1,876
<?php //////////////////////////////////////////////////////////////////////// //SITE CONFIGURATION //////////////////////////////////////////////////////////////////////// $QDEPURACION=1; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% //VERSION //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% $VERSION="Beta 2.0"; $VER=2; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% //DATABASE //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% $USER="sinfin"; $PASSWORD="123"; $DATABASE="Sinfin2"; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% //EMAIL //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% $EMAIL_USERNAME="pregradofisica@udea.edu.co"; $EMAIL_PASSWORD="Gmunu-Tmunu=0"; $EMAIL_ADMIN="vicedecacen@udea.edu.co"; //$EMAIL_ADMIN="pregradofisica@udea.edu.co"; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% //IDENTIFICACIONES //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% $DECANOTXT="decana"; $COORDINADOR="Dra. Aura Aleida Jaramillo Valencia"; $COORDINADORTXT="coordinadora"; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% //IMAGENES //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% $LOGOUDEA="http://astronomia-udea.co/principal/sites/default/files"; $MANATWORK="<p><center><img src=img/manatwork.png width=10%></center></p>"; //////////////////////////////////////////////////////////////////////// //LISTAS //////////////////////////////////////////////////////////////////////// $PROGRAMAS_FCEN=array( "astronomia"=>"Astronomía", "biologia"=>"Biología", "estadística"=>"Estadística", "fisica"=>"Física", "matematicas"=>"Matemáticas", "quimica"=>"Química", "tecnoquimica"=>"Tecnología Química", "ninguno"=>"Ninguno escogido" ); $DEPENDENCIAS=array( "fisica"=>"Instituto de Física", "biologia"=>"Instituto de Biología", "quimica"=>"Instituto de Química", "matematicas"=>"Instituto de Matemáticas", "facultad"=>"Toda la Facultad", "decanato"=>"Decanato", "vicedecanato"=>"Vicedecanato", "investigacion"=>"Centro de Investigaciones", ); //////////////////////////////////////////////////////////////////////// //DESTINATARIOS DE CUMPLIDOS //////////////////////////////////////////////////////////////////////// if(!$QTEST){ $DESTINATARIOS_CUMPLIDOS=array( array("Secretaria del Decanato","Luz Mary Castro","luz.castro@udea.edu.co"), array("Secretaria del CIEN","Ana Catalina Fernández","ana.fernandez@udea.edu.co"), array("Programa de Extensión","Natalia López","njlopez76@gmail.com"), array("Fondo de Pasajes Internacionales","Mauricio Toro","fondosinvestigacion@udea.edu.co"), array("Vicerrectoria de Investigación","Mauricio Toro","tramitesinvestigacion@udea.edu.co"), array("Centro de Investigaciones SIU","Ana Eugenia","aeugenia.restrepo@udea.edu.co"), array("Fondos de Vicerrectoría de Docencia","Sandra Monsalve","programacionacademica@udea.edu.co") ); }else{ $DESTINATARIOS_CUMPLIDOS=array( array("Secretaria del Decanato","Luz Mary Castro","pregradofisica@udea.edu.co"), array("Secretaria del CIEN","Maricela Botero","zuluagajorge@gmail.com"), array("Programa de Extensión","Natalia López","astronomia.udea@gmail.com"), array("Fondo de Pasajes Internacionales","Mauricio Toro","jorge.zuluaga@udea.edu.co"), array("Vicerrectoria de Investigación","Mauricio Toro","newton@udea.edu.co"), array("Centro de Investigaciones SIU","Ana Eugenia","newton@udea.edu.co"), array("Fondos de Vicerrectoría de Docencia","Sandra Perez","newton@udea.edu.co") ); } ?>
facom/Sinfin
etc/configuration.php
PHP
gpl-3.0
3,607
<?php if(!$_COOKIE['naszastrona']=="1"){ $plik="licz.txt"; $file=fopen($plik, "r"); flock($file, 1); $liczba=fgets($file, 16); flock($file, 3); fclose($file); $liczba++; echo liczba; $file=fopen($plik, "w"); flock($file, 2); fwrite($file, $liczba++); flock($file, 3); fclose($file); setcookie("naszastrona","1"); } ?>
jsasin/jprogramowania
lab9/odwiedziny.php
PHP
gpl-3.0
335
package view.ActionListeners; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import javax.swing.JFileChooser; import view.JAlphaNotationGUI; public class JMenuItemSaveAsViewActionListener implements ActionListener { private JAlphaNotationGUI gui; public JMenuItemSaveAsViewActionListener(JAlphaNotationGUI gui) { this.gui = gui; } @Override public void actionPerformed(ActionEvent e) { JFileChooser fc = new JFileChooser(); int returnVal = fc.showSaveDialog(fc); File f = new File(fc.getSelectedFile().getPath()); try { FileOutputStream os = new FileOutputStream(f); os.write(gui.GetTextSource().getBytes()); os.close(); } catch (FileNotFoundException e1) { } catch(IOException e2) { } } }
maximusx64/loweralphanotation
src/view/ActionListeners/JMenuItemSaveAsViewActionListener.java
Java
gpl-3.0
891
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), SchoolClass = mongoose.model('SchoolClass'), Student = mongoose.model('Student'), ClassRegistry = mongoose.model('ClassRegistry'), ObjectId = mongoose.Types.ObjectId, async = require('async'), _ = require('lodash'); /** * Find school class by id */ exports.schoolClass = function(req, res, next) { SchoolClass.findOne({ _id: new ObjectId(req.params.schoolClassId), academicYear: new ObjectId(req.params.academicYearId), complex: new ObjectId(req.params.complexId), school: new ObjectId(req.params.schoolId) }, function(err, schoolClass) { if (err) return next(err); if (!schoolClass) return next(new Error('Failed to load school class ' + req.params.schoolClassId)); req.schoolClass = schoolClass; next(); }); }; /** * Create an school class */ exports.create = function(req, res) { var schoolClass = new SchoolClass(req.body); schoolClass.save(function(err) { if (err) { res.jsonp(400, err); } else { res.jsonp(schoolClass); } }); }; /** * Update an school class */ exports.update = function(req, res) { var schoolClass = req.schoolClass; schoolClass = _.extend(schoolClass, req.body); schoolClass.save(function(err) { if (err) { res.jsonp(400, err); } else { res.jsonp(schoolClass); } }); }; /** * Delete an school class */ exports.destroy = function(req, res) { var schoolClass = req.schoolClass; schoolClass.remove(function(err) { if (err) { res.jsonp(400, err); } else { res.jsonp(schoolClass); } }); }; /** * Show an school class */ exports.show = function(req, res) { res.jsonp(req.schoolClass); }; /** * List of school classes */ exports.all = function(req, res) { SchoolClass.find({ academicYear: new ObjectId(req.params.academicYearId), complex: new ObjectId(req.params.complexId), school: new ObjectId(req.params.schoolId) }, function(err, schoolClass) { if (err) { res.jsonp(400, err); } else { res.jsonp(schoolClass); } }); }; exports.allStudents = function (req, res) { async.waterfall([ function (callback) { SchoolClass.findById(req.params.schoolClassId, callback); }, function (schoolClass, callback) { Student.find({'_id': { $in: schoolClass.students} }).populate('user', 'email').exec(callback); } ], function (err, result) { if (err) { res.jsonp(400, err); } else { res.jsonp(result); } }); }; exports.studentStats = function (req, res){ var student = new ObjectId(req.params.studentId); ClassRegistry.aggregate() .match({ school: new ObjectId(req.params.schoolId), complex: new ObjectId(req.params.complexId), academicYear: new ObjectId(req.params.academicYearId), schoolClass: new ObjectId(req.params.schoolClassId), absences: student }) .group({ _id: null, absences: {$addToSet: '$date'} }) .exec(function (err, result){ if(err) { res.jsonp(400, err); } else { res.jsonp(result[0]); } }); };
apuliasoft/aurea
app/controllers/schoolClasses.js
JavaScript
gpl-3.0
3,519
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Native mssql class representing moodle database interface. * * @package core_dml * @copyright 2009 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); require_once(__DIR__.'/moodle_database.php'); require_once(__DIR__.'/mssql_native_moodle_recordset.php'); require_once(__DIR__.'/mssql_native_moodle_temptables.php'); /** * Native mssql class representing moodle database interface. * * @package core_dml * @copyright 2009 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class mssql_native_moodle_database extends moodle_database { protected $mssql = null; protected $last_error_reporting; // To handle mssql driver default verbosity protected $collation; // current DB collation cache /** * Detects if all needed PHP stuff installed. * Note: can be used before connect() * @return mixed true if ok, string if something */ public function driver_installed() { if (!function_exists('mssql_connect')) { return get_string('mssqlextensionisnotpresentinphp', 'install'); } return true; } /** * Returns database family type - describes SQL dialect * Note: can be used before connect() * @return string db family name (mysql, postgres, mssql, oracle, etc.) */ public function get_dbfamily() { return 'mssql'; } /** * Returns more specific database driver type * Note: can be used before connect() * @return string db type mysqli, pgsql, oci, mssql, sqlsrv */ protected function get_dbtype() { return 'mssql'; } /** * Returns general database library name * Note: can be used before connect() * @return string db type pdo, native */ protected function get_dblibrary() { return 'native'; } /** * Returns localised database type name * Note: can be used before connect() * @return string */ public function get_name() { return get_string('nativemssql', 'install'); } /** * Returns localised database configuration help. * Note: can be used before connect() * @return string */ public function get_configuration_help() { return get_string('nativemssqlhelp', 'install'); } /** * Returns localised database description * Note: can be used before connect() * @return string */ public function get_configuration_hints() { $str = get_string('databasesettingssub_mssql', 'install'); $str .= "<p style='text-align:right'><a href=\"javascript:void(0)\" "; $str .= "onclick=\"return window.open('http://docs.moodle.org/en/Installing_MSSQL_for_PHP')\""; $str .= ">"; $str .= '<img src="pix/docs.gif' . '" alt="Docs" class="iconhelp" />'; $str .= get_string('moodledocslink', 'install') . '</a></p>'; return $str; } /** * Connect to db * Must be called before other methods. * @param string $dbhost The database host. * @param string $dbuser The database username. * @param string $dbpass The database username's password. * @param string $dbname The name of the database being connected to. * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used * @param array $dboptions driver specific options * @return bool true * @throws dml_connection_exception if error */ public function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null) { if ($prefix == '' and !$this->external) { //Enforce prefixes for everybody but mysql throw new dml_exception('prefixcannotbeempty', $this->get_dbfamily()); } $driverstatus = $this->driver_installed(); if ($driverstatus !== true) { throw new dml_exception('dbdriverproblem', $driverstatus); } $this->store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions); $dbhost = $this->dbhost; if (isset($dboptions['dbport'])) { if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) { $dbhost .= ','.$dboptions['dbport']; } else { $dbhost .= ':'.$dboptions['dbport']; } } ob_start(); if (!empty($this->dboptions['dbpersist'])) { // persistent connection $this->mssql = mssql_pconnect($dbhost, $this->dbuser, $this->dbpass, true); } else { $this->mssql = mssql_connect($dbhost, $this->dbuser, $this->dbpass, true); } $dberr = ob_get_contents(); ob_end_clean(); if ($this->mssql === false) { $this->mssql = null; throw new dml_connection_exception($dberr); } // already connected, select database and set some env. variables $this->query_start("--mssql_select_db", null, SQL_QUERY_AUX); $result = mssql_select_db($this->dbname, $this->mssql); $this->query_end($result); // No need to set charset. It's UTF8, with transparent conversions // back and forth performed both by FreeTDS or ODBTP // Allow quoted identifiers $sql = "SET QUOTED_IDENTIFIER ON"; $this->query_start($sql, null, SQL_QUERY_AUX); $result = mssql_query($sql, $this->mssql); $this->query_end($result); $this->free_result($result); // Force ANSI nulls so the NULL check was done by IS NULL and NOT IS NULL // instead of equal(=) and distinct(<>) symbols $sql = "SET ANSI_NULLS ON"; $this->query_start($sql, null, SQL_QUERY_AUX); $result = mssql_query($sql, $this->mssql); $this->query_end($result); $this->free_result($result); // Force ANSI warnings so arithmetic/string overflows will be // returning error instead of transparently truncating data $sql = "SET ANSI_WARNINGS ON"; $this->query_start($sql, null, SQL_QUERY_AUX); $result = mssql_query($sql, $this->mssql); $this->query_end($result); // Concatenating null with anything MUST return NULL $sql = "SET CONCAT_NULL_YIELDS_NULL ON"; $this->query_start($sql, null, SQL_QUERY_AUX); $result = mssql_query($sql, $this->mssql); $this->query_end($result); $this->free_result($result); // Set transactions isolation level to READ_COMMITTED // prevents dirty reads when using transactions + // is the default isolation level of MSSQL // Requires database to run with READ_COMMITTED_SNAPSHOT ON $sql = "SET TRANSACTION ISOLATION LEVEL READ COMMITTED"; $this->query_start($sql, NULL, SQL_QUERY_AUX); $result = mssql_query($sql, $this->mssql); $this->query_end($result); $this->free_result($result); // Connection stabilised and configured, going to instantiate the temptables controller $this->temptables = new mssql_native_moodle_temptables($this); return true; } /** * Close database connection and release all resources * and memory (especially circular memory references). * Do NOT use connect() again, create a new instance if needed. */ public function dispose() { parent::dispose(); // Call parent dispose to write/close session and other common stuff before closing connection if ($this->mssql) { mssql_close($this->mssql); $this->mssql = null; } } /** * Called before each db query. * @param string $sql * @param array array of parameters * @param int $type type of query * @param mixed $extrainfo driver specific extra information * @return void */ protected function query_start($sql, array $params=null, $type, $extrainfo=null) { parent::query_start($sql, $params, $type, $extrainfo); // mssql driver tends to send debug to output, we do not need that ;-) $this->last_error_reporting = error_reporting(0); } /** * Called immediately after each db query. * @param mixed db specific result * @return void */ protected function query_end($result) { // reset original debug level error_reporting($this->last_error_reporting); parent::query_end($result); } /** * Returns database server info array * @return array Array containing 'description' and 'version' info */ public function get_server_info() { static $info; if (!$info) { $info = array(); $sql = 'sp_server_info 2'; $this->query_start($sql, null, SQL_QUERY_AUX); $result = mssql_query($sql, $this->mssql); $this->query_end($result); $row = mssql_fetch_row($result); $info['description'] = $row[2]; $this->free_result($result); $sql = 'sp_server_info 500'; $this->query_start($sql, null, SQL_QUERY_AUX); $result = mssql_query($sql, $this->mssql); $this->query_end($result); $row = mssql_fetch_row($result); $info['version'] = $row[2]; $this->free_result($result); } return $info; } /** * Converts short table name {tablename} to real table name * supporting temp tables (#) if detected * * @param string sql * @return string sql */ protected function fix_table_names($sql) { if (preg_match_all('/\{([a-z][a-z0-9_]*)\}/', $sql, $matches)) { foreach($matches[0] as $key=>$match) { $name = $matches[1][$key]; if ($this->temptables->is_temptable($name)) { $sql = str_replace($match, $this->temptables->get_correct_name($name), $sql); } else { $sql = str_replace($match, $this->prefix.$name, $sql); } } } return $sql; } /** * Returns supported query parameter types * @return int bitmask of accepted SQL_PARAMS_* */ protected function allowed_param_types() { return SQL_PARAMS_QM; // Not really, but emulated, see emulate_bound_params() } /** * Returns last error reported by database engine. * @return string error message */ public function get_last_error() { return mssql_get_last_message(); } /** * Return tables in database WITHOUT current prefix * @param bool $usecache if true, returns list of cached tables. * @return array of table names in lowercase and without prefix */ public function get_tables($usecache=true) { if ($usecache and $this->tables !== null) { return $this->tables; } $this->tables = array(); $sql = "SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_name LIKE '$this->prefix%' AND table_type = 'BASE TABLE'"; $this->query_start($sql, null, SQL_QUERY_AUX); $result = mssql_query($sql, $this->mssql); $this->query_end($result); if ($result) { while ($row = mssql_fetch_row($result)) { $tablename = reset($row); if ($this->prefix !== '') { if (strpos($tablename, $this->prefix) !== 0) { continue; } $tablename = substr($tablename, strlen($this->prefix)); } $this->tables[$tablename] = $tablename; } $this->free_result($result); } // Add the currently available temptables $this->tables = array_merge($this->tables, $this->temptables->get_temptables()); return $this->tables; } /** * Return table indexes - everything lowercased. * @param string $table The table we want to get indexes from. * @return array An associative array of indexes containing 'unique' flag and 'columns' being indexed */ public function get_indexes($table) { $indexes = array(); $tablename = $this->prefix.$table; // Indexes aren't covered by information_schema metatables, so we need to // go to sys ones. Skipping primary key indexes on purpose. $sql = "SELECT i.name AS index_name, i.is_unique, ic.index_column_id, c.name AS column_name FROM sys.indexes i JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id JOIN sys.tables t ON i.object_id = t.object_id WHERE t.name = '$tablename' AND i.is_primary_key = 0 ORDER BY i.name, i.index_id, ic.index_column_id"; $this->query_start($sql, null, SQL_QUERY_AUX); $result = mssql_query($sql, $this->mssql); $this->query_end($result); if ($result) { $lastindex = ''; $unique = false; $columns = array(); while ($row = mssql_fetch_assoc($result)) { if ($lastindex and $lastindex != $row['index_name']) { // Save lastindex to $indexes and reset info $indexes[$lastindex] = array('unique' => $unique, 'columns' => $columns); $unique = false; $columns = array(); } $lastindex = $row['index_name']; $unique = empty($row['is_unique']) ? false : true; $columns[] = $row['column_name']; } if ($lastindex ) { // Add the last one if exists $indexes[$lastindex] = array('unique' => $unique, 'columns' => $columns); } $this->free_result($result); } return $indexes; } /** * Returns datailed information about columns in table. This information is cached internally. * @param string $table name * @param bool $usecache * @return array array of database_column_info objects indexed with column names */ public function get_columns($table, $usecache=true) { if ($usecache and isset($this->columns[$table])) { return $this->columns[$table]; } $this->columns[$table] = array(); if (!$this->temptables->is_temptable($table)) { // normal table, get metadata from own schema $sql = "SELECT column_name AS name, data_type AS type, numeric_precision AS max_length, character_maximum_length AS char_max_length, numeric_scale AS scale, is_nullable AS is_nullable, columnproperty(object_id(quotename(table_schema) + '.' + quotename(table_name)), column_name, 'IsIdentity') AS auto_increment, column_default AS default_value FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '{" . $table . "}' ORDER BY ordinal_position"; } else { // temp table, get metadata from tempdb schema $sql = "SELECT column_name AS name, data_type AS type, numeric_precision AS max_length, character_maximum_length AS char_max_length, numeric_scale AS scale, is_nullable AS is_nullable, columnproperty(object_id(quotename(table_schema) + '.' + quotename(table_name)), column_name, 'IsIdentity') AS auto_increment, column_default AS default_value FROM tempdb.INFORMATION_SCHEMA.COLUMNS JOIN tempdb..sysobjects ON name = table_name WHERE id = object_id('tempdb..{" . $table . "}') ORDER BY ordinal_position"; } list($sql, $params, $type) = $this->fix_sql_params($sql, null); $this->query_start($sql, null, SQL_QUERY_AUX); $result = mssql_query($sql, $this->mssql); $this->query_end($result); if (!$result) { return array(); } while ($rawcolumn = mssql_fetch_assoc($result)) { $rawcolumn = (object)$rawcolumn; $info = new stdClass(); $info->name = $rawcolumn->name; $info->type = $rawcolumn->type; $info->meta_type = $this->mssqltype2moodletype($info->type); // Prepare auto_increment info $info->auto_increment = $rawcolumn->auto_increment ? true : false; // Define type for auto_increment columns $info->meta_type = ($info->auto_increment && $info->meta_type == 'I') ? 'R' : $info->meta_type; // id columns being auto_incremnt are PK by definition $info->primary_key = ($info->name == 'id' && $info->meta_type == 'R' && $info->auto_increment); // Put correct length for character and LOB types $info->max_length = $info->meta_type == 'C' ? $rawcolumn->char_max_length : $rawcolumn->max_length; $info->max_length = ($info->meta_type == 'X' || $info->meta_type == 'B') ? -1 : $info->max_length; // Scale $info->scale = $rawcolumn->scale ? $rawcolumn->scale : false; // Prepare not_null info $info->not_null = $rawcolumn->is_nullable == 'NO' ? true : false; // Process defaults $info->has_default = !empty($rawcolumn->default_value); if ($rawcolumn->default_value === NULL) { $info->default_value = NULL; } else { $info->default_value = preg_replace("/^[\(N]+[']?(.*?)[']?[\)]+$/", '\\1', $rawcolumn->default_value); } // Process binary $info->binary = $info->meta_type == 'B' ? true : false; $this->columns[$table][$info->name] = new database_column_info($info); } $this->free_result($result); return $this->columns[$table]; } /** * Normalise values based on varying RDBMS's dependencies (booleans, LOBs...) * * @param database_column_info $column column metadata corresponding with the value we are going to normalise * @param mixed $value value we are going to normalise * @return mixed the normalised value */ protected function normalise_value($column, $value) { $this->detect_objects($value); if (is_bool($value)) { // Always, convert boolean to int $value = (int)$value; } // And continue processing because text columns with numeric info need special handling below if ($column->meta_type == 'B') { // BLOBs need to be properly "packed", but can be inserted directly if so. if (!is_null($value)) { // If value not null, unpack it to unquoted hexadecimal byte-string format $value = unpack('H*hex', $value); // we leave it as array, so emulate_bound_params() can detect it } // easily and "bind" the param ok. } else if ($column->meta_type == 'X') { // MSSQL doesn't cast from int to text, so if text column if (is_numeric($value)) { // and is numeric value then cast to string $value = array('numstr' => (string)$value); // and put into array, so emulate_bound_params() will know how } // to "bind" the param ok, avoiding reverse conversion to number } else if ($value === '') { if ($column->meta_type == 'I' or $column->meta_type == 'F' or $column->meta_type == 'N') { $value = 0; // prevent '' problems in numeric fields } } return $value; } /** * Selectively call mssql_free_result(), avoiding some warnings without using the horrible @ * * @param mssql_resource $resource resource to be freed if possible */ private function free_result($resource) { if (!is_bool($resource)) { // true/false resources cannot be freed mssql_free_result($resource); } } /** * Provides mapping between mssql native data types and moodle_database - database_column_info - ones) * * @param string $mssql_type native mssql data type * @return string 1-char database_column_info data type */ private function mssqltype2moodletype($mssql_type) { $type = null; switch (strtoupper($mssql_type)) { case 'BIT': $type = 'L'; break; case 'INT': case 'SMALLINT': case 'INTEGER': case 'BIGINT': $type = 'I'; break; case 'DECIMAL': case 'REAL': case 'FLOAT': $type = 'N'; break; case 'VARCHAR': case 'NVARCHAR': $type = 'C'; break; case 'TEXT': case 'NTEXT': case 'VARCHAR(MAX)': case 'NVARCHAR(MAX)': $type = 'X'; break; case 'IMAGE': case 'VARBINARY(MAX)': $type = 'B'; break; case 'DATETIME': $type = 'D'; break; } if (!$type) { throw new dml_exception('invalidmssqlnativetype', $mssql_type); } return $type; } /** * Do NOT use in code, to be used by database_manager only! * @param string $sql query * @return bool true * @throws dml_exception A DML specific exception is thrown for any errors. */ public function change_database_structure($sql) { $this->reset_caches(); $this->query_start($sql, null, SQL_QUERY_STRUCTURE); $result = mssql_query($sql, $this->mssql); $this->query_end($result); return true; } /** * Very ugly hack which emulates bound parameters in queries * because the mssql driver doesn't support placeholders natively at all */ protected function emulate_bound_params($sql, array $params=null) { if (empty($params)) { return $sql; } // ok, we have verified sql statement with ? and correct number of params $parts = array_reverse(explode('?', $sql)); $return = array_pop($parts); foreach ($params as $param) { if (is_bool($param)) { $return .= (int)$param; } else if (is_array($param) && isset($param['hex'])) { // detect hex binary, bind it specially $return .= '0x' . $param['hex']; } else if (is_array($param) && isset($param['numstr'])) { // detect numerical strings that *must not* $return .= "N'{$param['numstr']}'"; // be converted back to number params, but bound as strings } else if (is_null($param)) { $return .= 'NULL'; } else if (is_number($param)) { // we can not use is_numeric() because it eats leading zeros from strings like 0045646 $return .= "'".$param."'"; //fix for MDL-24863 to prevent auto-cast to int. } else if (is_float($param)) { $return .= $param; } else { $param = str_replace("'", "''", $param); $return .= "N'$param'"; } $return .= array_pop($parts); } return $return; } /** * Execute general sql query. Should be used only when no other method suitable. * Do NOT use this to make changes in db structure, use database_manager methods instead! * @param string $sql query * @param array $params query parameters * @return bool true * @throws dml_exception A DML specific exception is thrown for any errors. */ public function execute($sql, array $params=null) { list($sql, $params, $type) = $this->fix_sql_params($sql, $params); $rawsql = $this->emulate_bound_params($sql, $params); if (strpos($sql, ';') !== false) { throw new coding_exception('moodle_database::execute() Multiple sql statements found or bound parameters not used properly in query!'); } $this->query_start($sql, $params, SQL_QUERY_UPDATE); $result = mssql_query($rawsql, $this->mssql); $this->query_end($result); $this->free_result($result); return true; } /** * Get a number of records as a moodle_recordset using a SQL statement. * * Since this method is a little less readable, use of it should be restricted to * code where it's possible there might be large datasets being returned. For known * small datasets use get_records_sql - it leads to simpler code. * * The return type is like: * @see function get_recordset. * * @param string $sql the SQL select query to execute. * @param array $params array of sql parameters * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set). * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set). * @return moodle_recordset instance * @throws dml_exception A DML specific exception is thrown for any errors. */ public function get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) { $limitfrom = (int)$limitfrom; $limitnum = (int)$limitnum; $limitfrom = ($limitfrom < 0) ? 0 : $limitfrom; $limitnum = ($limitnum < 0) ? 0 : $limitnum; if ($limitfrom or $limitnum) { if ($limitnum >= 1) { // Only apply TOP clause if we have any limitnum (limitfrom offset is handled later) $fetch = $limitfrom + $limitnum; if (PHP_INT_MAX - $limitnum < $limitfrom) { // Check PHP_INT_MAX overflow $fetch = PHP_INT_MAX; } $sql = preg_replace('/^([\s(])*SELECT([\s]+(DISTINCT|ALL))?(?!\s*TOP\s*\()/i', "\\1SELECT\\2 TOP $fetch", $sql); } } list($sql, $params, $type) = $this->fix_sql_params($sql, $params); $rawsql = $this->emulate_bound_params($sql, $params); $this->query_start($sql, $params, SQL_QUERY_SELECT); $result = mssql_query($rawsql, $this->mssql); $this->query_end($result); if ($limitfrom) { // Skip $limitfrom records if (!@mssql_data_seek($result, $limitfrom)) { // Nothing, most probably seek past the end. mssql_free_result($result); $result = null; } } return $this->create_recordset($result); } protected function create_recordset($result) { return new mssql_native_moodle_recordset($result); } /** * Get a number of records as an array of objects using a SQL statement. * * Return value is like: * @see function get_records. * * @param string $sql the SQL select query to execute. The first column of this SELECT statement * must be a unique value (usually the 'id' field), as it will be used as the key of the * returned array. * @param array $params array of sql parameters * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set). * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set). * @return array of objects, or empty array if no records were found * @throws dml_exception A DML specific exception is thrown for any errors. */ public function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) { $rs = $this->get_recordset_sql($sql, $params, $limitfrom, $limitnum); $results = array(); foreach ($rs as $row) { $id = reset($row); if (isset($results[$id])) { $colname = key($row); debugging("Did you remember to make the first column something unique in your call to get_records? Duplicate value '$id' found in column '$colname'.", DEBUG_DEVELOPER); } $results[$id] = $row; } $rs->close(); return $results; } /** * Selects records and return values (first field) as an array using a SQL statement. * * @param string $sql The SQL query * @param array $params array of sql parameters * @return array of values * @throws dml_exception A DML specific exception is thrown for any errors. */ public function get_fieldset_sql($sql, array $params=null) { $rs = $this->get_recordset_sql($sql, $params); $results = array(); foreach ($rs as $row) { $results[] = reset($row); } $rs->close(); return $results; } /** * Insert new record into database, as fast as possible, no safety checks, lobs not supported. * @param string $table name * @param mixed $params data record as object or array * @param bool $returnit return it of inserted record * @param bool $bulk true means repeated inserts expected * @param bool $customsequence true if 'id' included in $params, disables $returnid * @return bool|int true or new id * @throws dml_exception A DML specific exception is thrown for any errors. */ public function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false) { if (!is_array($params)) { $params = (array)$params; } $returning = ""; $isidentity = false; if ($customsequence) { if (!isset($params['id'])) { throw new coding_exception('moodle_database::insert_record_raw() id field must be specified if custom sequences used.'); } $returnid = false; $columns = $this->get_columns($table); if (isset($columns['id']) and $columns['id']->auto_increment) { $isidentity = true; } // Disable IDENTITY column before inserting record with id, only if the // column is identity, from meta information. if ($isidentity) { $sql = 'SET IDENTITY_INSERT {' . $table . '} ON'; // Yes, it' ON!! list($sql, $xparams, $xtype) = $this->fix_sql_params($sql, null); $this->query_start($sql, null, SQL_QUERY_AUX); $result = mssql_query($sql, $this->mssql); $this->query_end($result); $this->free_result($result); } } else { unset($params['id']); if ($returnid) { $returning = "OUTPUT inserted.id"; } } if (empty($params)) { throw new coding_exception('moodle_database::insert_record_raw() no fields found.'); } $fields = implode(',', array_keys($params)); $qms = array_fill(0, count($params), '?'); $qms = implode(',', $qms); $sql = "INSERT INTO {" . $table . "} ($fields) $returning VALUES ($qms)"; list($sql, $params, $type) = $this->fix_sql_params($sql, $params); $rawsql = $this->emulate_bound_params($sql, $params); $this->query_start($sql, $params, SQL_QUERY_INSERT); $result = mssql_query($rawsql, $this->mssql); // Expected results are: // - true: insert ok and there isn't returned information. // - false: insert failed and there isn't returned information. // - resource: insert executed, need to look for returned (output) // values to know if the insert was ok or no. Posible values // are false = failed, integer = insert ok, id returned. $end = false; if (is_bool($result)) { $end = $result; } else if (is_resource($result)) { $end = mssql_result($result, 0, 0); // Fetch 1st column from 1st row. } $this->query_end($end); // End the query with the calculated $end. if ($returning !== "") { $params['id'] = $end; } $this->free_result($result); if ($customsequence) { // Enable IDENTITY column after inserting record with id, only if the // column is identity, from meta information. if ($isidentity) { $sql = 'SET IDENTITY_INSERT {' . $table . '} OFF'; // Yes, it' OFF!! list($sql, $xparams, $xtype) = $this->fix_sql_params($sql, null); $this->query_start($sql, null, SQL_QUERY_AUX); $result = mssql_query($sql, $this->mssql); $this->query_end($result); $this->free_result($result); } } if (!$returnid) { return true; } return (int)$params['id']; } /** * Insert a record into a table and return the "id" field if required. * * Some conversions and safety checks are carried out. Lobs are supported. * If the return ID isn't required, then this just reports success as true/false. * $data is an object containing needed data * @param string $table The database table to be inserted into * @param object $data A data object with values for one or more fields in the record * @param bool $returnid Should the id of the newly created record entry be returned? If this option is not requested then true/false is returned. * @return bool|int true or new id * @throws dml_exception A DML specific exception is thrown for any errors. */ public function insert_record($table, $dataobject, $returnid=true, $bulk=false) { $dataobject = (array)$dataobject; $columns = $this->get_columns($table); $cleaned = array(); foreach ($dataobject as $field => $value) { if ($field === 'id') { continue; } if (!isset($columns[$field])) { continue; } $column = $columns[$field]; $cleaned[$field] = $this->normalise_value($column, $value); } return $this->insert_record_raw($table, $cleaned, $returnid, $bulk); } /** * Import a record into a table, id field is required. * Safety checks are NOT carried out. Lobs are supported. * * @param string $table name of database table to be inserted into * @param object $dataobject A data object with values for one or more fields in the record * @return bool true * @throws dml_exception A DML specific exception is thrown for any errors. */ public function import_record($table, $dataobject) { $dataobject = (array)$dataobject; $columns = $this->get_columns($table); $cleaned = array(); foreach ($dataobject as $field => $value) { if (!isset($columns[$field])) { continue; } $column = $columns[$field]; $cleaned[$field] = $this->normalise_value($column, $value); } $this->insert_record_raw($table, $cleaned, false, false, true); return true; } /** * Update record in database, as fast as possible, no safety checks, lobs not supported. * @param string $table name * @param mixed $params data record as object or array * @param bool true means repeated updates expected * @return bool true * @throws dml_exception A DML specific exception is thrown for any errors. */ public function update_record_raw($table, $params, $bulk=false) { $params = (array)$params; if (!isset($params['id'])) { throw new coding_exception('moodle_database::update_record_raw() id field must be specified.'); } $id = $params['id']; unset($params['id']); if (empty($params)) { throw new coding_exception('moodle_database::update_record_raw() no fields found.'); } $sets = array(); foreach ($params as $field=>$value) { $sets[] = "$field = ?"; } $params[] = $id; // last ? in WHERE condition $sets = implode(',', $sets); $sql = "UPDATE {" . $table . "} SET $sets WHERE id = ?"; list($sql, $params, $type) = $this->fix_sql_params($sql, $params); $rawsql = $this->emulate_bound_params($sql, $params); $this->query_start($sql, $params, SQL_QUERY_UPDATE); $result = mssql_query($rawsql, $this->mssql); $this->query_end($result); $this->free_result($result); return true; } /** * Update a record in a table * * $dataobject is an object containing needed data * Relies on $dataobject having a variable "id" to * specify the record to update * * @param string $table The database table to be checked against. * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified. * @param bool true means repeated updates expected * @return bool true * @throws dml_exception A DML specific exception is thrown for any errors. */ public function update_record($table, $dataobject, $bulk=false) { $dataobject = (array)$dataobject; $columns = $this->get_columns($table); $cleaned = array(); foreach ($dataobject as $field => $value) { if (!isset($columns[$field])) { continue; } $column = $columns[$field]; $cleaned[$field] = $this->normalise_value($column, $value); } return $this->update_record_raw($table, $cleaned, $bulk); } /** * Set a single field in every table record which match a particular WHERE clause. * * @param string $table The database table to be checked against. * @param string $newfield the field to set. * @param string $newvalue the value to set the field to. * @param string $select A fragment of SQL to be used in a where clause in the SQL call. * @param array $params array of sql parameters * @return bool true * @throws dml_exception A DML specific exception is thrown for any errors. */ public function set_field_select($table, $newfield, $newvalue, $select, array $params=null) { if ($select) { $select = "WHERE $select"; } if (is_null($params)) { $params = array(); } // convert params to ? types list($select, $params, $type) = $this->fix_sql_params($select, $params); // Get column metadata $columns = $this->get_columns($table); $column = $columns[$newfield]; $newvalue = $this->normalise_value($column, $newvalue); if (is_null($newvalue)) { $newfield = "$newfield = NULL"; } else { $newfield = "$newfield = ?"; array_unshift($params, $newvalue); } $sql = "UPDATE {" . $table . "} SET $newfield $select"; list($sql, $params, $type) = $this->fix_sql_params($sql, $params); $rawsql = $this->emulate_bound_params($sql, $params); $this->query_start($sql, $params, SQL_QUERY_UPDATE); $result = mssql_query($rawsql, $this->mssql); $this->query_end($result); $this->free_result($result); return true; } /** * Delete one or more records from a table which match a particular WHERE clause. * * @param string $table The database table to be checked against. * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria). * @param array $params array of sql parameters * @return bool true * @throws dml_exception A DML specific exception is thrown for any errors. */ public function delete_records_select($table, $select, array $params=null) { if ($select) { $select = "WHERE $select"; } $sql = "DELETE FROM {" . $table . "} $select"; list($sql, $params, $type) = $this->fix_sql_params($sql, $params); $rawsql = $this->emulate_bound_params($sql, $params); $this->query_start($sql, $params, SQL_QUERY_UPDATE); $result = mssql_query($rawsql, $this->mssql); $this->query_end($result); $this->free_result($result); return true; } public function sql_cast_char2int($fieldname, $text=false) { if (!$text) { return ' CAST(' . $fieldname . ' AS INT) '; } else { return ' CAST(' . $this->sql_compare_text($fieldname) . ' AS INT) '; } } public function sql_cast_char2real($fieldname, $text=false) { if (!$text) { return ' CAST(' . $fieldname . ' AS REAL) '; } else { return ' CAST(' . $this->sql_compare_text($fieldname) . ' AS REAL) '; } } public function sql_ceil($fieldname) { return ' CEILING(' . $fieldname . ')'; } protected function get_collation() { if (isset($this->collation)) { return $this->collation; } if (!empty($this->dboptions['dbcollation'])) { // perf speedup $this->collation = $this->dboptions['dbcollation']; return $this->collation; } // make some default $this->collation = 'Latin1_General_CI_AI'; $sql = "SELECT CAST(DATABASEPROPERTYEX('$this->dbname', 'Collation') AS varchar(255)) AS SQLCollation"; $this->query_start($sql, null, SQL_QUERY_AUX); $result = mssql_query($sql, $this->mssql); $this->query_end($result); if ($result) { if ($rawcolumn = mssql_fetch_assoc($result)) { $this->collation = reset($rawcolumn); } $this->free_result($result); } return $this->collation; } /** * Returns 'LIKE' part of a query. * * @param string $fieldname usually name of the table column * @param string $param usually bound query parameter (?, :named) * @param bool $casesensitive use case sensitive search * @param bool $accensensitive use accent sensitive search (not all databases support accent insensitive) * @param bool $notlike true means "NOT LIKE" * @param string $escapechar escape char for '%' and '_' * @return string SQL code fragment */ public function sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = '\\') { if (strpos($param, '%') !== false) { debugging('Potential SQL injection detected, sql_like() expects bound parameters (? or :named)'); } $collation = $this->get_collation(); if ($casesensitive) { $collation = str_replace('_CI', '_CS', $collation); } else { $collation = str_replace('_CS', '_CI', $collation); } if ($accentsensitive) { $collation = str_replace('_AI', '_AS', $collation); } else { $collation = str_replace('_AS', '_AI', $collation); } $LIKE = $notlike ? 'NOT LIKE' : 'LIKE'; return "$fieldname COLLATE $collation $LIKE $param ESCAPE '$escapechar'"; } public function sql_concat() { $arr = func_get_args(); foreach ($arr as $key => $ele) { $arr[$key] = ' CAST(' . $ele . ' AS NVARCHAR(255)) '; } $s = implode(' + ', $arr); if ($s === '') { return " '' "; } return " $s "; } public function sql_concat_join($separator="' '", $elements=array()) { for ($n=count($elements)-1; $n > 0 ; $n--) { array_splice($elements, $n, 0, $separator); } $s = implode(' + ', $elements); if ($s === '') { return " '' "; } return " $s "; } public function sql_isempty($tablename, $fieldname, $nullablefield, $textfield) { if ($textfield) { return ' (' . $this->sql_compare_text($fieldname) . " = '') "; } else { return " ($fieldname = '') "; } } /** * Returns the SQL text to be used to calculate the length in characters of one expression. * @param string fieldname or expression to calculate its length in characters. * @return string the piece of SQL code to be used in the statement. */ public function sql_length($fieldname) { return ' LEN(' . $fieldname . ')'; } public function sql_order_by_text($fieldname, $numchars=32) { return ' CONVERT(varchar, ' . $fieldname . ', ' . $numchars . ')'; } /** * Returns the SQL for returning searching one string for the location of another. */ public function sql_position($needle, $haystack) { return "CHARINDEX(($needle), ($haystack))"; } /** * Returns the proper substr() SQL text used to extract substrings from DB * NOTE: this was originally returning only function name * * @param string $expr some string field, no aggregates * @param mixed $start integer or expression evaluating to int * @param mixed $length optional integer or expression evaluating to int * @return string sql fragment */ public function sql_substr($expr, $start, $length=false) { if (count(func_get_args()) < 2) { throw new coding_exception('moodle_database::sql_substr() requires at least two parameters', 'Originaly this function wa s only returning name of SQL substring function, it now requires all parameters.'); } if ($length === false) { return "SUBSTRING($expr, $start, (LEN($expr) - $start + 1))"; } else { return "SUBSTRING($expr, $start, $length)"; } } public function session_lock_supported() { return true; } /** * Obtain session lock * @param int $rowid id of the row with session record * @param int $timeout max allowed time to wait for the lock in seconds * @return bool success */ public function get_session_lock($rowid, $timeout) { if (!$this->session_lock_supported()) { return; } parent::get_session_lock($rowid, $timeout); $timeoutmilli = $timeout * 1000; $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid; // There is one bug in PHP/freetds (both reproducible with mssql_query() // and its mssql_init()/mssql_bind()/mssql_execute() alternative) for // stored procedures, causing scalar results of the execution // to be cast to boolean (true/fals). Here there is one // workaround that forces the return of one recordset resource. // $sql = "sp_getapplock '$fullname', 'Exclusive', 'Session', $timeoutmilli"; $sql = "BEGIN DECLARE @result INT EXECUTE @result = sp_getapplock @Resource='$fullname', @LockMode='Exclusive', @LockOwner='Session', @LockTimeout='$timeoutmilli' SELECT @result END"; $this->query_start($sql, null, SQL_QUERY_AUX); $result = mssql_query($sql, $this->mssql); $this->query_end($result); if ($result) { $row = mssql_fetch_row($result); if ($row[0] < 0) { throw new dml_sessionwait_exception(); } } $this->free_result($result); } public function release_session_lock($rowid) { if (!$this->session_lock_supported()) { return; } if (!$this->used_for_db_sessions) { return; } parent::release_session_lock($rowid); $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid; $sql = "sp_releaseapplock '$fullname', 'Session'"; $this->query_start($sql, null, SQL_QUERY_AUX); $result = mssql_query($sql, $this->mssql); $this->query_end($result); $this->free_result($result); } /** * Driver specific start of real database transaction, * this can not be used directly in code. * @return void */ protected function begin_transaction() { // requires database to run with READ_COMMITTED_SNAPSHOT ON $sql = "BEGIN TRANSACTION"; // Will be using READ COMMITTED isolation $this->query_start($sql, NULL, SQL_QUERY_AUX); $result = mssql_query($sql, $this->mssql); $this->query_end($result); $this->free_result($result); } /** * Driver specific commit of real database transaction, * this can not be used directly in code. * @return void */ protected function commit_transaction() { $sql = "COMMIT TRANSACTION"; $this->query_start($sql, NULL, SQL_QUERY_AUX); $result = mssql_query($sql, $this->mssql); $this->query_end($result); $this->free_result($result); } /** * Driver specific abort of real database transaction, * this can not be used directly in code. * @return void */ protected function rollback_transaction() { $sql = "ROLLBACK TRANSACTION"; $this->query_start($sql, NULL, SQL_QUERY_AUX); $result = mssql_query($sql, $this->mssql); $this->query_end($result); $this->free_result($result); } }
ualberta-eclass/moodle-block_demostudent
lib/dml/mssql_native_moodle_database.php
PHP
gpl-3.0
51,280
<?php session_cache_limiter(''); header('Content-type:image/' . strtolower(substr(strrchr($_GET['filename'],"."),1))); require($_SERVER['DOCUMENT_ROOT'] . '/admin/system/settings/config.php'); $longExpiryOffset = 315360000; header ( "Cache-Control: public, max-age=" . $longExpiryOffset ); header ( "Expires: " . gmdate ( "D, d M Y H:i:s", time () + $longExpiryOffset ) . " GMT" ); $filename = $_GET['filename']; $file_year = $_GET['file_year']; $file_month = $_GET['file_month']; $resize_x = $_GET['resize_x']; $resize_y = $_GET['resize_y']; //if (isset($_GET['resize_mode'])){ $resize_mode = $_GET['resize_mode']; } else { $resize_mode = 'ZEBRA_IMAGE_CROP_CENTER'; }; if (!isset($_GET['resize_mode'])) { $resize_mode = 6; $resize_mode_name = 'ZEBRA_IMAGE_CROP_CENTER'; } else { $resize_mode = $_GET['resize_mode']; if ($resize_mode == 0) { $resize_mode_name = 'ZEBRA_IMAGE_BOXED'; } elseif ($resize_mode == 1) { $resize_mode_name = 'ZEBRA_IMAGE_NOT_BOXED'; } elseif ($resize_mode == 2) { $resize_mode_name = 'ZEBRA_IMAGE_CROP_TOPLEFT'; } elseif ($resize_mode == 3) { $resize_mode_name = 'ZEBRA_IMAGE_CROP_TOPCENTER'; } elseif ($resize_mode == 4) { $resize_mode_name = 'ZEBRA_IMAGE_CROP_TOPRIGHT'; } elseif ($resize_mode == 5) { $resize_mode_name = 'ZEBRA_IMAGE_CROP_MIDDLELEFT'; } elseif ($resize_mode == 6) { $resize_mode_name = 'ZEBRA_IMAGE_CROP_CENTER'; } elseif ($resize_mode == 7) { $resize_mode_name = 'ZEBRA_IMAGE_CROP_MIDDLERIGHT'; } elseif ($resize_mode == 8) { $resize_mode_name = 'ZEBRA_IMAGE_CROP_BOTTOMLEFT'; } elseif ($resize_mode == 9) { $resize_mode_name = 'ZEBRA_IMAGE_CROP_BOTTOMCENTER'; } elseif ($resize_mode == 10) { $resize_mode_name = 'ZEBRA_IMAGE_CROP_BOTTOMRIGHT'; } } $resized_file = $_SERVER['DOCUMENT_ROOT'] . '/uploads/image/' . $file_year . '/' . $file_month . '/' . $resize_x . 'x' . $resize_y . '_' . $resize_mode_name . '/' . $filename; $redirect = 'http://' . $_SERVER['HTTP_HOST'] . '/uploads/image/' . $file_year . '/' . $file_month . '/' . $resize_x . 'x' . $resize_y . '_' . $resize_mode_name . '/' . $filename; $file_extension = strtolower(substr(strrchr($filename,"."),1)); //$headers = apache_request_headers(); if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) { $if_modified_since = preg_replace('/;.*$/', '', $_SERVER['HTTP_IF_MODIFIED_SINCE']); } else { $if_modified_since = ''; } if (file_exists($resized_file)) { // Checking if the client is validating his cache and if it is current. //if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == filemtime($resized_file))) { //header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($resized_file)).' GMT', true, 304); /*if (isset($if_modified_since) && (strtotime($if_modified_since) == filemtime($resized_file))) { // Client's cache IS current, so we just respond '304 Not Modified'. header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($resized_file)).' GMT', true, 304); } else { // Image not cached or cache outdated, we respond '200 OK' and output the image. header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($resized_file)).' GMT', true, 200); header('Content-Length: '.filesize($resized_file)); //header('Content-Type: image/png'); print file_get_contents($resized_file); }*/ //header( 'Location: ' . $redirect ) ; //readfile($resized_file); header( 'Location: ' . $redirect ) ; } else { $image = new Zebra_Image(); $image->source_path = $_SERVER['DOCUMENT_ROOT'] . '/uploads/image/' . $file_year . '/' . $file_month . '/' . $filename; File::create_dir($_SERVER['DOCUMENT_ROOT'] . '/uploads/image/' . $file_year . '/' . $file_month . '/' . $resize_x . 'x' . $resize_y . '_' . $resize_mode_name . '/'); $image->target_path = $resized_file; if (!$image->resize($resize_x, $resize_y, $resize_mode)) show_error($image->error, $image->source_path, $image->target_path); //readfile($resized_file); print file_get_contents($resized_file); } ?>
DaniLatin/Xenium
admin/system/on.the.fly/image.resize.php
PHP
gpl-3.0
4,262
package se.nordicehealth.servlet.impl; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import se.nordicehealth.common.impl.Packet; import se.nordicehealth.servlet.core.PPCPasswordValidation; public class PasswordHandle implements PPCPasswordValidation { public String newPassError(User user, String oldPass, String newPass1, String newPass2) { if (user == null || !user.passwordMatches(oldPass)) { return Packet.INVALID_DETAILS; } if (!newPass1.equals(newPass2)) { return Packet.MISMATCH_NEW; } int ret = validatePassword(newPass1); if (ret < 0) { return Packet.PASSWORD_INVALID_LENGTH; } else if (ret == 0) { return Packet.PASSWORD_SIMPLE; } else { return Packet.SUCCESS; } } private int validatePassword(String password) { if (password.length() < 6 || password.length() > 32) { return -1; } List<Pattern> pattern = Arrays.asList( Pattern.compile("\\p{Lower}"), /* lowercase */ Pattern.compile("\\p{Upper}"), /* uppercase */ Pattern.compile("\\p{Digit}"), /* digits */ Pattern.compile("[\\p{Punct} ]") /* punctuation and space */ ); if (Pattern.compile("[^\\p{Print}]").matcher(password).find()) { return 0; // expression contains non-ascii or non-printable characters } int points = 0; for (Pattern p : pattern) { if (p.matcher(password).find()) { ++points; } } return points - 1; } }
NIASC/PROM_PREM_Collector
src/main/java/se/nordicehealth/servlet/impl/PasswordHandle.java
Java
gpl-3.0
1,418
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "guiChatConsole.h" #include "chat.h" #include "client/client.h" #include "debug.h" #include "gettime.h" #include "client/keycode.h" #include "settings.h" #include "porting.h" #include "client/tile.h" #include "client/fontengine.h" #include "log.h" #include "gettext.h" #include <string> #if USE_FREETYPE #include "irrlicht_changes/CGUITTFont.h" #endif inline u32 clamp_u8(s32 value) { return (u32) MYMIN(MYMAX(value, 0), 255); } GUIChatConsole::GUIChatConsole( gui::IGUIEnvironment* env, gui::IGUIElement* parent, s32 id, ChatBackend* backend, Client* client, IMenuManager* menumgr ): IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, core::rect<s32>(0,0,100,100)), m_chat_backend(backend), m_client(client), m_menumgr(menumgr), m_animate_time_old(porting::getTimeMs()) { // load background settings s32 console_alpha = g_settings->getS32("console_alpha"); m_background_color.setAlpha(clamp_u8(console_alpha)); // load the background texture depending on settings ITextureSource *tsrc = client->getTextureSource(); if (tsrc->isKnownSourceImage("background_chat.jpg")) { m_background = tsrc->getTexture("background_chat.jpg"); m_background_color.setRed(255); m_background_color.setGreen(255); m_background_color.setBlue(255); } else { v3f console_color = g_settings->getV3F("console_color"); m_background_color.setRed(clamp_u8(myround(console_color.X))); m_background_color.setGreen(clamp_u8(myround(console_color.Y))); m_background_color.setBlue(clamp_u8(myround(console_color.Z))); } u16 chat_font_size = g_settings->getU16("chat_font_size"); m_font = g_fontengine->getFont(chat_font_size != 0 ? chat_font_size : FONT_SIZE_UNSPECIFIED, FM_Mono); if (!m_font) { errorstream << "GUIChatConsole: Unable to load mono font" << std::endl; } else { core::dimension2d<u32> dim = m_font->getDimension(L"M"); m_fontsize = v2u32(dim.Width, dim.Height); m_font->grab(); } m_fontsize.X = MYMAX(m_fontsize.X, 1); m_fontsize.Y = MYMAX(m_fontsize.Y, 1); // set default cursor options setCursor(true, true, 2.0, 0.1); } GUIChatConsole::~GUIChatConsole() { if (m_font) m_font->drop(); } void GUIChatConsole::openConsole(f32 scale) { assert(scale > 0.0f && scale <= 1.0f); m_open = true; m_desired_height_fraction = scale; m_desired_height = scale * m_screensize.Y; reformatConsole(); m_animate_time_old = porting::getTimeMs(); IGUIElement::setVisible(true); Environment->setFocus(this); m_menumgr->createdMenu(this); } bool GUIChatConsole::isOpen() const { return m_open; } bool GUIChatConsole::isOpenInhibited() const { return m_open_inhibited > 0; } void GUIChatConsole::closeConsole() { m_open = false; Environment->removeFocus(this); m_menumgr->deletingMenu(this); } void GUIChatConsole::closeConsoleAtOnce() { closeConsole(); m_height = 0; recalculateConsolePosition(); } void GUIChatConsole::replaceAndAddToHistory(const std::wstring &line) { ChatPrompt& prompt = m_chat_backend->getPrompt(); prompt.addToHistory(prompt.getLine()); prompt.replace(line); } void GUIChatConsole::setCursor( bool visible, bool blinking, f32 blink_speed, f32 relative_height) { if (visible) { if (blinking) { // leave m_cursor_blink unchanged m_cursor_blink_speed = blink_speed; } else { m_cursor_blink = 0x8000; // on m_cursor_blink_speed = 0.0; } } else { m_cursor_blink = 0; // off m_cursor_blink_speed = 0.0; } m_cursor_height = relative_height; } void GUIChatConsole::draw() { if(!IsVisible) return; video::IVideoDriver* driver = Environment->getVideoDriver(); // Check screen size v2u32 screensize = driver->getScreenSize(); if (screensize != m_screensize) { // screen size has changed // scale current console height to new window size if (m_screensize.Y != 0) m_height = m_height * screensize.Y / m_screensize.Y; m_screensize = screensize; m_desired_height = m_desired_height_fraction * m_screensize.Y; reformatConsole(); } // Animation u64 now = porting::getTimeMs(); animate(now - m_animate_time_old); m_animate_time_old = now; // Draw console elements if visible if (m_height > 0) { drawBackground(); drawText(); drawPrompt(); } gui::IGUIElement::draw(); } void GUIChatConsole::reformatConsole() { s32 cols = m_screensize.X / m_fontsize.X - 2; // make room for a margin (looks better) s32 rows = m_desired_height / m_fontsize.Y - 1; // make room for the input prompt if (cols <= 0 || rows <= 0) cols = rows = 0; recalculateConsolePosition(); m_chat_backend->reformat(cols, rows); } void GUIChatConsole::recalculateConsolePosition() { core::rect<s32> rect(0, 0, m_screensize.X, m_height); DesiredRect = rect; recalculateAbsolutePosition(false); } void GUIChatConsole::animate(u32 msec) { // animate the console height s32 goal = m_open ? m_desired_height : 0; // Set invisible if close animation finished (reset by openConsole) // This function (animate()) is never called once its visibility becomes false so do not // actually set visible to false before the inhibited period is over if (!m_open && m_height == 0 && m_open_inhibited == 0) IGUIElement::setVisible(false); if (m_height != goal) { s32 max_change = msec * m_screensize.Y * (m_height_speed / 1000.0); if (max_change == 0) max_change = 1; if (m_height < goal) { // increase height if (m_height + max_change < goal) m_height += max_change; else m_height = goal; } else { // decrease height if (m_height > goal + max_change) m_height -= max_change; else m_height = goal; } recalculateConsolePosition(); } // blink the cursor if (m_cursor_blink_speed != 0.0) { u32 blink_increase = 0x10000 * msec * (m_cursor_blink_speed / 1000.0); if (blink_increase == 0) blink_increase = 1; m_cursor_blink = ((m_cursor_blink + blink_increase) & 0xffff); } // decrease open inhibit counter if (m_open_inhibited > msec) m_open_inhibited -= msec; else m_open_inhibited = 0; } void GUIChatConsole::drawBackground() { video::IVideoDriver* driver = Environment->getVideoDriver(); if (m_background != NULL) { core::rect<s32> sourcerect(0, -m_height, m_screensize.X, 0); driver->draw2DImage( m_background, v2s32(0, 0), sourcerect, &AbsoluteClippingRect, m_background_color, false); } else { driver->draw2DRectangle( m_background_color, core::rect<s32>(0, 0, m_screensize.X, m_height), &AbsoluteClippingRect); } } void GUIChatConsole::drawText() { if (m_font == NULL) return; ChatBuffer& buf = m_chat_backend->getConsoleBuffer(); for (u32 row = 0; row < buf.getRows(); ++row) { const ChatFormattedLine& line = buf.getFormattedLine(row); if (line.fragments.empty()) continue; s32 line_height = m_fontsize.Y; s32 y = row * line_height + m_height - m_desired_height; if (y + line_height < 0) continue; for (const ChatFormattedFragment &fragment : line.fragments) { s32 x = (fragment.column + 1) * m_fontsize.X; core::rect<s32> destrect( x, y, x + m_fontsize.X * fragment.text.size(), y + m_fontsize.Y); #if USE_FREETYPE if (m_font->getType() == irr::gui::EGFT_CUSTOM) { // Draw colored text if FreeType is enabled irr::gui::CGUITTFont *tmp = dynamic_cast<irr::gui::CGUITTFont *>(m_font); tmp->draw( fragment.text, destrect, video::SColor(255, 255, 255, 255), false, false, &AbsoluteClippingRect); } else #endif { // Otherwise use standard text m_font->draw( fragment.text.c_str(), destrect, video::SColor(255, 255, 255, 255), false, false, &AbsoluteClippingRect); } } } } void GUIChatConsole::drawPrompt() { if (!m_font) return; u32 row = m_chat_backend->getConsoleBuffer().getRows(); s32 line_height = m_fontsize.Y; s32 y = row * line_height + m_height - m_desired_height; ChatPrompt& prompt = m_chat_backend->getPrompt(); std::wstring prompt_text = prompt.getVisiblePortion(); // FIXME Draw string at once, not character by character // That will only work with the cursor once we have a monospace font for (u32 i = 0; i < prompt_text.size(); ++i) { wchar_t ws[2] = {prompt_text[i], 0}; s32 x = (1 + i) * m_fontsize.X; core::rect<s32> destrect( x, y, x + m_fontsize.X, y + m_fontsize.Y); m_font->draw( ws, destrect, video::SColor(255, 255, 255, 255), false, false, &AbsoluteClippingRect); } // Draw the cursor during on periods if ((m_cursor_blink & 0x8000) != 0) { s32 cursor_pos = prompt.getVisibleCursorPosition(); if (cursor_pos >= 0) { s32 cursor_len = prompt.getCursorLength(); video::IVideoDriver* driver = Environment->getVideoDriver(); s32 x = (1 + cursor_pos) * m_fontsize.X; core::rect<s32> destrect( x, y + m_fontsize.Y * (1.0 - m_cursor_height), x + m_fontsize.X * MYMAX(cursor_len, 1), y + m_fontsize.Y * (cursor_len ? m_cursor_height+1 : 1) ); video::SColor cursor_color(255,255,255,255); driver->draw2DRectangle( cursor_color, destrect, &AbsoluteClippingRect); } } } bool GUIChatConsole::OnEvent(const SEvent& event) { ChatPrompt &prompt = m_chat_backend->getPrompt(); if(event.EventType == EET_KEY_INPUT_EVENT && event.KeyInput.PressedDown) { // Key input if (KeyPress(event.KeyInput) == getKeySetting("keymap_console")) { closeConsole(); // inhibit open so the_game doesn't reopen immediately m_open_inhibited = 50; m_close_on_enter = false; return true; } if (event.KeyInput.Key == KEY_ESCAPE) { closeConsoleAtOnce(); m_close_on_enter = false; // inhibit open so the_game doesn't reopen immediately m_open_inhibited = 1; // so the ESCAPE button doesn't open the "pause menu" return true; } else if(event.KeyInput.Key == KEY_PRIOR) { m_chat_backend->scrollPageUp(); return true; } else if(event.KeyInput.Key == KEY_NEXT) { m_chat_backend->scrollPageDown(); return true; } else if(event.KeyInput.Key == KEY_RETURN) { prompt.addToHistory(prompt.getLine()); std::wstring text = prompt.replace(L""); m_client->typeChatMessage(text); if (m_close_on_enter) { closeConsoleAtOnce(); m_close_on_enter = false; } return true; } else if(event.KeyInput.Key == KEY_UP) { // Up pressed // Move back in history prompt.historyPrev(); return true; } else if(event.KeyInput.Key == KEY_DOWN) { // Down pressed // Move forward in history prompt.historyNext(); return true; } else if(event.KeyInput.Key == KEY_LEFT || event.KeyInput.Key == KEY_RIGHT) { // Left/right pressed // Move/select character/word to the left depending on control and shift keys ChatPrompt::CursorOp op = event.KeyInput.Shift ? ChatPrompt::CURSOROP_SELECT : ChatPrompt::CURSOROP_MOVE; ChatPrompt::CursorOpDir dir = event.KeyInput.Key == KEY_LEFT ? ChatPrompt::CURSOROP_DIR_LEFT : ChatPrompt::CURSOROP_DIR_RIGHT; ChatPrompt::CursorOpScope scope = event.KeyInput.Control ? ChatPrompt::CURSOROP_SCOPE_WORD : ChatPrompt::CURSOROP_SCOPE_CHARACTER; prompt.cursorOperation(op, dir, scope); return true; } else if(event.KeyInput.Key == KEY_HOME) { // Home pressed // move to beginning of line prompt.cursorOperation( ChatPrompt::CURSOROP_MOVE, ChatPrompt::CURSOROP_DIR_LEFT, ChatPrompt::CURSOROP_SCOPE_LINE); return true; } else if(event.KeyInput.Key == KEY_END) { // End pressed // move to end of line prompt.cursorOperation( ChatPrompt::CURSOROP_MOVE, ChatPrompt::CURSOROP_DIR_RIGHT, ChatPrompt::CURSOROP_SCOPE_LINE); return true; } else if(event.KeyInput.Key == KEY_BACK) { // Backspace or Ctrl-Backspace pressed // delete character / word to the left ChatPrompt::CursorOpScope scope = event.KeyInput.Control ? ChatPrompt::CURSOROP_SCOPE_WORD : ChatPrompt::CURSOROP_SCOPE_CHARACTER; prompt.cursorOperation( ChatPrompt::CURSOROP_DELETE, ChatPrompt::CURSOROP_DIR_LEFT, scope); return true; } else if(event.KeyInput.Key == KEY_DELETE) { // Delete or Ctrl-Delete pressed // delete character / word to the right ChatPrompt::CursorOpScope scope = event.KeyInput.Control ? ChatPrompt::CURSOROP_SCOPE_WORD : ChatPrompt::CURSOROP_SCOPE_CHARACTER; prompt.cursorOperation( ChatPrompt::CURSOROP_DELETE, ChatPrompt::CURSOROP_DIR_RIGHT, scope); return true; } else if(event.KeyInput.Key == KEY_KEY_A && event.KeyInput.Control) { // Ctrl-A pressed // Select all text prompt.cursorOperation( ChatPrompt::CURSOROP_SELECT, ChatPrompt::CURSOROP_DIR_LEFT, // Ignored ChatPrompt::CURSOROP_SCOPE_LINE); return true; } else if(event.KeyInput.Key == KEY_KEY_C && event.KeyInput.Control) { // Ctrl-C pressed // Copy text to clipboard if (prompt.getCursorLength() <= 0) return true; std::wstring wselected = prompt.getSelection(); std::string selected = wide_to_utf8(wselected); Environment->getOSOperator()->copyToClipboard(selected.c_str()); return true; } else if(event.KeyInput.Key == KEY_KEY_V && event.KeyInput.Control) { // Ctrl-V pressed // paste text from clipboard if (prompt.getCursorLength() > 0) { // Delete selected section of text prompt.cursorOperation( ChatPrompt::CURSOROP_DELETE, ChatPrompt::CURSOROP_DIR_LEFT, // Ignored ChatPrompt::CURSOROP_SCOPE_SELECTION); } IOSOperator *os_operator = Environment->getOSOperator(); const c8 *text = os_operator->getTextFromClipboard(); if (!text) return true; std::basic_string<unsigned char> str((const unsigned char*)text); prompt.input(std::wstring(str.begin(), str.end())); return true; } else if(event.KeyInput.Key == KEY_KEY_X && event.KeyInput.Control) { // Ctrl-X pressed // Cut text to clipboard if (prompt.getCursorLength() <= 0) return true; std::wstring wselected = prompt.getSelection(); std::string selected = wide_to_utf8(wselected); Environment->getOSOperator()->copyToClipboard(selected.c_str()); prompt.cursorOperation( ChatPrompt::CURSOROP_DELETE, ChatPrompt::CURSOROP_DIR_LEFT, // Ignored ChatPrompt::CURSOROP_SCOPE_SELECTION); return true; } else if(event.KeyInput.Key == KEY_KEY_U && event.KeyInput.Control) { // Ctrl-U pressed // kill line to left end prompt.cursorOperation( ChatPrompt::CURSOROP_DELETE, ChatPrompt::CURSOROP_DIR_LEFT, ChatPrompt::CURSOROP_SCOPE_LINE); return true; } else if(event.KeyInput.Key == KEY_KEY_K && event.KeyInput.Control) { // Ctrl-K pressed // kill line to right end prompt.cursorOperation( ChatPrompt::CURSOROP_DELETE, ChatPrompt::CURSOROP_DIR_RIGHT, ChatPrompt::CURSOROP_SCOPE_LINE); return true; } else if(event.KeyInput.Key == KEY_TAB) { // Tab or Shift-Tab pressed // Nick completion std::list<std::string> names = m_client->getConnectedPlayerNames(); bool backwards = event.KeyInput.Shift; prompt.nickCompletion(names, backwards); return true; } else if (!iswcntrl(event.KeyInput.Char) && !event.KeyInput.Control) { #if defined(__linux__) && (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9) wchar_t wc = L'_'; mbtowc( &wc, (char *) &event.KeyInput.Char, sizeof(event.KeyInput.Char) ); prompt.input(wc); #else prompt.input(event.KeyInput.Char); #endif return true; } } else if(event.EventType == EET_MOUSE_INPUT_EVENT) { if(event.MouseInput.Event == EMIE_MOUSE_WHEEL) { s32 rows = myround(-3.0 * event.MouseInput.Wheel); m_chat_backend->scroll(rows); } } return Parent ? Parent->OnEvent(event) : false; } void GUIChatConsole::setVisible(bool visible) { m_open = visible; IGUIElement::setVisible(visible); if (!visible) { m_height = 0; recalculateConsolePosition(); } }
MrCerealGuy/Stonecraft
src/gui/guiChatConsole.cpp
C++
gpl-3.0
16,677
var gAutoRender = true var gMirrorEntities = false var gNamedStyle = null var gLanguage = 'mscgen' var gDebug = false var gLinkToInterpreter = false var gVerticalLabelAlignment = 'middle' var gIncludeSource = true module.exports = { getAutoRender: function () { return gAutoRender }, setAutoRender: function (pBool) { gAutoRender = pBool }, getMirrorEntities: function () { return gMirrorEntities }, setMirrorEntities: function (pBool) { gMirrorEntities = pBool }, getIncludeSource: function () { return gIncludeSource }, setIncludeSource: function (pBool) { gIncludeSource = pBool }, getVerticalLabelAlignment: function () { return gVerticalLabelAlignment }, setVerticalLabelAlignment: function (pVerticalLabelAlignment) { gVerticalLabelAlignment = pVerticalLabelAlignment }, getNamedStyle: function () { return gNamedStyle }, setNamedStyle: function (pStyle) { gNamedStyle = pStyle }, getLanguage: function () { return gLanguage }, setLanguage: function (pLanguage) { gLanguage = pLanguage }, getDebug: function () { return gDebug }, setDebug: function (pDebug) { gDebug = pDebug }, getLinkToInterpreter: function () { return gLinkToInterpreter }, setLinkToInterpreter: function (pBool) { gLinkToInterpreter = pBool } } /* This file is part of mscgen_js. mscgen_js is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. mscgen_js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with mscgen_js. If not, see <http://www.gnu.org/licenses/>. */
sverweij/mscgen_js
src/script/interpreter/state.js
JavaScript
gpl-3.0
1,921
package com.folioreader.ui.tableofcontents.adapter; import android.content.Context; import android.graphics.Color; import android.support.v4.content.ContextCompat; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.folioreader.Config; import com.folioreader.R; import com.folioreader.model.TOCLinkWrapper; import com.folioreader.util.MultiLevelExpIndListAdapter; import java.util.ArrayList; /** * Created by mahavir on 3/10/17. */ public class TOCAdapter extends MultiLevelExpIndListAdapter { private static final int LEVEL_ONE_PADDING_PIXEL = 15; private TOCCallback callback; private final Context mContext; private String selectedHref; private Config mConfig; public TOCAdapter(Context context, ArrayList<TOCLinkWrapper> tocLinkWrappers, String selectedHref, Config config) { super(tocLinkWrappers); mContext = context; this.selectedHref = selectedHref; this.mConfig = config; } public void setCallback(TOCCallback callback) { this.callback = callback; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new TOCRowViewHolder(LayoutInflater.from(parent.getContext()) .inflate(R.layout.row_table_of_contents, parent, false)); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { TOCRowViewHolder viewHolder = (TOCRowViewHolder) holder; TOCLinkWrapper tocLinkWrapper = (TOCLinkWrapper) getItemAt(position); if (tocLinkWrapper.getChildren() == null || tocLinkWrapper.getChildren().isEmpty()) { viewHolder.children.setVisibility(View.INVISIBLE); } else { viewHolder.children.setVisibility(View.VISIBLE); } viewHolder.sectionTitle.setText(tocLinkWrapper.getTocLink().getTitle()); if (mConfig.isNightMode()) { if (tocLinkWrapper.isGroup()) { viewHolder.children.setImageResource(R.drawable.ic_plus_white_24dp); } else { viewHolder.children.setImageResource(R.drawable.ic_minus_white_24dp); } } else { if (tocLinkWrapper.isGroup()) { viewHolder.children.setImageResource(R.drawable.ic_plus_black_24dp); } else { viewHolder.children.setImageResource(R.drawable.ic_minus_black_24dp); } } int leftPadding = getPaddingPixels(mContext, LEVEL_ONE_PADDING_PIXEL) * (tocLinkWrapper.getIndentation()); viewHolder.view.setPadding(leftPadding, 0, 0, 0); // set color to each indentation level if (tocLinkWrapper.getIndentation() == 0) { viewHolder.view.setBackgroundColor(Color.WHITE); viewHolder.sectionTitle.setTextColor(Color.BLACK); } else if (tocLinkWrapper.getIndentation() == 1) { viewHolder.view.setBackgroundColor(Color.parseColor("#f7f7f7")); viewHolder.sectionTitle.setTextColor(Color.BLACK); } else if (tocLinkWrapper.getIndentation() == 2) { viewHolder.view.setBackgroundColor(Color.parseColor("#b3b3b3")); viewHolder.sectionTitle.setTextColor(Color.WHITE); } else if (tocLinkWrapper.getIndentation() == 3) { viewHolder.view.setBackgroundColor(Color.parseColor("#f7f7f7")); viewHolder.sectionTitle.setTextColor(Color.BLACK); } if (tocLinkWrapper.getChildren() == null || tocLinkWrapper.getChildren().isEmpty()) { viewHolder.children.setVisibility(View.INVISIBLE); } else { viewHolder.children.setVisibility(View.VISIBLE); } if (mConfig.isNightMode()) { viewHolder.container.setBackgroundColor(ContextCompat.getColor(mContext, R.color.black)); viewHolder.children.setBackgroundColor(ContextCompat.getColor(mContext, R.color.black)); viewHolder.sectionTitle.setTextColor(ContextCompat.getColor(mContext, R.color.white)); } else { viewHolder.container.setBackgroundColor(ContextCompat.getColor(mContext, R.color.white)); viewHolder.children.setBackgroundColor(ContextCompat.getColor(mContext, R.color.white)); viewHolder.sectionTitle.setTextColor(ContextCompat.getColor(mContext, R.color.black)); } if (tocLinkWrapper.getTocLink().getHref().equals(selectedHref)) { viewHolder.sectionTitle.setTextColor(mConfig.getThemeColor()); } } public interface TOCCallback { void onTocClicked(int position); void onExpanded(int position); } public class TOCRowViewHolder extends RecyclerView.ViewHolder { public ImageView children; TextView sectionTitle; private LinearLayout container; private View view; TOCRowViewHolder(View itemView) { super(itemView); view = itemView; children = (ImageView) itemView.findViewById(R.id.children); container = (LinearLayout) itemView.findViewById(R.id.container); children.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (callback != null) callback.onExpanded(getAdapterPosition()); } }); sectionTitle = (TextView) itemView.findViewById(R.id.section_title); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (callback != null) callback.onTocClicked(getAdapterPosition()); } }); } } private static int getPaddingPixels(Context context, int dpValue) { // Get the screen's density scale final float scale = context.getResources().getDisplayMetrics().density; // Convert the dps to pixels, based on density scale return (int) (dpValue * scale + 0.5f); } }
mmjang/ankihelper
folioreader/src/main/java/com/folioreader/ui/tableofcontents/adapter/TOCAdapter.java
Java
gpl-3.0
6,346
var winston = require("winston"); var chalk = require("chalk"); var fs = require('fs'); var moment = require('moment'); try { fs.mkdirSync('logs') } catch (err) { if (err.code !== 'EEXIST') throw err } const TERM_COLORS = { error: "red", warn: "yellow", info: "blue", verbose: "white", silly: "grey", }; function winstonColorFormatter(options) { options.level = chalk[TERM_COLORS[options.level]](options.level); return winstonFormatter(options); } function winstonFormatter(options) { return options.timestamp() + ' ' + options.level + ' ' + (options.message ? options.message : '') + (options.meta && Object.keys(options.meta).length ? '\n\t' + JSON.stringify(options.meta) : '' ); } function getTimestamp() { return moment().format('MMM-D-YYYY HH:mm:ss.SSS Z'); } var log = null; function doLog(level, module, messageOrObject) { if (typeof(messageOrObject) === 'object' && !(messageOrObject instanceof Error)) messageOrObject = JSON.stringify(messageOrObject); var message = "[" + module + "] " + messageOrObject; if (!log) { console.log("[preinit] " + getTimestamp() + " - " + level + " - " + message); } else log.log(level, message); } class LogService { static info(module, message) { doLog('info', module, message); } static warn(module, message) { doLog('warn', module, message); } static error(module, message) { doLog('error', module, message); } static verbose(module, message) { doLog('verbose', module, message); } static silly(module, message) { doLog('silly', module, message); } static init(config) { var transports = []; transports.push(new (winston.transports.File)({ json: false, name: "file", filename: config.logging.file, timestamp: getTimestamp, formatter: winstonFormatter, level: config.logging.fileLevel, maxsize: config.logging.rotate.size, maxFiles: config.logging.rotate.count, zippedArchive: false })); if (config.logging.console) { transports.push(new (winston.transports.Console)({ json: false, name: "console", timestamp: getTimestamp, formatter: winstonColorFormatter, level: config.logging.consoleLevel })); } log = new winston.Logger({ transports: transports, levels: { error: 0, warn: 1, info: 2, verbose: 3, silly: 4 } }); } } module.exports = LogService;
turt2live/matrix-appservice-instagram
src/util/LogService.js
JavaScript
gpl-3.0
2,765
# coding=utf-8 import flask_pymongo from app import mongo from .tags import Tag class PostsTags(object): """ 标签文章关系模型 :_id 自动 id :post_id 文章 id :tag_id 标签 id """ def __init__(self): pass @staticmethod def get_post_tags(post_id): """ 获取文章的标签列表 :param post_id: 文章 id :return: 文章下的标签列表 or None """ tags = [] try: results = mongo.db.posts_tags.find({ 'post_id': post_id }) for result in results: tag_id = result.get('tag_id') tag = Tag.get_tag_by_id(tag_id) tags.append(tag) if len(tags) > 0: return tags return None except: return None @staticmethod def add_post_tags_relation(post_id, tag_ids): """ 添加文章与标签关联记录 :param post_id: 文章 id :param tag_ids: 标签 id 列表 :return: 添加成功返回插入的记录数量,否则返回 False """ count = 0 try: mongo.db.posts_tags.delete_many({'post_id': post_id}) except: pass for tag_id in tag_ids: tag_id = int(tag_id) try: result = mongo.db.posts_tags.update_one({ 'post_id': post_id, 'tag_id': tag_id }, { '$setOnInsert': { 'post_id': post_id, 'tag_id': tag_id } }, upsert=True) #count += result.modified_count or result.upserted_id if result.upserted_id: count += 1 except: pass return count if count else False
thundernet8/Plog
app/core/models/posts_tags.py
Python
gpl-3.0
1,897
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Grakn is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. */ package ai.grakn.graph.internal.structure; import ai.grakn.concept.Thing; import ai.grakn.graph.internal.concept.ConceptImpl; import ai.grakn.util.Schema; import org.apache.tinkerpop.gremlin.structure.Direction; import java.util.stream.Stream; /** * <p> * Represent a Shard of a concept * </p> * * <p> * Wraps a {@link VertexElement} which is a shard of a {@link ai.grakn.concept.Concept}. * This is used to break supernodes apart. For example the instances of a {@link ai.grakn.concept.Type} are * spread across several shards. * </p> * * @author fppt */ public class Shard { private final VertexElement vertexElement; public Shard(ConceptImpl owner, VertexElement vertexElement){ this(vertexElement); owner(owner); } public Shard(VertexElement vertexElement){ this.vertexElement = vertexElement; } public VertexElement vertex(){ return vertexElement; } /** * * @return The id of this shard. Strings are used because shards are looked up via the string index. */ public String id(){ return vertex().property(Schema.VertexProperty.ID); } /** * * @param owner Sets the owner of this shard */ private void owner(ConceptImpl owner){ vertex().putEdge(owner.vertex(), Schema.EdgeLabel.SHARD); } /** * Links a new concept to this shard. * * @param concept The concept to link to this shard */ public void link(ConceptImpl concept){ concept.vertex().putEdge(vertex(), Schema.EdgeLabel.ISA); } /** * * @return All the concept linked to this shard */ public <V extends Thing> Stream<V> links(){ return vertex().getEdgesOfType(Direction.IN, Schema.EdgeLabel.ISA). map(EdgeElement::source). map(vertexElement -> vertex().graph().factory().buildConcept(vertexElement)); } /** * * @return The hash code of the underlying vertex */ public int hashCode() { return id().hashCode(); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; Shard shard = (Shard) object; //based on id because vertex comparisons are equivalent return id().equals(shard.id()); } }
sheldonkhall/grakn
grakn-graph/src/main/java/ai/grakn/graph/internal/structure/Shard.java
Java
gpl-3.0
3,136
package sandbox_client; /** * Central organizer for main tabs. Passes information between the server object and the client tabs. * * @author dmayans */ import javafx.application.Platform; import javafx.scene.control.TabPane; public class Client { public static final int TAB_WIDTH = 85; // indices of tabs public static final int CONTROLS = 0; public static final int MAP = 1; public static final int PLANETS = 2; public static final int RESEARCH = 3; public static final int PERSONNEL = 4; public static final int EMPIRE = 5; public static final int STATUS = 6; public static final int COUNCIL = 7; public static final int SIMULATOR = 8; // and their names (keep synchronized) public static final String[] TAB_NAMES = {"Home", "Map", "Planets", "Research", "Personnel", "Empire", "Players", "Council", "Simulator"}; public static final int NUM_TABS = TAB_NAMES.length; // contained tabs private ControlsTab _controls; private MapTab _map; private PlanetsTab _planets; private ResearchTab _research; private PersonnelTab _personnel; private EmpireTab _empire; private StatusTab _status; private CouncilTab _council; @SuppressWarnings("unused") private CombatSimTab _simulator; private AbstractTab[] _tabs = new AbstractTab[NUM_TABS]; private Server _server; // graphics protected final TabPane _root = new TabPane(); public Client() { // the tabs _tabs[CONTROLS] = _controls = new ControlsTab(this); _tabs[MAP] = _map = new MapTab(this); _tabs[PLANETS] = _planets = new PlanetsTab(); _tabs[RESEARCH] = _research = new ResearchTab(); _tabs[PERSONNEL] = _personnel = new PersonnelTab(); _tabs[EMPIRE] = _empire = new EmpireTab(); _tabs[STATUS] = _status = new StatusTab(); _tabs[COUNCIL] = _council = new CouncilTab(); _tabs[SIMULATOR] = _simulator = new CombatSimTab(); // formatting _root.setTabMinWidth(TAB_WIDTH); for(AbstractTab tab : _tabs) { _root.getTabs().add(tab._root); } } // used for focus public void finishInitialization() { _controls.finishInitialization(); } // cleanly inform user about a disconnection public void disconnection() { for(int i=0; i<NUM_TABS; i++) { if(i == STATUS) continue; this.setEnabledGeneric(false, i); } _controls.disconnection(); Database.disconnection(); } // add the server once created public void setServer(Server s) { _server = s; } // kill the server public void killServer() { _server.cleanup(); } // initialize tabs based on player information from server public void namesReceived() { Platform.runLater(new Runnable() { @Override public void run() { for(AbstractTab t : _tabs) { t.addNames(); } } } );} // enables or disables a tab public void setEnabledGeneric(boolean enabled, int index) { _tabs[index]._root.setDisable(!enabled); _controls.setEnabledGeneric(enabled, index); if(_root.getSelectionModel().getSelectedItem() == _tabs[index]._root) { _root.getSelectionModel().select(CONTROLS); } } // handling player names public void tryName(String name) { _server.tryLogin(name); } public void validName(String name) { if(name != null) { _controls.success(); Platform.runLater(new Runnable() { @Override public void run() { for(AbstractTab t : _tabs) { t.localName(name); } } }); } else { _controls.invalidName(); } } // MAP COMMANDS // writes the name of the map to the controls page public void nameMap(String name) { _controls.nameMap(name); } // writes the contents of the map to the diplomacy page public void writeMap(int[] mapdata) { _map.writeMap(mapdata); } // write information to the server public void write(int protocol, String text) { _server.write(protocol, text); } // PLANET CHANGE OWNER public void notifyChown(String planetName, String newOwner, String oldOwner) { _map.planetChown(planetName, newOwner); _planets.planetChown(newOwner, oldOwner); _research.updatePlanet(); _personnel.updateSD(); } // SPACE DOCK public void notifySD(String planetName, boolean sdock) { _map.notifySD(planetName, sdock); _personnel.updateSD(); } // END ROUND public void endRoundStart() { _empire.lock(); } public void endRoundFinish() { _empire.unlock(); } // TECH AND PERSONNEL public void research(String player, String tech) { _status.update(); Platform.runLater(new Runnable() { @Override public void run() { _research.research(player, tech); } }); } public void forget(String player, String tech) { _status.update(); Platform.runLater(new Runnable() { @Override public void run() { _research.forget(player, tech); } }); } public void hire(String player, String person) { _status.update(); Platform.runLater(new Runnable() { @Override public void run() { _personnel.hire(player, person); } }); } public void release(String player, String person) { _status.update(); Platform.runLater(new Runnable() { @Override public void run() { _personnel.release(player, person); } }); } // EMPIRE public void advancePlayer(String player) { if(player.equals(Database.getName())) { Platform.runLater(new Runnable() { @Override public void run() { _empire.advance(); _personnel.updateSD(); } }); } _status.update(); } // RESOLUTION public void resolution(String resolution1, String resolution2) { _council.resolved(resolution1, resolution2); } // RESOLUTION RESULT public void resolutionResult(){ _council.result(); } }
Rcloutier778/TIMEGA
sandbox_client/Client.java
Java
gpl-3.0
5,616
<?php /** * TrcIMPLAN Sitio Web - SMIIndicadoresLaLaguna EconomiaCrecimientoEnLosEmpleadosEnElSectorFormal * * Copyright (C) 2017 Guillermo Valdés Lozano <guivaloz@movimientolibre.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @package TrcIMPLANSitioWeb */ namespace SMIIndicadoresLaLaguna; /** * Clase EconomiaCrecimientoEnLosEmpleadosEnElSectorFormal */ class EconomiaCrecimientoEnLosEmpleadosEnElSectorFormal extends \SMIBase\PublicacionWeb { /** * Constructor */ public function __construct() { // Ejecutar constructor en el padre parent::__construct(); // Título y fecha $this->nombre = 'Crecimiento en los Empleados en el Sector Formal en La Laguna'; $this->fecha = '2015-07-14T13:36:14'; // El nombre del archivo a crear $this->archivo = 'economia-crecimiento-en-los-empleados-en-el-sector-formal'; // La descripción y claves dan información a los buscadores y redes sociales $this->descripcion = 'Incluido en el subíndice de "Gobiernos Eficientes y Eficaces". Mide la tasa de cambio del número de empleados en el sector formal entre 2008 y 2012.'; $this->claves = 'IMPLAN, La Laguna, Índice de Competitividad Urbana, Empleo'; // Para el Organizador $this->categorias = array('Índice de Competitividad Urbana', 'Empleo'); $this->fuentes = array('IMCO'); $this->regiones = array('La Laguna'); } // constructor /** * Datos Estructura * * @return array Arreglo con arreglos asociativos */ public function datos_estructura() { return array( 'fecha' => array('enca' => 'Fecha', 'formato' => 'fecha'), 'valor' => array('enca' => 'Dato', 'formato' => 'porcentaje'), 'fuente_nombre' => array('enca' => 'Fuente', 'formato' => 'texto'), 'notas' => array('enca' => 'Notas', 'formato' => 'texto')); } // datos_estructura /** * Datos * * @return array Arreglo con arreglos asociativos */ public function datos() { return array( array('fecha' => '2008-12-31', 'valor' => '-7.4600', 'fuente_nombre' => 'IMCO'), array('fecha' => '2009-12-31', 'valor' => '-7.4600', 'fuente_nombre' => 'IMCO'), array('fecha' => '2010-12-31', 'valor' => '-7.4600', 'fuente_nombre' => 'IMCO'), array('fecha' => '2011-12-31', 'valor' => '-7.4600', 'fuente_nombre' => 'IMCO'), array('fecha' => '2012-12-31', 'valor' => '-7.4600', 'fuente_nombre' => 'IMCO')); // formateado 0, valor 10, crudo 5 } // datos /** * Otras Regiones Estructura * * @return array Arreglo con arreglos asociativos */ public function otras_regiones_estructura() { return array( 'region_nombre' => array('enca' => 'Región', 'formato' => 'texto'), 'fecha' => array('enca' => 'Fecha', 'formato' => 'fecha'), 'valor' => array('enca' => 'Dato', 'formato' => 'porcentaje'), 'fuente_nombre' => array('enca' => 'Fuente', 'formato' => 'texto'), 'notas' => array('enca' => 'Notas', 'formato' => 'texto')); } // otras_regiones_estructura /** * Otras regiones * * @return array Arreglo con arreglos asociativos */ public function otras_regiones() { return array( array('region_nombre' => 'Torreón', 'fecha' => '2012-12-31', 'valor' => '-5.6600', 'fuente_nombre' => 'IMCO'), array('region_nombre' => 'Gómez Palacio', 'fecha' => '2012-12-31', 'valor' => '-9.7700', 'fuente_nombre' => 'IMCO'), array('region_nombre' => 'Lerdo', 'fecha' => '2012-12-31', 'valor' => '-14.2700', 'fuente_nombre' => 'IMCO'), array('region_nombre' => 'Matamoros', 'fecha' => '2012-12-31', 'valor' => '-4.2700', 'fuente_nombre' => 'IMCO'), array('region_nombre' => 'La Laguna', 'fecha' => '2012-12-31', 'valor' => '-7.4600', 'fuente_nombre' => 'IMCO')); } // otras_regiones /** * Mapas * * @return string Código HTML con el iframe de Carto */ public function mapas() { return NULL; } // mapas /** * Observaciones * * @return string Markdown */ public function observaciones() { return NULL; } // observaciones } // Clase EconomiaCrecimientoEnLosEmpleadosEnElSectorFormal ?>
TRCIMPLAN/trcimplan.github.io
lib/SMIIndicadoresLaLaguna/EconomiaCrecimientoEnLosEmpleadosEnElSectorFormal.php
PHP
gpl-3.0
5,051
<?php return [ /* |-------------------------------------------------------------------------- | Application Environment |-------------------------------------------------------------------------- | | This value determines the "environment" your application is currently | running in. This may determine how you prefer to configure various | services your application utilizes. Set this in your ".env" file. | */ 'env' => env('APP_ENV', 'production'), /* |-------------------------------------------------------------------------- | Application Debug Mode |-------------------------------------------------------------------------- | | When your application is in debug mode, detailed error messages with | stack traces will be shown on every error that occurs within your | application. If disabled, a simple generic error page is shown. | */ 'debug' => env('APP_DEBUG', false), /* |-------------------------------------------------------------------------- | Application URL |-------------------------------------------------------------------------- | | This URL is used by the console to properly generate URLs when using | the Artisan command line tool. You should set this to the root of | your application so that it is used when running Artisan tasks. | */ 'url' => env('APP_URL', 'http://localhost'), /* |-------------------------------------------------------------------------- | Application Timezone |-------------------------------------------------------------------------- | | Here you may specify the default timezone for your application, which | will be used by the PHP date and date-time functions. We have gone | ahead and set this to a sensible default for you out of the box. | */ 'timezone' => 'UTC', /* |-------------------------------------------------------------------------- | Application Locale Configuration |-------------------------------------------------------------------------- | | The application locale determines the default locale that will be used | by the translation service provider. You are free to set this value | to any of the locales which will be supported by the application. | */ 'locale' => 'en', /* |-------------------------------------------------------------------------- | Application Fallback Locale |-------------------------------------------------------------------------- | | The fallback locale determines the locale to use when the current one | is not available. You may change the value to correspond to any of | the language folders that are provided through your application. | */ 'fallback_locale' => 'en', /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | This key is used by the Illuminate encrypter service and should be set | to a random, 32 character string, otherwise these encrypted strings | will not be safe. Please do this before deploying an application! | */ 'key' => env('APP_KEY'), 'cipher' => 'AES-256-CBC', /* |-------------------------------------------------------------------------- | Logging Configuration |-------------------------------------------------------------------------- | | Here you may configure the log settings for your application. Out of | the box, Laravel uses the Monolog PHP logging library. This gives | you a variety of powerful log handlers / formatters to utilize. | | Available Settings: "single", "daily", "syslog", "errorlog" | */ 'log' => env('APP_LOG', 'single'), 'log_level' => env('APP_LOG_LEVEL', 'debug'), /* |-------------------------------------------------------------------------- | Autoloaded Service Providers |-------------------------------------------------------------------------- | | The service providers listed here will be automatically loaded on the | request to your application. Feel free to add your own services to | this array to grant expanded functionality to your applications. | */ 'providers' => [ /* * Laravel Framework Service Providers... */ Illuminate\Auth\AuthServiceProvider::class, Illuminate\Broadcasting\BroadcastServiceProvider::class, Illuminate\Bus\BusServiceProvider::class, Illuminate\Cache\CacheServiceProvider::class, Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class, Illuminate\Cookie\CookieServiceProvider::class, Illuminate\Database\DatabaseServiceProvider::class, Illuminate\Encryption\EncryptionServiceProvider::class, Illuminate\Filesystem\FilesystemServiceProvider::class, Illuminate\Foundation\Providers\FoundationServiceProvider::class, Illuminate\Hashing\HashServiceProvider::class, Illuminate\Mail\MailServiceProvider::class, Illuminate\Pagination\PaginationServiceProvider::class, Illuminate\Pipeline\PipelineServiceProvider::class, Illuminate\Queue\QueueServiceProvider::class, Illuminate\Redis\RedisServiceProvider::class, Illuminate\Auth\Passwords\PasswordResetServiceProvider::class, Illuminate\Session\SessionServiceProvider::class, Illuminate\Translation\TranslationServiceProvider::class, Illuminate\Validation\ValidationServiceProvider::class, Illuminate\View\ViewServiceProvider::class, /* * Application Service Providers... */ App\Providers\AppServiceProvider::class, App\Providers\AuthServiceProvider::class, App\Providers\EventServiceProvider::class, App\Providers\RouteServiceProvider::class, /* * New Service Providers */ App\Modules\ModulesServiceProvider::class, ], /* |-------------------------------------------------------------------------- | Class Aliases |-------------------------------------------------------------------------- | | This array of class aliases will be registered when this application | is started. However, feel free to register as many as you wish as | the aliases are "lazy" loaded so they don't hinder performance. | */ 'aliases' => [ 'App' => Illuminate\Support\Facades\App::class, 'Artisan' => Illuminate\Support\Facades\Artisan::class, 'Auth' => Illuminate\Support\Facades\Auth::class, 'Blade' => Illuminate\Support\Facades\Blade::class, 'Cache' => Illuminate\Support\Facades\Cache::class, 'Config' => Illuminate\Support\Facades\Config::class, 'Cookie' => Illuminate\Support\Facades\Cookie::class, 'Crypt' => Illuminate\Support\Facades\Crypt::class, 'DB' => Illuminate\Support\Facades\DB::class, 'Eloquent' => Illuminate\Database\Eloquent\Model::class, 'Event' => Illuminate\Support\Facades\Event::class, 'File' => Illuminate\Support\Facades\File::class, 'Gate' => Illuminate\Support\Facades\Gate::class, 'Hash' => Illuminate\Support\Facades\Hash::class, 'Lang' => Illuminate\Support\Facades\Lang::class, 'Log' => Illuminate\Support\Facades\Log::class, 'Mail' => Illuminate\Support\Facades\Mail::class, 'Password' => Illuminate\Support\Facades\Password::class, 'Queue' => Illuminate\Support\Facades\Queue::class, 'Redirect' => Illuminate\Support\Facades\Redirect::class, 'Redis' => Illuminate\Support\Facades\Redis::class, 'Request' => Illuminate\Support\Facades\Request::class, 'Response' => Illuminate\Support\Facades\Response::class, 'Route' => Illuminate\Support\Facades\Route::class, 'Schema' => Illuminate\Support\Facades\Schema::class, 'Session' => Illuminate\Support\Facades\Session::class, 'Storage' => Illuminate\Support\Facades\Storage::class, 'URL' => Illuminate\Support\Facades\URL::class, 'Validator' => Illuminate\Support\Facades\Validator::class, 'View' => Illuminate\Support\Facades\View::class, ], ];
ishoshani/HealthSnacks
HealthPage/config/app.php
PHP
gpl-3.0
8,408
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'save', 'nb', { toolbar: 'Lagre' } );
ernestbuffington/PHP-Nuke-Titanium
includes/wysiwyg/ckeditor/plugins/save/lang/nb.js
JavaScript
gpl-3.0
228
package com.topdata.toppontoweb.services.gerafrequencia.services.bancodehoras; import com.topdata.toppontoweb.entity.bancohoras.BancoHoras; import com.topdata.toppontoweb.entity.configuracoes.SequenciaPercentuais; import com.topdata.toppontoweb.entity.tipo.TipoDia; import com.topdata.toppontoweb.services.gerafrequencia.entity.bancodehoras.BancodeHorasAcrescimosApi; import com.topdata.toppontoweb.services.gerafrequencia.entity.bancodehoras.BancodeHorasApi; import com.topdata.toppontoweb.services.gerafrequencia.entity.bancodehoras.TabelaCreditoSaldoUnico; import com.topdata.toppontoweb.services.gerafrequencia.entity.calculo.Calculo; import com.topdata.toppontoweb.services.gerafrequencia.entity.calculo.SaidaDia; import com.topdata.toppontoweb.services.gerafrequencia.entity.saldo.SaldoDiaCompensado; import com.topdata.toppontoweb.services.gerafrequencia.entity.saldo.SaldoExtras; import com.topdata.toppontoweb.services.gerafrequencia.entity.tabela.TabelaSequenciaPercentuais; import com.topdata.toppontoweb.services.gerafrequencia.utils.CONSTANTES; import com.topdata.toppontoweb.services.gerafrequencia.utils.Utils; import java.time.Duration; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.function.Consumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Realiza todos os acréscimos no saldo de crédito do banco de horas de acordo * com a tabela de percentuais cadastrada * * @author enio.junior */ public class BancodeHorasAcrescimosService { public final static Logger LOGGER = LoggerFactory.getLogger(BancodeHorasAcrescimosService.class.getName()); private final BancodeHorasAcrescimosApi bancodeHorasAcrescimos; private final Calculo calculo; private final SaldosBHMensal saldosBHMensal; private BancodeHorasApi bancodeHoras; private List<SequenciaPercentuais> sequenciaPercentuaisList; private List<SequenciaPercentuais> sequenciaPercentuaisSaldoMensalList; private List<SequenciaPercentuais> sequenciaPercentuaisNoturnosList; private boolean tipoLimiteDiario; private BancoHoras bancoHoras; private Duration compensadasDiurnas; private Duration compensadasNoturnas; private Duration diferencaAcrescimoDiurnas; private Duration diferencaAcrescimoDiurnasACompensar; private Duration diferencaAcrescimoNoturnas; private Duration diferencaAcrescimoNoturnasACompensar; private Duration somaDiurnasTabelaAcrescimosBH; private Duration somaNoturnasTabelaAcrescimosBH; private Duration somaCompensadasTabelaAcrescimosBH; public BancodeHorasAcrescimosService(Calculo calculo) { this.bancodeHorasAcrescimos = new BancodeHorasAcrescimosApi(); this.calculo = calculo; this.saldosBHMensal = this.calculo.getSaldosBHMensal(); } public void getCalculaAcrescimos(SaidaDia saidaDia, BancodeHorasApi bancodeHoras) { this.sequenciaPercentuaisList = this.calculo.getFuncionarioService() .getFuncionarioBancodeHorasService().getPercentuaisTipoDiaBancoDeHoras( this.calculo.getRegrasService().isFeriado(), this.calculo.getRegrasService().isRealizaCompensacao()); //Calculo.getRegrasService().isDiaCompensadoSemSomenteJustificativa() this.sequenciaPercentuaisNoturnosList = this.calculo.getFuncionarioService().getFuncionarioBancodeHorasService().getPercentuaisSomenteNoturnosBancoDeHoras(); this.bancoHoras = this.calculo.getFuncionarioService().getFuncionarioBancodeHorasService().getBancoDeHoras(); this.tipoLimiteDiario = this.bancoHoras.getTipoLimiteDiario(); //Cria controle quando tipo de bh mensal if (!this.tipoLimiteDiario) { LOGGER.debug("BH tipo mensal... dia: {} - funcionário: {} ", this.calculo.getDiaProcessado(), this.calculo.getNomeFuncionario()); inicializaSaldosBHMensal(); } else { LOGGER.debug("BH tipo diário... dia: {} - funcionário: {} ", this.calculo.getDiaProcessado(), this.calculo.getNomeFuncionario()); } this.bancodeHoras = bancodeHoras; this.bancodeHorasAcrescimos.setBancodeHoras(bancodeHoras); bancodeHoras.setTotalAcrescimosDiurnas(Duration.ZERO); bancodeHoras.setTotalAcrescimosNoturnas(Duration.ZERO); bancodeHoras.setSaldoExtrasDiurnas(saidaDia.getSaldoExtras().getDiurnas()); //Ajustar percentual Noturno getAjustePercentualNoturno(saidaDia.getSaldoExtras()); //Enquadrar dentro dos limites do dia setEnquadrarLimites(); //Seta de fato quanto das horas extras vão para o banco de horas (Dentro dos limites) //O restante continua sendo hora extra if (bancodeHoras.getSaldoExtrasDiurnas() != null) { saidaDia.getSaldoExtras().setDiurnas(saidaDia.getSaldoExtras().getDiurnas().minus(bancodeHoras.getSaldoExtrasDiurnas())); } if (bancodeHoras.getSaldoExtrasNoturnas() != null) { saidaDia.getSaldoExtras().setNoturnas(saidaDia.getSaldoExtras().getNoturnas().minus(bancodeHoras.getSaldoExtrasNoturnas())); } saidaDia.setTabelaExtrasList(this.calculo.getFuncionarioService().getFuncionarioJornadaService().getTabelaExtrasList(saidaDia.getSaldoExtras())); //Realiza as operações de crédito setAcrescimos(bancodeHoras); } public void getCalculaAcrescimosCompensadas(SaidaDia saidaDia, BancodeHorasApi bancodeHoras) { this.bancodeHoras = bancodeHoras; this.bancodeHorasAcrescimos.setBancodeHoras(bancodeHoras); this.sequenciaPercentuaisList = this.calculo.getFuncionarioService() .getFuncionarioBancodeHorasService() .getPercentuaisTipoDiaBancoDeHorasCompensadas(); if (this.bancodeHorasAcrescimos.getTabelaTipoDiaList() == null) { this.bancodeHorasAcrescimos.setTabelaTipoDiaList(new ArrayList<>()); } Date dataCompensada = this.calculo.getFuncionarioService() .getFuncionarioCompensacoesService().getCompensandoDia().getDataCompensada(); SaldoDiaCompensado saldoDiaCompensado = Utils.getSaldoDiaCompensado(dataCompensada, this.calculo.getEntradaAPI().getSaldoDiaCompensadoList()); setDiurnasCompensadas(saldoDiaCompensado); setNoturnasCompensadas(saldoDiaCompensado); } private void setDiurnasCompensadas(SaldoDiaCompensado saldoDiaCompensado) { this.compensadasDiurnas = saldoDiaCompensado.getCompensadasDiurnas(); this.diferencaAcrescimoDiurnas = compensadasDiurnas; this.diferencaAcrescimoDiurnasACompensar = saldoDiaCompensado.getACompensarDiurnas(); if (this.sequenciaPercentuaisList.size() > 0) { this.sequenciaPercentuaisList .stream() .sorted(new Utils.ordenaSequencia()) .forEach(new acrescimosDiurnasCompensadas()); } else { //Como não tem limite cadastrado, aloca todas as horas no 1 limite sem acréscimos setTabelaPercentuaisTipoDiaCompensado(null); this.bancodeHorasAcrescimos.getTabela().setDivisaoDiurnas(this.compensadasDiurnas); this.bancodeHorasAcrescimos.getTabelaTipoDiaList().add(this.bancodeHorasAcrescimos.getTabela()); } //Atualizar a lista de dias que compensaram com os acréscimos realizados //tipo de dia compensado saldoDiaCompensado.setCompensadasDiurnas(this.diferencaAcrescimoDiurnas); saldoDiaCompensado.setACompensarDiurnas(this.diferencaAcrescimoDiurnasACompensar); } private class acrescimosDiurnasCompensadas implements Consumer<SequenciaPercentuais> { public acrescimosDiurnasCompensadas() { } @Override public void accept(SequenciaPercentuais sequenciaPercentual) { setTabelaPercentuaisTipoDiaCompensado(sequenciaPercentual); //CAMPO ACIMA 24 HORAS //Horas Diurnas por limites para o cálculo de percentuais if (compensadasDiurnas.toMillis() > 0) { Date horas = Utils.getDataAjustaDiferenca3horas(sequenciaPercentual.getHoras()); if (compensadasDiurnas.toMillis() > Utils.getHorasAcima24horas(horas.toInstant()).toMillis()) { bancodeHorasAcrescimos.getTabela().setDivisaoDiurnas(Utils.getHorasAcima24horas(horas.toInstant())); compensadasDiurnas = compensadasDiurnas.minus(Utils.getHorasAcima24horas(horas.toInstant())); } else { bancodeHorasAcrescimos.getTabela().setDivisaoDiurnas(compensadasDiurnas); compensadasDiurnas = compensadasDiurnas.minus(bancodeHoras.getSaldoAusenciasDiurnas()); } //Somente tipo diário multiplicar pelos acréscimos Duration horasComAcrescimo = Utils.getAcrescimoPercentualTabelasPercentuais(bancodeHorasAcrescimos.getTabela().getDivisaoDiurnas(), bancodeHorasAcrescimos.getTabela().getAcrescimo()); Duration acrescimoRealizado = horasComAcrescimo.minus(bancodeHorasAcrescimos.getTabela().getDivisaoDiurnas()); //Total compensado com os acréscimos //Pega somente a diferença e soma no que já está lá diferencaAcrescimoDiurnas = diferencaAcrescimoDiurnas.plus(acrescimoRealizado); diferencaAcrescimoDiurnasACompensar = diferencaAcrescimoDiurnasACompensar.minus(acrescimoRealizado); if (diferencaAcrescimoDiurnasACompensar.isNegative()) { diferencaAcrescimoDiurnasACompensar = Duration.ZERO; } bancodeHorasAcrescimos.getTabela().setResultadoDiurnas(horasComAcrescimo); bancodeHoras.setTotalAcrescimosDiurnas(bancodeHoras.getTotalAcrescimosDiurnas().plus(bancodeHorasAcrescimos.getTabela().getResultadoDiurnas())); bancodeHorasAcrescimos.getTabelaTipoDiaList().add(bancodeHorasAcrescimos.getTabela()); } } } /** * * @param saldoDiaCompensado */ private void setNoturnasCompensadas(SaldoDiaCompensado saldoDiaCompensado) { this.compensadasNoturnas = saldoDiaCompensado.getCompensadasNoturnas(); this.diferencaAcrescimoNoturnas = this.compensadasNoturnas; this.diferencaAcrescimoNoturnasACompensar = saldoDiaCompensado.getACompensarNoturnas(); this.bancodeHorasAcrescimos.getTabelaTipoDiaList() .stream() .sorted(new Utils.ordenaSequencia()) .forEach(new AcrescimosNoturnos()); //Atualizar a lista de dias que compensaram com os acréscimos realizados //tipo de dia compensado saldoDiaCompensado.setCompensadasNoturnas(this.diferencaAcrescimoNoturnas); saldoDiaCompensado.setACompensarNoturnas(this.diferencaAcrescimoNoturnasACompensar); } /** * Tabela acréscimos noturnos de compensação */ private class AcrescimosNoturnos implements Consumer<TabelaSequenciaPercentuais> { public AcrescimosNoturnos() { } @Override public void accept(TabelaSequenciaPercentuais tabelaTipoDia) { if (sequenciaPercentuaisList.size() > 0) { //CAMPO ACIMA 24 HORAS //Horas Noturnas por limites para o cálculo de percentuais Date horas = Utils.getDataAjustaDiferenca3horas(tabelaTipoDia.getHoras()); if (compensadasNoturnas.toMillis() > 0 && tabelaTipoDia.getDivisaoDiurnas().toMillis() < Utils.getHorasAcima24horas(horas.toInstant()).toMillis()) { if (compensadasNoturnas.toMillis() > Utils.getHorasAcima24horas(horas.toInstant()).minus(tabelaTipoDia.getDivisaoNoturnas()).toMillis()) { tabelaTipoDia.setDivisaoNoturnas(Utils.getHorasAcima24horas(horas.toInstant()).minus(tabelaTipoDia.getDivisaoNoturnas())); compensadasNoturnas = compensadasNoturnas.minus(Utils.getHorasAcima24horas(horas.toInstant()).minus(tabelaTipoDia.getDivisaoNoturnas())); } else { tabelaTipoDia.setDivisaoNoturnas(bancodeHoras.getSaldoExtrasNoturnas()); compensadasNoturnas = compensadasNoturnas.minus(bancodeHoras.getSaldoExtrasNoturnas()); } //Somente tipo diário realizar os acréscimos Duration horasComAcrescimo = Utils.getAcrescimoPercentualTabelasPercentuais(tabelaTipoDia.getDivisaoNoturnas(), tabelaTipoDia.getAcrescimo()); Duration acrescimoRealizado = horasComAcrescimo.minus(tabelaTipoDia.getDivisaoNoturnas()); //Total compensado com os acréscimos //Pega somente a diferença e soma no que já está lá diferencaAcrescimoNoturnas = diferencaAcrescimoNoturnas.plus(acrescimoRealizado); diferencaAcrescimoNoturnasACompensar = diferencaAcrescimoNoturnasACompensar.minus(acrescimoRealizado); if (diferencaAcrescimoNoturnasACompensar.isNegative()) { diferencaAcrescimoNoturnasACompensar = Duration.ZERO; } tabelaTipoDia.setResultadoNoturnas(horasComAcrescimo); bancodeHoras.setTotalAcrescimosNoturnas(bancodeHoras.getTotalAcrescimosNoturnas().plus(tabelaTipoDia.getResultadoNoturnas())); } } else { //Como não tem limite cadastrado, aloca todas as horas no 1 limite sem acréscimos tabelaTipoDia.setDivisaoNoturnas(compensadasNoturnas); bancodeHoras.setSaldoExtrasNoturnas(Duration.ZERO); } } } /** * Verifica se existe o controle de saldos bh mensal do banco de horas do * funcionário */ private void inicializaSaldosBHMensal() { if (this.sequenciaPercentuaisList.size() > 0 && !this.calculo.isPeriodoSaldoPrimeiroDiaBancodeHoras() && !this.tipoLimiteDiario) { //BH Mensal if (this.saldosBHMensal.getBancoHoras() == null || (this.saldosBHMensal.getBancoHoras() != null && !this.saldosBHMensal.getBancoHoras().getIdBancoHoras().equals(this.bancoHoras.getIdBancoHoras()))) { //Não possui, então cria o controle de saldos do bh mensal this.saldosBHMensal.setBancoHoras(bancoHoras); } sequenciaPercentuaisSaldoMensalList = this.saldosBHMensal.getPercentuaisTipoDiaBancoDeHoras(this.calculo.getRegrasService().isFeriado(), this.calculo.getRegrasService().isRealizaCompensacao()); } } private void setEnquadrarLimites() { this.bancodeHorasAcrescimos.setLimiteDia(Utils.getHorasAcima24horas(this.calculo.getFuncionarioService().getFuncionarioBancodeHorasService().getLimiteDiaBancoDeHoras( this.calculo.getRegrasService().getIdTipoDia()).toInstant())); if (getOrdenacao().equals(CONSTANTES.PRIMEIRO_DIURNAS)) { this.bancodeHoras.setSaldoExtrasDiurnas(getEnquadraLimiteDia(this.bancodeHoras.getSaldoExtrasDiurnas())); this.bancodeHoras.setSaldoExtrasNoturnas(getEnquadraLimiteDia(this.bancodeHoras.getSaldoExtrasNoturnas())); } else { this.bancodeHoras.setSaldoExtrasNoturnas(getEnquadraLimiteDia(this.bancodeHoras.getSaldoExtrasNoturnas())); this.bancodeHoras.setSaldoExtrasDiurnas(getEnquadraLimiteDia(this.bancodeHoras.getSaldoExtrasDiurnas())); } } private Duration getEnquadraLimiteDia(Duration saldoCredito) { if (saldoCredito.toMillis() > 0 && this.bancodeHorasAcrescimos.getLimiteDia().toMillis() > 0) { if (saldoCredito.toMillis() > this.bancodeHorasAcrescimos.getLimiteDia().toMillis()) { saldoCredito = this.bancodeHorasAcrescimos.getLimiteDia(); this.bancodeHorasAcrescimos.setLimiteDia(Duration.ZERO); } else { this.bancodeHorasAcrescimos.setLimiteDia(this.bancodeHorasAcrescimos.getLimiteDia().minus(saldoCredito)); } } else { saldoCredito = Duration.ZERO; } return saldoCredito; } /** * Ajuste do percentual noturno de acordo com a configuração do banco de * horas * * @param saldoExtras */ private void getAjustePercentualNoturno(SaldoExtras saldoExtras) { if (this.calculo.getRegrasService().isAdicionalNoturno() && this.bancoHoras.getNaoPagaAdicionalNoturnoBH() && !saldoExtras.getNoturnas().isZero()) { this.bancodeHoras.setSaldoExtrasNoturnas(Utils.getRetirarPercentual(saldoExtras.getNoturnas(), this.calculo.getFuncionarioService().getFuncionarioJornadaService().getJornada().getPercentualAdicionalNoturno())); } else { bancodeHoras.setSaldoExtrasNoturnas(saldoExtras.getNoturnas()); } } /** * Se as horas diurnas previstas da jornada for maior que as noturnas ou * tudo zerado Então primeiro Diurnas, Senão primeiro Noturnas * * @return */ private String getOrdenacao() { Duration diurnas = this.calculo.getSaldosService().getTotalHorasPrevistas().getDiurnas(); Duration noturnas = this.calculo.getSaldosService().getTotalHorasPrevistas().getNoturnas(); if (diurnas.toMillis() > noturnas.toMillis() || (diurnas == Duration.ZERO && noturnas == Duration.ZERO)) { return CONSTANTES.PRIMEIRO_DIURNAS; } else { return CONSTANTES.PRIMEIRO_NOTURNAS; } } private void setAcrescimos(BancodeHorasApi bancodeHoras) { getTabelaDiurnas(); getTabelaNoturnas(); bancodeHoras.setAcrescimosTipoDiaList(this.bancodeHorasAcrescimos.getTabelaTipoDiaList()); getTabelaSomenteNoturnas(); bancodeHoras.setAcrescimosSomenteNoturnasList(this.bancodeHorasAcrescimos.getTabelaNoturnasList()); bancodeHoras.setTabelaTiposdeDia(this.bancodeHorasAcrescimos.getTabelaTipoDiaList()); //bancodeHoras.setCredito(Utils.getArredondamento(bancodeHoras.getTotalAcrescimosDiurnas().plus(bancodeHoras.getTotalAcrescimosNoturnas()))); bancodeHoras.setCredito(Utils.getSomenteHorasMinutos(bancodeHoras.getTotalAcrescimosDiurnas()).plus(Utils.getSomenteHorasMinutos(bancodeHoras.getTotalAcrescimosNoturnas()))); if (!bancodeHoras.getSaldoExtrasDiurnas().plus(bancodeHoras.getSaldoExtrasNoturnas()).isZero()) { setCriarUltimoPercentual(); } } public void setTabelaCreditoSaldoUnico() { setTotaisCreditoSaldoUnico(); List<TabelaCreditoSaldoUnico> tabelaCreditoSaldoUnicoList = new ArrayList<>(); this.calculo.getTipoDiaList() .stream() .forEach(new criarSaldosTipoDia(tabelaCreditoSaldoUnicoList)); if (this.bancodeHoras != null) { this.bancodeHoras.setTabelaCreditoSaldoUnicoList(tabelaCreditoSaldoUnicoList); } } private class criarSaldosTipoDia implements Consumer<TipoDia> { private final List<TabelaCreditoSaldoUnico> tabelaCreditoSaldoUnicoList; public criarSaldosTipoDia(List<TabelaCreditoSaldoUnico> tabelaCreditoSaldoUnicoList) { this.tabelaCreditoSaldoUnicoList = tabelaCreditoSaldoUnicoList; } @Override public void accept(TipoDia tipoDia) { TabelaCreditoSaldoUnico creditoSaldoUnico = new TabelaCreditoSaldoUnico(); creditoSaldoUnico.setTipoDia(tipoDia); creditoSaldoUnico.setSaldo(Duration.ZERO); if (calculo.getRegrasService().getIdTipoDia() == tipoDia.getIdTipodia()) { creditoSaldoUnico.setSaldo(somaDiurnasTabelaAcrescimosBH); } if (tipoDia.getDescricao().equals(CONSTANTES.TIPODIA_COMPENSADO)) { creditoSaldoUnico.setSaldo(somaCompensadasTabelaAcrescimosBH); } if (tipoDia.getDescricao().equals(CONSTANTES.TIPODIA_HORAS_NOTURNAS)) { creditoSaldoUnico.setSaldo(somaNoturnasTabelaAcrescimosBH); } tabelaCreditoSaldoUnicoList.add(creditoSaldoUnico); } } private void setTotaisCreditoSaldoUnico() { if (this.bancodeHoras != null && this.bancodeHoras.getTabelaTiposdeDia() != null) { this.somaDiurnasTabelaAcrescimosBH = Duration.ZERO; this.bancodeHoras.getTabelaTiposdeDia() .stream() .filter(f -> !f.getTipoDia().getDescricao().equals(CONSTANTES.TIPODIA_COMPENSADO)) .forEach((TabelaSequenciaPercentuais tabela) -> { this.somaDiurnasTabelaAcrescimosBH = this.somaDiurnasTabelaAcrescimosBH.plus(tabela.getResultadoDiurnas()); }); this.somaNoturnasTabelaAcrescimosBH = Duration.ZERO; this.bancodeHoras.getTabelaTiposdeDia() .stream() .filter(f -> !f.getTipoDia().getDescricao().equals(CONSTANTES.TIPODIA_COMPENSADO)) .forEach((TabelaSequenciaPercentuais tabela) -> { this.somaNoturnasTabelaAcrescimosBH = this.somaNoturnasTabelaAcrescimosBH.plus(tabela.getResultadoNoturnas()); }); this.somaCompensadasTabelaAcrescimosBH = Duration.ZERO; this.bancodeHoras.getTabelaTiposdeDia() .stream() .filter(f -> f.getTipoDia().getDescricao().equals(CONSTANTES.TIPODIA_COMPENSADO)) .forEach((TabelaSequenciaPercentuais tabela) -> { this.somaCompensadasTabelaAcrescimosBH = this.somaCompensadasTabelaAcrescimosBH.plus(tabela.getResultadoDiurnas().plus(tabela.getResultadoNoturnas())); }); } } private void getTabelaDiurnas() { LOGGER.debug("Processando tabela de acréscimos diurnas BH... dia: {} - funcionário: {} ", this.calculo.getDiaProcessado(), this.calculo.getNomeFuncionario()); this.bancodeHorasAcrescimos.setTabelaTipoDiaList(new ArrayList<>()); //Se BH diário if (this.tipoLimiteDiario) { if (this.sequenciaPercentuaisList.size() > 0) { this.sequenciaPercentuaisList .stream() .sorted(new Utils.ordenaSequencia()) .forEach(new acrescimosDiurnasLimiteDiario()); } else { AlocaLimite1SemAcrescimos(); } } else //É BH mensal //Quando BH Mensal ignora o tipo de dia compensado { if (this.sequenciaPercentuaisSaldoMensalList != null && this.sequenciaPercentuaisSaldoMensalList.size() > 0) { this.sequenciaPercentuaisSaldoMensalList .stream() .sorted(new Utils.ordenaSequencia()) .forEach(new acrescimosDiurnasLimiteMensal()); } else { AlocaLimite1SemAcrescimos(); } } } /** * Como não tem limite cadastrado, aloca todas as horas no 1 limite sem * acréscimos */ private void AlocaLimite1SemAcrescimos() { setTabelaPercentuaisTipoDia(null); this.bancodeHorasAcrescimos.getTabela().setResultadoDiurnas(this.bancodeHoras.getSaldoExtrasDiurnas()); this.bancodeHorasAcrescimos.getTabela().setResultadoNoturnas(this.bancodeHoras.getSaldoExtrasNoturnas()); this.bancodeHoras.setTotalAcrescimosDiurnas(this.bancodeHoras.getSaldoExtrasDiurnas()); this.bancodeHoras.setTotalAcrescimosNoturnas(this.bancodeHoras.getSaldoExtrasNoturnas()); this.bancodeHoras.setSaldoExtrasDiurnas(Duration.ZERO); this.bancodeHoras.setSaldoExtrasNoturnas(Duration.ZERO); this.bancodeHorasAcrescimos.getTabelaTipoDiaList().add(this.bancodeHorasAcrescimos.getTabela()); } private class acrescimosDiurnasLimiteDiario implements Consumer<SequenciaPercentuais> { public acrescimosDiurnasLimiteDiario() { } @Override public void accept(SequenciaPercentuais sequenciaPercentuais) { setTabelaPercentuaisTipoDia(sequenciaPercentuais); //CAMPO ACIMA 24 HORAS //Horas Diurnas por limites para o cálculo de percentuais Date horas = Utils.getDataAjustaDiferenca3horas(sequenciaPercentuais.getHoras()); if (bancodeHoras.getSaldoExtrasDiurnas().toMillis() > 0) { if (bancodeHoras.getSaldoExtrasDiurnas().toMillis() > Utils.getHorasAcima24horas(horas.toInstant()).toMillis()) { bancodeHorasAcrescimos.getTabela().setDivisaoDiurnas(Utils.getHorasAcima24horas(horas.toInstant())); bancodeHoras.setSaldoExtrasDiurnas(bancodeHoras.getSaldoExtrasDiurnas().minus(Utils.getHorasAcima24horas(horas.toInstant()))); } else { bancodeHorasAcrescimos.getTabela().setDivisaoDiurnas(bancodeHoras.getSaldoExtrasDiurnas()); bancodeHoras.setSaldoExtrasDiurnas(Duration.ZERO); } //Somente tipo diário multiplicar pelos acréscimos bancodeHorasAcrescimos.getTabela().setResultadoDiurnas(Utils.getAcrescimoPercentualTabelasPercentuais(bancodeHorasAcrescimos.getTabela().getDivisaoDiurnas(), sequenciaPercentuais.getAcrescimo())); bancodeHoras.setTotalAcrescimosDiurnas(bancodeHoras.getTotalAcrescimosDiurnas().plus(bancodeHorasAcrescimos.getTabela().getResultadoDiurnas())); bancodeHorasAcrescimos.getTabelaTipoDiaList().add(bancodeHorasAcrescimos.getTabela()); } } } private class acrescimosDiurnasLimiteMensal implements Consumer<SequenciaPercentuais> { public acrescimosDiurnasLimiteMensal() { } @Override public void accept(SequenciaPercentuais sequenciaPercentuais) { setTabelaPercentuaisTipoDia(sequenciaPercentuais); //CAMPO ACIMA 24 HORAS //Horas Diurnas por limites para o cálculo de percentuais Date horas = Utils.getDataAjustaDiferenca3horas(sequenciaPercentuais.getHoras()); if (bancodeHoras.getSaldoExtrasDiurnas().toMillis() > 0 && Utils.getHorasAcima24horas(horas.toInstant()).toMillis() > 0) { if (bancodeHoras.getSaldoExtrasDiurnas().toMillis() > Utils.getHorasAcima24horas(horas.toInstant()).toMillis()) { bancodeHorasAcrescimos.getTabela().setDivisaoDiurnas(Utils.getHorasAcima24horas(horas.toInstant())); bancodeHoras.setSaldoExtrasDiurnas(bancodeHoras.getSaldoExtrasDiurnas().minus(Utils.getHorasAcima24horas(horas.toInstant()))); } else { bancodeHorasAcrescimos.getTabela().setDivisaoDiurnas(bancodeHoras.getSaldoExtrasDiurnas()); bancodeHoras.setSaldoExtrasDiurnas(Duration.ZERO); } setHorasExtrasAcumulo(sequenciaPercentuais, bancodeHoras.getSaldoExtrasDiurnas(), bancodeHorasAcrescimos.getTabela().getDivisaoDiurnas()); //Tipo mensal não realiza os acréscimos, somente separa as horas //deve somente separar igual é feito nas extras bancodeHorasAcrescimos.getTabela().setResultadoDiurnas(bancodeHorasAcrescimos.getTabela().getDivisaoDiurnas()); bancodeHoras.setTotalAcrescimosDiurnas(bancodeHoras.getTotalAcrescimosDiurnas().plus(bancodeHorasAcrescimos.getTabela().getResultadoDiurnas())); bancodeHorasAcrescimos.getTabelaTipoDiaList().add(bancodeHorasAcrescimos.getTabela()); } else { bancodeHorasAcrescimos.getTabelaTipoDiaList().add(bancodeHorasAcrescimos.getTabela()); } } } /** * Se possui dia de fechamento, verificar se é o dia ou se passou, caso sim, * começa novamente do primeiro limite, verifica se tem saldo no limite * cadastrado, se não tem, então não faz nada, não gera pro próximo. Senão * continua normalmente... * * @param sequenciaPercentuais * @param saldoExtras * @param divisoes */ private void setHorasExtrasAcumulo(SequenciaPercentuais sequenciaPercentuais, Duration saldoExtras, Duration divisoes) { //Diminuir do saldo disponível limite mensal as horas //que foram alocadas acima sequenciaPercentuais.setHoras(Utils.FormatoDataHora(Utils.getHorasAcima24horas(Utils.getDataAjustaDiferenca3horas(sequenciaPercentuais.getHoras()).toInstant()).minus(divisoes))); if (this.saldosBHMensal.getBancoHoras().getHabilitaDiaFechamento()) { Integer diaFechamento = this.saldosBHMensal.getBancoHoras().getDiaFechamentoExtra(); if (this.calculo.getDiaProcessado().getDate() > diaFechamento) { //saldo extras = saldo extras - limite original //pois não poderá alocar pro outro período o que era pra ser nesse. Duration limiteOriginal = getHorasLimiteOriginal(sequenciaPercentuais.getSequenciaPercentuaisPK().getIdSequencia()); if (saldoExtras.toMillis() > limiteOriginal.toMillis()) { saldoExtras.minus(limiteOriginal); } } } } /** * Consultar no banco de horas do funcionário o limite original, pois em * SaldosBHMensal está o saldo atualizado que ainda pode ser utilizado * * @param idSequencia * @return */ private Duration getHorasLimiteOriginal(Integer idSequencia) { Date horas = this.bancoHoras.getPercentuaisAcrescimo() .getSequenciaPercentuaisList() .stream() .filter(f -> (f.getSequenciaPercentuaisPK().getIdSequencia() == idSequencia)) .map(f -> f.getHoras()).findFirst().orElse(null); return Utils.getHorasAcima24horas(Utils.getDataAjustaDiferenca3horas(horas).toInstant()); } private void getTabelaNoturnas() { LOGGER.debug("Processando tabela de acréscimos noturnas BH... dia: {} - funcionário: {} ", this.calculo.getDiaProcessado(), this.calculo.getNomeFuncionario()); //Se BH diário if (this.tipoLimiteDiario) { this.bancodeHorasAcrescimos.getTabelaTipoDiaList() .stream() .sorted(new Utils.ordenaSequencia()) .forEach(new acrescimosNoturnasLimiteDiario()); } else //É BH mensal //Quando BH Mensal ignora o tipo de dia compensado if (this.sequenciaPercentuaisSaldoMensalList != null && this.sequenciaPercentuaisSaldoMensalList.size() > 0) { this.sequenciaPercentuaisSaldoMensalList .stream() .sorted(new Utils.ordenaSequencia()) .forEach(new acrescimosNoturnasLimiteMensal()); } } private class acrescimosNoturnasLimiteMensal implements Consumer<SequenciaPercentuais> { public acrescimosNoturnasLimiteMensal() { } @Override public void accept(SequenciaPercentuais sequenciaPercentuais) { TabelaSequenciaPercentuais atualizaTabela = bancodeHorasAcrescimos.getTabelaTipoDiaList().get(sequenciaPercentuais.getSequenciaPercentuaisPK().getIdSequencia()); //CAMPO ACIMA 24 HORAS //Horas Diurnas por limites para o cálculo de percentuais Date horas = Utils.getDataAjustaDiferenca3horas(sequenciaPercentuais.getHoras()); if (bancodeHoras.getSaldoExtrasNoturnas().toMillis() > 0 && Utils.getHorasAcima24horas(horas.toInstant()).toMillis() > 0) { if (bancodeHoras.getSaldoExtrasNoturnas().toMillis() > Utils.getHorasAcima24horas(horas.toInstant()).toMillis()) { atualizaTabela.setDivisaoNoturnas(atualizaTabela.getDivisaoNoturnas().plus(Utils.getHorasAcima24horas(horas.toInstant()))); bancodeHoras.setSaldoExtrasNoturnas(bancodeHoras.getSaldoExtrasNoturnas().minus(Utils.getHorasAcima24horas(horas.toInstant()))); } else { atualizaTabela.setDivisaoNoturnas(atualizaTabela.getDivisaoNoturnas().plus(bancodeHoras.getSaldoExtrasNoturnas())); bancodeHoras.setSaldoExtrasNoturnas(Duration.ZERO); } setHorasExtrasAcumulo(sequenciaPercentuais, bancodeHoras.getSaldoExtrasNoturnas(), atualizaTabela.getDivisaoNoturnas()); atualizaTabela.setResultadoNoturnas(atualizaTabela.getDivisaoNoturnas()); bancodeHoras.setTotalAcrescimosNoturnas(bancodeHoras.getTotalAcrescimosNoturnas().plus(atualizaTabela.getResultadoNoturnas())); } } } private class acrescimosNoturnasLimiteDiario implements Consumer<TabelaSequenciaPercentuais> { public acrescimosNoturnasLimiteDiario() { } @Override public void accept(TabelaSequenciaPercentuais tabela) { if (sequenciaPercentuaisList.size() > 0) { //CAMPO ACIMA 24 HORAS //Horas Noturnas por limites para o cálculo de percentuais Date horas = Utils.getDataAjustaDiferenca3horas(tabela.getHoras()); if (bancodeHoras.getSaldoExtrasNoturnas().toMillis() > 0 && tabela.getDivisaoDiurnas().toMillis() < Utils.getHorasAcima24horas(horas.toInstant()).toMillis()) { if (bancodeHoras.getSaldoExtrasNoturnas().toMillis() > Utils.getHorasAcima24horas(horas.toInstant()).minus(tabela.getDivisaoNoturnas()).toMillis()) { tabela.setDivisaoNoturnas(Utils.getHorasAcima24horas(horas.toInstant()).minus(tabela.getDivisaoNoturnas())); bancodeHoras.setSaldoExtrasNoturnas(bancodeHoras.getSaldoExtrasNoturnas().minus(Utils.getHorasAcima24horas(horas.toInstant()).minus(tabela.getDivisaoNoturnas()))); } else { tabela.setDivisaoNoturnas(bancodeHoras.getSaldoExtrasNoturnas()); bancodeHoras.setSaldoExtrasNoturnas(Duration.ZERO); } //Somente tipo diário realizar os acréscimos tabela.setResultadoNoturnas(Utils.getAcrescimoPercentualTabelasPercentuais(tabela.getDivisaoNoturnas(), tabela.getAcrescimo())); bancodeHoras.setTotalAcrescimosNoturnas(Utils.getSomenteHorasMinutos(bancodeHoras.getTotalAcrescimosNoturnas()).plus(Utils.getSomenteHorasMinutos(tabela.getResultadoNoturnas()))); } } else { //Como não tem limite cadastrado, aloca todas as horas no 1 limite sem acréscimos tabela.setDivisaoNoturnas(bancodeHoras.getSaldoExtrasNoturnas()); bancodeHoras.setSaldoExtrasNoturnas(Duration.ZERO); } } } private void getTabelaSomenteNoturnas() { LOGGER.debug("Processando tabela de acréscimos somente noturnas BH... dia: {} - funcionário: {} ", this.calculo.getDiaProcessado(), this.calculo.getNomeFuncionario()); this.bancodeHorasAcrescimos.setTabelaNoturnasList(new ArrayList<>()); //Horas noturnas somente para BH Diário if (this.tipoLimiteDiario) { if (this.sequenciaPercentuaisNoturnosList.size() > 0) { this.bancodeHoras.setSaldoExtrasNoturnas(bancodeHoras.getTotalAcrescimosNoturnas()); this.bancodeHoras.setTotalAcrescimosNoturnas(Duration.ZERO); this.sequenciaPercentuaisNoturnosList .stream() .sorted(new Utils.ordenaSequencia()) .forEach(new acrescimosSomenteNoturnasLimiteDiario()); } else { //Como não tem limite cadastrado, aloca todas as horas no 1 limite sem acréscimos setTabelaPercentuaisTipoDia(null); this.bancodeHorasAcrescimos.getTabela().setDivisaoNoturnas(this.bancodeHoras.getSaldoExtrasNoturnas()); this.bancodeHoras.setSaldoExtrasNoturnas(Duration.ZERO); this.bancodeHorasAcrescimos.getTabelaNoturnasList().add(this.bancodeHorasAcrescimos.getTabela()); } } } private class acrescimosSomenteNoturnasLimiteDiario implements Consumer<SequenciaPercentuais> { public acrescimosSomenteNoturnasLimiteDiario() { } @Override public void accept(SequenciaPercentuais sequenciaPercentuais) { setTabelaPercentuaisTipoDia(sequenciaPercentuais); //Campo acima 24h //Horas Noturnas por limites para o cálculo de percentuais Date horas = Utils.getDataAjustaDiferenca3horas(sequenciaPercentuais.getHoras()); if (bancodeHoras.getSaldoExtrasNoturnas().toMillis() > 0) { if (bancodeHoras.getSaldoExtrasNoturnas().toMillis() > Utils.getHorasAcima24horas(horas.toInstant()).toMillis()) { bancodeHorasAcrescimos.getTabela().setDivisaoNoturnas(Utils.getHorasAcima24horas(horas.toInstant())); bancodeHoras.setSaldoExtrasNoturnas(bancodeHoras.getSaldoExtrasNoturnas().minus(Utils.getHorasAcima24horas(horas.toInstant()))); } else { bancodeHorasAcrescimos.getTabela().setDivisaoNoturnas(bancodeHoras.getSaldoExtrasNoturnas()); bancodeHoras.setSaldoExtrasNoturnas(Duration.ZERO); } //Somente tipo diário realizar os acréscimos Duration somenteNoturnasComAcrescimos = Utils.getAcrescimoPercentualTabelasPercentuais(bancodeHorasAcrescimos.getTabela().getDivisaoNoturnas(), sequenciaPercentuais.getAcrescimo()); Duration somenteAcrescimosCalculados = somenteNoturnasComAcrescimos.minus(bancodeHorasAcrescimos.getTabela().getDivisaoNoturnas()); bancodeHorasAcrescimos.getTabela().setResultadoNoturnas(somenteNoturnasComAcrescimos); bancodeHorasAcrescimos.getTabelaNoturnasList().add(bancodeHorasAcrescimos.getTabela()); //Atualizar a tabela que unifica tudo Integer idSequencia = sequenciaPercentuais.getSequenciaPercentuaisPK().getIdSequencia(); if (idSequencia <= bancodeHorasAcrescimos.getTabelaTipoDiaList().size() - 1) { Duration totalNoturnas = bancodeHorasAcrescimos.getTabelaTipoDiaList().get(idSequencia) .getResultadoNoturnas().plus(somenteAcrescimosCalculados); bancodeHorasAcrescimos.getTabelaTipoDiaList().get(idSequencia) .setResultadoNoturnas(totalNoturnas); bancodeHoras.setTotalAcrescimosNoturnas( bancodeHoras.getTotalAcrescimosNoturnas().plus(totalNoturnas)); } else { bancodeHorasAcrescimos.getTabelaTipoDiaList().add( new TabelaSequenciaPercentuais( Duration.ZERO, Duration.ZERO, bancodeHorasAcrescimos.getTabela().getDivisaoNoturnas(), somenteNoturnasComAcrescimos, null, bancodeHorasAcrescimos.getTabela().getAcrescimo(), idSequencia, calculo.getRegrasService().getTipoDia())); bancodeHoras.setTotalAcrescimosNoturnas( Utils.getSomenteHorasMinutos(bancodeHoras.getTotalAcrescimosNoturnas()) .plus(Utils.getSomenteHorasMinutos(somenteNoturnasComAcrescimos))); } } } } private void setTabelaPercentuaisTipoDia(SequenciaPercentuais sequenciaPercentuais) { TabelaSequenciaPercentuais tabela = new TabelaSequenciaPercentuais(); if (sequenciaPercentuais != null) { tabela.setTipoDia(sequenciaPercentuais.getTipoDia()); tabela.setIdSequencia(sequenciaPercentuais.getSequenciaPercentuaisPK().getIdSequencia()); tabela.setHoras(Utils.getDataAjustaDiferenca3horas(sequenciaPercentuais.getHoras())); tabela.setAcrescimo(sequenciaPercentuais.getAcrescimo()); } else { tabela.setTipoDia(this.calculo.getRegrasService().getTipoDia()); tabela.setIdSequencia(1); tabela.setAcrescimo(0d); } this.bancodeHorasAcrescimos.setTabela(tabela); } private void setTabelaPercentuaisTipoDiaCompensado(SequenciaPercentuais sequenciaPercentuais) { TabelaSequenciaPercentuais tabela = new TabelaSequenciaPercentuais(); tabela.setTipoDia(new TipoDia(2, CONSTANTES.TIPODIA_COMPENSADO)); if (sequenciaPercentuais != null) { tabela.setIdSequencia(sequenciaPercentuais.getSequenciaPercentuaisPK().getIdSequencia()); tabela.setHoras(Utils.getDataAjustaDiferenca3horas(sequenciaPercentuais.getHoras())); tabela.setAcrescimo(sequenciaPercentuais.getAcrescimo()); } else { tabela.setIdSequencia(1); tabela.setAcrescimo(0d); } this.bancodeHorasAcrescimos.setTabela(tabela); } /** * Se efetuou todas as divisões e ainda ficou saldo pois tem mais horas que * os limites configurados, então criar um novo com 0%, como não tem limite * cadastrado, aloca todas as horas no 1 limite sem acréscimos */ private void setCriarUltimoPercentual() { setTabelaPercentuaisTipoDia(null); this.bancodeHorasAcrescimos.getTabela().setDivisaoDiurnas(this.bancodeHoras.getSaldoExtrasDiurnas()); this.bancodeHorasAcrescimos.getTabela().setDivisaoNoturnas(this.bancodeHoras.getSaldoExtrasNoturnas()); this.bancodeHoras.setSaldoExtrasDiurnas(Duration.ZERO); this.bancodeHoras.setSaldoExtrasNoturnas(Duration.ZERO); this.bancodeHorasAcrescimos.getTabelaTipoDiaList().add(this.bancodeHorasAcrescimos.getTabela()); } }
julianoezequiel/simple-serve
ex/src/main/java/com/topdata/toppontoweb/services/gerafrequencia/services/bancodehoras/BancodeHorasAcrescimosService.java
Java
gpl-3.0
42,634
<?php /** * This file is loaded automatically by the app/webroot/index.php file after core.php * * This file should load/create any application wide configuration settings, such as * Caching, Logging, loading additional configuration files. * * You should also use this file to include any files that provide global functions/constants * that your application uses. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package app.Config * @since CakePHP(tm) v 0.10.8.2117 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ // Setup a 'default' cache configuration for use in the application. Cache::config('default', array('engine' => 'File')); /** * The settings below can be used to set additional paths to models, views and controllers. * * App::build(array( * 'Model' => array('/path/to/models/', '/next/path/to/models/'), * 'Model/Behavior' => array('/path/to/behaviors/', '/next/path/to/behaviors/'), * 'Model/Datasource' => array('/path/to/datasources/', '/next/path/to/datasources/'), * 'Model/Datasource/Database' => array('/path/to/databases/', '/next/path/to/database/'), * 'Model/Datasource/Session' => array('/path/to/sessions/', '/next/path/to/sessions/'), * 'Controller' => array('/path/to/controllers/', '/next/path/to/controllers/'), * 'Controller/Component' => array('/path/to/components/', '/next/path/to/components/'), * 'Controller/Component/Auth' => array('/path/to/auths/', '/next/path/to/auths/'), * 'Controller/Component/Acl' => array('/path/to/acls/', '/next/path/to/acls/'), * 'View' => array('/path/to/views/', '/next/path/to/views/'), * 'View/Helper' => array('/path/to/helpers/', '/next/path/to/helpers/'), * 'Console' => array('/path/to/consoles/', '/next/path/to/consoles/'), * 'Console/Command' => array('/path/to/commands/', '/next/path/to/commands/'), * 'Console/Command/Task' => array('/path/to/tasks/', '/next/path/to/tasks/'), * 'Lib' => array('/path/to/libs/', '/next/path/to/libs/'), * 'Locale' => array('/path/to/locales/', '/next/path/to/locales/'), * 'Vendor' => array('/path/to/vendors/', '/next/path/to/vendors/'), * 'Plugin' => array('/path/to/plugins/', '/next/path/to/plugins/'), * )); * */ /** * Custom Inflector rules, can be set to correctly pluralize or singularize table, model, controller names or whatever other * string is passed to the inflection functions * * Inflector::rules('singular', array('rules' => array(), 'irregular' => array(), 'uninflected' => array())); * Inflector::rules('plural', array('rules' => array(), 'irregular' => array(), 'uninflected' => array())); * */ /** * Plugins need to be loaded manually, you can either load them one by one or all of them in a single call * Uncomment one of the lines below, as you need. make sure you read the documentation on CakePlugin to use more * advanced ways of loading plugins * * CakePlugin::loadAll(); // Loads all plugins at once * CakePlugin::load('DebugKit'); //Loads a single plugin named DebugKit * */ /** * You can attach event listeners to the request lifecycle as Dispatcher Filter . By Default CakePHP bundles two filters: * * - AssetDispatcher filter will serve your asset files (css, images, js, etc) from your themes and plugins * - CacheDispatcher filter will read the Cache.check configure variable and try to serve cached content generated from controllers * * Feel free to remove or add filters as you see fit for your application. A few examples: * * Configure::write('Dispatcher.filters', array( * 'MyCacheFilter', // will use MyCacheFilter class from the Routing/Filter package in your app. * 'MyPlugin.MyFilter', // will use MyFilter class from the Routing/Filter package in MyPlugin plugin. * array('callable' => $aFunction, 'on' => 'before', 'priority' => 9), // A valid PHP callback type to be called on beforeDispatch * array('callable' => $anotherMethod, 'on' => 'after'), // A valid PHP callback type to be called on afterDispatch * * )); */ Configure::write('Dispatcher.filters', array( 'AssetDispatcher', 'CacheDispatcher' )); /** * Configures default file logging options */ App::uses('CakeLog', 'Log'); CakeLog::config('debug', array( 'engine' => 'File', 'types' => array('notice', 'info', 'debug'), 'file' => 'debug', )); CakeLog::config('error', array( 'engine' => 'File', 'types' => array('warning', 'error', 'critical', 'alert', 'emergency'), 'file' => 'error', )); $options = array( 'uploadPath' => DS.'files'.DS.date('Y').DS.date('m').DS ); Configure::write('uploadOptions', $options);
eramat/LibreApprenti
app/Config/bootstrap.php
PHP
gpl-3.0
5,321
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <?php $room = $_SERVER['QUERY_STRING']; $date = date("Ymd"); $con = mysqli_connect("localhost","lee","1234","smr","3306"); mysqli_set_charset($con,"utf8"); $result = mysqli_query($con,"select * from v1 where Date = '$date' and Room_ID = '$room' order by Time"); $re2 = mysqli_query($con,"select * from room where Room_ID='$room'"); $row2 = mysqli_fetch_array($re2); $re3 = mysqli_query($con,"select * from place where place_ID='$row2[place_ID]'"); $row3 = mysqli_fetch_array($re3); $number=1; ?> <table width = "790" class="displaytable" cellpadding="20"> <tr align="center"><td bgcolor="#1294AB"><font color="white" size="5px"><b> 금일 <?php echo $row3[Building]." ".$row2[RoomNum]." "; ?> 예약현황</font></td></tr> <table width = "790"> <tr align="center" height="30px"> <td bgcolor="#FF3636"><font color="white"><b>순번</font></td> <td bgcolor="#FF3636"><font color="white"><b>신청자 이름</font></td> <td bgcolor="#FF3636"><font color="white"><b>사용시간</font></td> <td bgcolor="#FF3636"><font color="white"><b>연락처</font></td> <td bgcolor="#FF3636" width="220px"><font color="white"><b>사용목적</font></td> </tr> <?php while($row = mysqli_fetch_array($result)) { $p1 = floor($row[Phone]/100000000); $p2 = floor(($row[Phone]-($p1*100000000))/10000); if($p2<1000) $p2='0'.$p2; if($p2<100) $p2='0'.$p2; if($p2<10) $p2='0'.$p2; $p3 = $row[Phone]-($p1*100000000+$p2*10000); if($p3<1000) $p3='0'.$p3; if($p3<100) $p3='0'.$p3; if($p3<10) $p3='0'.$p3; $_SESSION['id']=$row[ID]; $ttime=$row[Time]+1; echo (" <tr align=\"center\" height=\"60px\"> <td bgcolor=\"#FFCBCB\"><b> $number</td> <td bgcolor=\"#FFCBCB\"><b> $row[name]</td> <td bgcolor=\"#FFCBCB\"><b> $row[Time]:00 ~ $ttime:00</td> <td bgcolor=\"#FFCBCB\"><b> 0$p1-$p2-$p3</td> <td bgcolor=\"#FFCBCB\"><b> $row[Usage]</td> </tr> "); $number++; } ?> </table> </body> </html>
teagunnNa/S.M.V-Project
display/roomDisplay.php
PHP
gpl-3.0
2,131
import socket as _socket import os import types import _lightbluecommon from _obexcommon import OBEXError # public attributes __all__ = ("sendfile", "recvfile") def sendfile(address, channel, source): if not isinstance(source, (types.StringTypes, types.FileType)): raise TypeError("source must be string or built-in file object") if isinstance(source, types.StringTypes): try: _socket.bt_obex_send_file(address, channel, unicode(source)) except Exception, e: raise OBEXError(str(e)) else: # given file object if hasattr(source, "name"): localpath = _tempfilename(source.name) else: localpath = _tempfilename() try: # write the source file object's data into a file, then send it f = file(localpath, "wb") f.write(source.read()) f.close() try: _socket.bt_obex_send_file(address, channel, unicode(localpath)) except Exception, e: raise OBEXError(str(e)) finally: # remove temporary file if os.path.isfile(localpath): try: os.remove(localpath) except Exception, e: print "[lightblue.obex] unable to remove temporary file %s: %s" %\ (localpath, str(e)) def recvfile(sock, dest): if not isinstance(dest, (types.StringTypes, types.FileType)): raise TypeError("dest must be string or built-in file object") if isinstance(dest, types.StringTypes): _recvfile(sock, dest) else: # given file object localpath = _tempfilename() try: # receive a file and then read it into the file object _recvfile(sock, localpath) recvdfile = file(localpath, "rb") dest.write(recvdfile.read()) recvdfile.close() finally: # remove temporary file if os.path.isfile(localpath): try: os.remove(localpath) except Exception, e: print "[lightblue.obex] unable to remove temporary file %s: %s" %\ (localpath, str(e)) # receives file and saves to local path def _recvfile(sock, localpath): # PyS60's bt_obex_receive() won't receive the file if given a file path # that already exists (it tells the client there's a conflict error). So # we need to handle this somehow, and preferably backup the original file # so that we can put it back if the recv fails. if os.path.isfile(localpath): # if given an existing path, rename existing file temppath = _tempfilename(localpath) os.rename(localpath, temppath) else: temppath = None try: # receive a file (get internal _sock cos sock is our own SocketWrapper # object) _socket.bt_obex_receive(sock._sock, unicode(localpath)) except _socket.error, e: try: if temppath is not None: # recv failed, put original file back os.rename(temppath, localpath) finally: # if the renaming of the original file fails, this will still # get raised raise OBEXError(str(e)) else: # recv successful, remove the original file if temppath is not None: os.remove(temppath) # Must point to C:\ because can't write in start-up dir (on Z:?) def _tempfilename(basename="C:\\lightblue_obex_received_file"): version = 1 while os.path.isfile(basename): version += 1 basename = basename[:-1] + str(version) return basename
hfeeki/python-lightblue
src/series60/_obex.py
Python
gpl-3.0
3,871
%[kind : lang] %[file : messages_%%(self.obName.lower())%%_lang.php] %[path : language/french] <?php /** * Message file for entity %%(self.obName)%% * * Please don't forget to load this file: * Solution A : Use "/application/config/autoload.php" * Add this line: * $autoload['language'] = array(..., 'messages_%%(self.obName.lower())%%', ...); * * Solution B : Load this message file anywhere you want. * */ $lang['%%(self.obName.lower())%%.message.askConfirm.deletion'] = "Désirez-vous supprimer ce %%(self.displayName)%% ?"; $lang['%%(self.obName.lower())%%.message.confirm.deleted'] = "%%(self.displayName)%% supprimé avec succès"; $lang['%%(self.obName.lower())%%.message.confirm.added'] = "%%(self.displayName)%% créé avec succès"; $lang['%%(self.obName.lower())%%.message.confirm.modified'] = "%%(self.displayName)%% mis à jour avec succès"; $lang['%%(self.obName.lower())%%.form.create.title'] = "Ajouter un %%(self.displayName.lower())%%"; $lang['%%(self.obName.lower())%%.form.edit.title'] = "Editer un %%(self.displayName.lower())%%"; $lang['%%(self.obName.lower())%%.form.list.title'] = "Liste des %%(self.displayName.lower())%%s"; $lang['%%(self.obName.lower())%%.menu.item'] = "%%(self.displayName)%%"; %%allAttributesCode = "" for field in self.fields: attributeCode = """$lang['%(objectObName)s.form.%(dbName)s.label'] = "%(obName)s"; $lang['%(objectObName)s.form.%(dbName)s.description'] = "%(desc)s"; """ % { 'dbName': field.dbName, 'obName': field.obName, 'objectObName':self.obName.lower(), 'desc' : field.description } allAttributesCode += attributeCode RETURN = allAttributesCode %% ?>
jchome/CI-Generator
themes/ubuntu/templates/messages_lang_fr.php
PHP
gpl-3.0
1,684
// Copyright (c) 2006-2011 Frank Laub // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. The name of the author may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. using OpenSSL.Core; using System; using System.Runtime.InteropServices; using System.Text; namespace OpenSSL.Crypto { #region MessageDigest /// <summary> /// Wraps the EVP_MD object /// </summary> public class MessageDigest : Base { /// <summary> /// Creates a EVP_MD struct /// </summary> /// <param name="ptr"></param> /// <param name="owner"></param> internal MessageDigest(IntPtr ptr, bool owner) : base(ptr, owner) { } /// <summary> /// Prints MessageDigest /// </summary> /// <param name="bio"></param> public override void Print(BIO bio) { bio.Write("MessageDigest"); } /// <summary> /// Not implemented, these objects should never be disposed. /// </summary> protected override void OnDispose() { throw new NotImplementedException(); } /// <summary> /// Calls EVP_get_digestbyname() /// </summary> /// <param name="name"></param> /// <returns></returns> public static MessageDigest CreateByName(string name) { var buf = Encoding.ASCII.GetBytes(name); var ptr = Native.EVP_get_digestbyname(buf); if (ptr == IntPtr.Zero) return null; return new MessageDigest(ptr, false); } /// <summary> /// Calls OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH) /// </summary> public static string[] AllNamesSorted { get { return new NameCollector(Native.OBJ_NAME_TYPE_MD_METH, true).Result.ToArray(); } } /// <summary> /// Calls OBJ_NAME_do_all(OBJ_NAME_TYPE_CIPHER_METH) /// </summary> public static string[] AllNames { get { return new NameCollector(Native.OBJ_NAME_TYPE_MD_METH, false).Result.ToArray(); } } #region MessageDigests /// <summary> /// EVP_md_null() /// </summary> public static MessageDigest Null = new MessageDigest(Native.EVP_md_null(), false); /// <summary> /// EVP_md4() /// </summary> public static MessageDigest MD4 = new MessageDigest(Native.EVP_md4(), false); /// <summary> /// EVP_md5() /// </summary> public static MessageDigest MD5 = new MessageDigest(Native.EVP_md5(), false); /// <summary> /// EVP_sha() /// </summary> public static MessageDigest SHA = new MessageDigest(Native.EVP_sha(), false); /// <summary> /// EVP_sha1() /// </summary> public static MessageDigest SHA1 = new MessageDigest(Native.EVP_sha1(), false); /// <summary> /// EVP_sha224() /// </summary> public static MessageDigest SHA224 = new MessageDigest(Native.EVP_sha224(), false); /// <summary> /// EVP_sha256() /// </summary> public static MessageDigest SHA256 = new MessageDigest(Native.EVP_sha256(), false); /// <summary> /// EVP_sha384() /// </summary> public static MessageDigest SHA384 = new MessageDigest(Native.EVP_sha384(), false); /// <summary> /// EVP_sha512() /// </summary> public static MessageDigest SHA512 = new MessageDigest(Native.EVP_sha512(), false); /// <summary> /// EVP_dss() /// </summary> public static MessageDigest DSS = new MessageDigest(Native.EVP_dss(), false); /// <summary> /// EVP_dss1() /// </summary> public static MessageDigest DSS1 = new MessageDigest(Native.EVP_dss1(), false); /// <summary> /// EVP_ripemd160() /// </summary> public static MessageDigest RipeMD160 = new MessageDigest(Native.EVP_ripemd160(), false); /// <summary> /// EVP_ecdsa() /// </summary> public static MessageDigest ECDSA = new MessageDigest(Native.EVP_ecdsa(), false); #endregion #region Properties /// <summary> /// Returns the block_size field /// </summary> public int BlockSize { get { return Native.EVP_MD_block_size(ptr); } } /// <summary> /// Returns the md_size field /// </summary> public int Size { get { return Native.EVP_MD_size(ptr); } } /// <summary> /// Returns the type field using OBJ_nid2ln() /// </summary> public string LongName { get { return Native.StaticString(Native.OBJ_nid2ln(Native.EVP_MD_type(ptr))); } } /// <summary> /// Returns the type field using OBJ_nid2sn() /// </summary> public string Name { get { return Native.StaticString(Native.OBJ_nid2sn(Native.EVP_MD_type(ptr))); } } #endregion } #endregion #region EVP_MD_CTX [StructLayout(LayoutKind.Sequential)] struct EVP_MD_CTX { public IntPtr digest; public IntPtr engine; public uint flags; public IntPtr md_data; public IntPtr pctx; public IntPtr update; } #endregion /// <summary> /// Wraps the EVP_MD_CTX object /// </summary> public class MessageDigestContext : Base { private MessageDigest md; /// <summary> /// Calls BIO_get_md_ctx() then BIO_get_md() /// </summary> /// <param name="bio"></param> public MessageDigestContext(BIO bio) : base(Native.ExpectNonNull(Native.BIO_get_md_ctx(bio.Handle)), false) { md = new MessageDigest(Native.ExpectNonNull(Native.BIO_get_md(bio.Handle)), false); } /// <summary> /// Calls EVP_MD_CTX_create() then EVP_MD_CTX_init() /// </summary> /// <param name="md"></param> public MessageDigestContext(MessageDigest md) : base(Native.EVP_MD_CTX_create(), true) { Native.EVP_MD_CTX_init(ptr); this.md = md; } /// <summary> /// Prints the long name /// </summary> /// <param name="bio"></param> public override void Print(BIO bio) { bio.Write("MessageDigestContext: " + md.LongName); } #region Methods /// <summary> /// Calls EVP_DigestInit_ex(), EVP_DigestUpdate(), and EVP_DigestFinal_ex() /// </summary> /// <param name="msg"></param> /// <returns></returns> public byte[] Digest(byte[] msg) { var digest = new byte[md.Size]; var len = (uint)digest.Length; Native.ExpectSuccess(Native.EVP_DigestInit_ex(ptr, md.Handle, IntPtr.Zero)); Native.ExpectSuccess(Native.EVP_DigestUpdate(ptr, msg, (uint)msg.Length)); Native.ExpectSuccess(Native.EVP_DigestFinal_ex(ptr, digest, ref len)); return digest; } /// <summary> /// Calls EVP_DigestInit_ex() /// </summary> public void Init() { Native.ExpectSuccess(Native.EVP_DigestInit_ex(ptr, md.Handle, IntPtr.Zero)); } /// <summary> /// Calls EVP_DigestUpdate() /// </summary> /// <param name="msg"></param> public void Update(byte[] msg) { Native.ExpectSuccess(Native.EVP_DigestUpdate(ptr, msg, (uint)msg.Length)); } /// <summary> /// Calls EVP_DigestFinal_ex() /// </summary> /// <returns></returns> public byte[] DigestFinal() { var digest = new byte[md.Size]; var len = (uint)digest.Length; Native.ExpectSuccess(Native.EVP_DigestFinal_ex(ptr, digest, ref len)); return digest; } /// <summary> /// Calls EVP_SignFinal() /// </summary> /// <param name="pkey"></param> /// <returns></returns> public byte[] SignFinal(CryptoKey pkey) { var sig = new byte[pkey.Size]; var len = (uint)sig.Length; Native.ExpectSuccess(Native.EVP_SignFinal(ptr, sig, ref len, pkey.Handle)); return sig; } /// <summary> /// Calls EVP_VerifyFinal() /// </summary> /// <param name="sig"></param> /// <param name="pkey"></param> /// <returns></returns> public bool VerifyFinal(byte[] sig, CryptoKey pkey) { var ret = Native.ExpectSuccess(Native.EVP_VerifyFinal(ptr, sig, (uint)sig.Length, pkey.Handle)); return ret == 1; } /// <summary> /// Calls EVP_DigestInit_ex(), EVP_DigestUpdate(), and EVP_SignFinal() /// </summary> /// <param name="msg"></param> /// <param name="pkey"></param> /// <returns></returns> public byte[] Sign(byte[] msg, CryptoKey pkey) { var sig = new byte[pkey.Size]; var len = (uint)sig.Length; Native.ExpectSuccess(Native.EVP_DigestInit_ex(ptr, md.Handle, IntPtr.Zero)); Native.ExpectSuccess(Native.EVP_DigestUpdate(ptr, msg, (uint)msg.Length)); Native.ExpectSuccess(Native.EVP_SignFinal(ptr, sig, ref len, pkey.Handle)); var ret = new byte[len]; Buffer.BlockCopy(sig, 0, ret, 0, (int)len); return ret; } /// <summary> /// Calls EVP_SignFinal() /// </summary> /// <param name="md"></param> /// <param name="bio"></param> /// <param name="pkey"></param> /// <returns></returns> public static byte[] Sign(MessageDigest md, BIO bio, CryptoKey pkey) { var bmd = BIO.MessageDigest(md); bmd.Push(bio); while (true) { var bytes = bmd.ReadBytes(1024 * 4); if (bytes.Count == 0) break; } var ctx = new MessageDigestContext(bmd); var sig = new byte[pkey.Size]; var len = (uint)sig.Length; Native.ExpectSuccess(Native.EVP_SignFinal(ctx.Handle, sig, ref len, pkey.Handle)); var ret = new byte[len]; Buffer.BlockCopy(sig, 0, ret, 0, (int)len); return ret; } /// <summary> /// Calls EVP_DigestInit_ex(), EVP_DigestUpdate(), and EVP_VerifyFinal() /// </summary> /// <param name="msg"></param> /// <param name="sig"></param> /// <param name="pkey"></param> /// <returns></returns> public bool Verify(byte[] msg, byte[] sig, CryptoKey pkey) { Native.ExpectSuccess(Native.EVP_DigestInit_ex(ptr, md.Handle, IntPtr.Zero)); Native.ExpectSuccess(Native.EVP_DigestUpdate(ptr, msg, (uint)msg.Length)); var ret = Native.ExpectSuccess(Native.EVP_VerifyFinal(ptr, sig, (uint)sig.Length, pkey.Handle)); return ret == 1; } /// <summary> /// Calls EVP_VerifyFinal() /// </summary> /// <param name="md"></param> /// <param name="bio"></param> /// <param name="sig"></param> /// <param name="pkey"></param> /// <returns></returns> public static bool Verify(MessageDigest md, BIO bio, byte[] sig, CryptoKey pkey) { var bmd = BIO.MessageDigest(md); bmd.Push(bio); while (true) { var bytes = bmd.ReadBytes(1024 * 4); if (bytes.Count == 0) break; } var ctx = new MessageDigestContext(bmd); var ret = Native.ExpectSuccess(Native.EVP_VerifyFinal(ctx.Handle, sig, (uint)sig.Length, pkey.Handle)); return ret == 1; } #endregion #region IDisposable Members /// <summary> /// Calls EVP_MD_CTX_cleanup() and EVP_MD_CTX_destroy() /// </summary> protected override void OnDispose() { Native.EVP_MD_CTX_cleanup(ptr); Native.EVP_MD_CTX_destroy(ptr); } #endregion } }
dantmnf/YASS
openssl-net/ManagedOpenSsl/Crypto/MessageDigest.cs
C#
gpl-3.0
11,581
#include <core/session.h> #include <core/request.h> #include <tools/property_set.h> #include <core/context.h> #include <core/controller_spawn.h> #include <core/target.h> BEGIN_ENUM_IMPL(ExecutionStatus) { {"Unplanned", (uint32_t)EExecutionStatus::Unplanned}, {"Pending", (uint32_t)EExecutionStatus::Pending}, {"Planned", (uint32_t)EExecutionStatus::Planned}, {"Skipped", (uint32_t)EExecutionStatus::Skipped}, {"Waiting", (uint32_t)EExecutionStatus::Waiting}, {"Async", (uint32_t)EExecutionStatus::Async}, {"Done", (uint32_t)EExecutionStatus::Done}, }; END_ENUM_IMPL(ExecutionStatus); Session::Session(): current_execution_level(1), finished(false) { } Session::~Session() { inputs.clear(); outputs.clear(); bypass.reset(); action_bypasses.clear(); } PropertySetPtr Session::getBypass() { return bypass; } PropertySetPtr Session::getBypass(int32_t action_id) { if(action_bypasses.count(action_id) == 0) action_bypasses[action_id].reset(new PropertySet()); return action_bypasses[action_id]; } std::set<int32_t> & Session::getNexts() { return nexts; } std::set<int32_t> & Session::getPendings() { return pendings; } std::set<Target> & Session::getSubQueries() { return subqueries; } std::map<int32_t, EExecutionStatus> & Session::getStatus() { return status; } EExecutionStatus Session::getStatus(int32_t action_id) const { return status.at(action_id); } void Session::setStatus(int32_t action_id, EExecutionStatus s) { status[action_id] = s; } std::map<int32_t, std::map<std::string, ContextPtr> > & Session::getInputs() { return inputs; } std::map<int32_t, std::map<std::string, ContextPtr> > & Session::getOutputs(){ return outputs; } void Session::setOutput(int32_t action_id, const std::string & output, ContextPtr ctx) { outputs[action_id][output] = ctx; } ContextPtr Session::getOutput( int32_t aid, const std::string & output) { if(outputs.count(aid) > 0 and outputs[aid].count(output) > 0 ) return outputs[aid][output]; return ContextPtr(); } void Session::setInput(int32_t action_id, const std::string & input, ContextPtr ctx) { inputs[action_id][input] = ctx; } ContextPtr Session::getInput( int32_t action_id, const std::string & input) { if(inputs[action_id].count(input) > 0) { return inputs[action_id][input]; } return ContextPtr(); } void Session::addSubQuery(const Target & t) { subqueries.insert(t); } void Session::removeSubQuery(const Target & t) { subqueries.erase(t); } uint32_t Session::getCurrentExecutionLevel() const { return current_execution_level; } void Session::upCurrentExecutionLevel() { current_execution_level++; } RequestPtr Session::getOriginalRequest() const { return request; } const std::vector<RequestPtr> & Session::getRequests() const { return requests; } RequestPtr Session::getLastRequest() const { if(requests.size() == 0) return RequestPtr(); auto it = requests.rbegin(); return * it; } ControllerSpawnPtr Session::getControllerSpawn() { if(request) return request->getControllerSpawn(); return ControllerSpawnPtr(); } void Session::pushRequest(RequestPtr req) { if(not request) { // initial request found ! request = req; //! recovering bypasses ... bypass = req->getBypass(); action_bypasses = req->getActionBypasses(); } requests.push_back(req); } bool Session::hasFinished() { return finished; } void Session::setFinished() { finished = true; } OSTREAM_HELPER_IMPL(Session, obj) { out << "[Session]"; return out; }
kluthen/libworkflow
core/session.cpp
C++
gpl-3.0
3,699
import Form from 'cerebral-module-forms/Form'; import {TOX_MAX_FRIEND_REQUEST_LENGTH} from './../../../../shared/tox'; export default function sendMessage () { return Form({ message: { value: '', isRequired: true, validations: [{ maxBytes: TOX_MAX_FRIEND_REQUEST_LENGTH }], errorMessages: ['invalidMessage'] } }); }
toxzilla/app
src/app/modules/Chat/forms/sendMessage.js
JavaScript
gpl-3.0
368
package fr.guiguilechat.jcelechat.model.sde.attributes; import fr.guiguilechat.jcelechat.model.sde.DoubleAttribute; /** * */ public class HeatDamage extends DoubleAttribute { public static final HeatDamage INSTANCE = new HeatDamage(); @Override public int getId() { return 1211; } @Override public int getCatId() { return 7; } @Override public boolean getHighIsGood() { return false; } @Override public double getDefaultValue() { return 0.0; } @Override public boolean getPublished() { return true; } @Override public boolean getStackable() { return true; } @Override public String toString() { return "HeatDamage"; } }
guiguilechat/EveOnline
model/sde/SDE-Types/src/generated/java/fr/guiguilechat/jcelechat/model/sde/attributes/HeatDamage.java
Java
gpl-3.0
784
package de.hablijack.eilkurier.form; import org.hibernate.validator.constraints.NotEmpty; public class CategoryCreateForm { @NotEmpty private String name = ""; private String description = ""; private byte[] picture; private String pictureContentType; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public byte[] getPicture() { return picture; } public void setPicture(byte[] picture) { this.picture = picture; } public String getPictureContentType() { return pictureContentType; } public void setPictureContentType(String pictureContentType) { this.pictureContentType = pictureContentType; } }
hablijack/eilkurier
src/main/java/de/hablijack/eilkurier/form/CategoryCreateForm.java
Java
gpl-3.0
862
package edu.vanderbilt.clinicalsystems.epic.annotation.builder.javac; import com.sun.source.tree.Tree; import edu.vanderbilt.clinicalsystems.epic.annotation.builder.RoutineTools.ReportType; public abstract class TreeInterpreter<R,P> extends TreeVisitorAdapter<R,P> { private final RoutineJdkTools m_builderTools ; public TreeInterpreter(RoutineJdkTools builderTools) { m_builderTools = builderTools ; } protected void report( ReportType reportType, String message, Tree tree) { m_builderTools.report( reportType, message, tree ); } @Override protected RuntimeException unsupportedTreeTypeException(Tree tree, P parameter) { RuntimeException ex = super.unsupportedTreeTypeException(tree, parameter); report( ReportType.ERROR, ex.getMessage(), tree ); return ex; } }
timcoffman/java-m-engine
EpicAnnotationJdkProcessing/src/main/java/edu/vanderbilt/clinicalsystems/epic/annotation/builder/javac/TreeInterpreter.java
Java
gpl-3.0
789
/* * Palantír Pocket * http://mynameisrienk.com/?palantir * https://github.com/MyNameIsRienk/PalantírPocket **/ /* * IMPORTANT! * Temporarily added ?[Date.now] params to all urls to easily bypass * caching. This needs to be remove prior to commit for production! * * PROBLEM! * The window does not deal well with zoomed out (i.e. non-responsive) * web pages on iOS. Possible solutions are (1) setting body overflow * to hidden and dimensions equel to device window size, (2) a more * responsive version using FlameViewportScale.js^, (3) resetting * the viewport meta attributes. * ^http://menacingcloud.com/source/js/FlameViewportScale.js **/ var PP_JSON = PP_JSON || '//mynameisrienk.github.io/palantirpocket/data.json?' + Date.now(); var PP_CSS = PP_CSS || '//mynameisrienk.github.io/palantirpocket/stylesheet.css?' + Date.now(); var PP_ICON = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAArklEQVR4XqWQQQqDQAxFf1zY21k3XsAeoHgYu7NasV5QqM5mUlACw5RMWvrh7T6Pn2TMjH/IEGSaJtYgIoRIQsFurKrqg2VZMI4jI04s8P7obJsTICmKM4bhIRJ9QSplWaLvB04s8ADiW4975/m5s64vdN2df1pQ15cQ6SkLojjnQqSnC4hgYAiOUAJbYCA9/YkW9hOJdOwFIOT5SQWg1AJG295MvFcETXOlbxHBG8Vy2fHIq9l6AAAAAElFTkSuQmCC"; /* Insert DOM Elements ============================================================================ */ function palantirCallback(data) { // Stringify & parse as a precaution; reverse data to keep with JSON file window.list = JSON.parse(JSON.stringify(data)) || data; var palantir = document.createDocumentFragment(); var div = document.createElement('div'); div.id = 'PALANTIR'; var box = document.createElement('div'); box.id = 'palantir-search-box'; var field = document.createElement('div'); field.id = 'palantir-search-field'; var search = document.createElement('input'); search.id = 'palantir-search'; search.type = 'search'; search.placeholder = 'Search' var ul = document.createElement('ul'); ul.id = 'palantir-results'; // Loop through the JSONP provided object for (var i = 0; i < list.length; i++) { var li = document.createElement('li'); // Add favicons (if available) if(list[i].icon != null) { var icon = list[i].icon; } else { var domain = list[i].url.match(/(https?:\/\/)([\da-z\.-]+)\.([a-z\.]{2,6})\/?/); var icon = (domain) ? 'http://' + domain[2].replace('www.','').substr(0,1) + '.getfavicon.appspot.com/' + domain[0] + '?defaulticon=lightpng': PP_ICON; } var a = document.createElement('a'); a.href = list[i].url; var desc = (list[i].description != null) ? list[i].description : list[i].url; var txt = "<span>" + list[i].title + "</span>" + desc; a.innerHTML = txt; li.appendChild(a); li.style.backgroundImage = "url(" + icon + ")"; ul.appendChild(li); }; // Append window to screen field.appendChild(search); box.appendChild(field); div.appendChild(box); div.appendChild(ul); palantir.appendChild(div); document.getElementsByTagName('body')[0].appendChild(palantir); // Add an open/close button var btn = document.createElement('a'); btn.href = 'javascript:void(0);' btn.id = 'palantir-close'; btn.addEventListener('click', function(e) { var el = document.getElementById('PALANTIR'); el.className = (el.className != 'open' ? 'open' : ''); }); document.getElementsByTagName('body')[0].appendChild(btn); // Calling clientHeight forces layout on element, req. for animation var reset = div.clientHeight; div.className = 'open'; // Add search function document.getElementById('palantir-search').addEventListener('keyup', palantirSearch ); document.getElementById('palantir-search').addEventListener('click', palantirSearch ); document.getElementById('palantir-search').addEventListener('blur', palantirSearch ); } function palantirSearch() { var items = document.getElementById('palantir-results').getElementsByTagName('li'); var val = document.getElementById('palantir-search').value; if( val ) { for (var i = items.length - 1; i >= 0; i--) { items[i].style.display="none"; }; // Escape Regex specials and split query words var input = val.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); input = input.split(/\s/); // Create a regex for query words in any order var regex = '^'; for( i = 0; i < input.length; i++ ) { regex += '(?=.*' + input[i] + ')'; } var query = new RegExp( regex, 'i' ); // Query the list of items list.filter( function( value, index, list ) { if( (value.title + value.description).search( query ) !== -1 ) { items[index].style.display="block"; } }, query ); } else { for (var i = items.length - 1; i >= 0; i--) { items[i].style.display="block"; }; } } /* Insert JSONP & CSS ============================================================================ */ var css = document.createElement('style'); css.type = 'text/css'; css.innerHTML = '@import "' + PP_CSS + '";'; document.getElementsByTagName('body')[0].appendChild(css); var head = document.getElementsByTagName('head')[0]; var palantirFile = document.createElement('script'); palantirFile.type = 'text/javascript'; palantirFile.src = PP_JSON; head.appendChild(palantirFile);
mynameisrienk/Palantir-Pocket
src/script.js
JavaScript
gpl-3.0
5,311
@javax.xml.bind.annotation.XmlSchema(namespace = "http://tempuri.org/", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package com.trafree.crawler.client;
LeoLiao321/Test
TestGradle/src/main/java/com/trafree/crawler/client/package-info.java
Java
gpl-3.0
176
package hardcorequesting.proxies; import hardcorequesting.BlockHighlightRemover; import hardcorequesting.client.interfaces.hud.GUIOverlay; import hardcorequesting.client.sounds.SoundHandler; import hardcorequesting.quests.Quest; import hardcorequesting.quests.QuestTicker; import net.minecraft.client.Minecraft; import net.minecraftforge.common.MinecraftForge; public class ClientProxy extends CommonProxy { public SoundHandler soundHandler; @Override public void initSounds(String path) { //init all the sounds } @Override public void initRenderers() { //init the rendering stuff //MinecraftForge.EVENT_BUS.register(new GUIOverlay(Minecraft.getMinecraft())); new BlockHighlightRemover(); } @Override public void init() { Quest.serverTicker = new QuestTicker(false); Quest.clientTicker = new QuestTicker(true); } }
hilburn/HQM
src/main/java/hardcorequesting/proxies/ClientProxy.java
Java
gpl-3.0
874
<? echo Controller::byName('browse')->renderView('pagination_info', array( 'page' => $page, 'per_page' => $per_page, 'total' => $total, 'word' => 'queue' )); ?> <?= Controller::byName('queue')->renderView('draw_queues', array('queues' => $queues)); ?> <? echo Controller::byName('browse')->renderView('pagination', array( 'page' => $page, 'per_page' => $per_page, 'total' => $total, 'base_url' => '/queues', )); ?>
qharley/BotQueue
views/queue/home.php
PHP
gpl-3.0
434
/*------------------------------------------------------------------------------ Copyright 2014, HexWorld Authors. This file is part of HexWorld. HexWorld is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. HexWorld is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with HexWorld. If not, see <http://www.gnu.org/licenses/>. ------------------------------------------------------------------------------*/ /** @file c_null.hpp @brief Null Component. @author Luis Cabellos @date 2013-10-13 */ //------------------------------------------------------------------------------ #ifndef C_NULL_HPP_ #define C_NULL_HPP_ //------------------------------------------------------------------------------ #include "component.hpp" //------------------------------------------------------------------------------ class CNull : public Component { public: constexpr static ComponentType type = ComponentType::CT_NULL; CNull( Entity & e ); ComponentType getType() const override; void test() const; private: }; //------------------------------------------------------------------------------ inline ComponentType CNull::getType() const{ return type; } //------------------------------------------------------------------------------ #endif//C_NULL_HPP_ //------------------------------------------------------------------------------
zhensydow/hworld
src/ent/c_null.hpp
C++
gpl-3.0
1,830
/** * Copyright (C) Intersect 2012. * * This module contains Proprietary Information of Intersect, * and should be treated as Confidential. */ package au.org.intersect.exsite9.commands.handlers; import java.io.File; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.IHandler; import org.eclipse.core.commands.IHandlerListener; import org.eclipse.core.commands.NotEnabledException; import org.eclipse.core.commands.NotHandledException; import org.eclipse.core.commands.common.NotDefinedException; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.handlers.HandlerUtil; import org.eclipse.ui.handlers.IHandlerService; import au.org.intersect.exsite9.domain.Folder; import au.org.intersect.exsite9.domain.Project; import au.org.intersect.exsite9.domain.ResearchFile; import au.org.intersect.exsite9.jobs.ConsolidateFoldersJob; import au.org.intersect.exsite9.service.IProjectManager; import au.org.intersect.exsite9.service.IProjectService; import au.org.intersect.exsite9.service.IResearchFileService; /** * Command handler to allow a user to locate a file on disk that is flagged as missing in the project, via the plugin.xml */ public class FindResearchFileHandler implements IHandler { private static final Logger LOG = Logger.getLogger(FindResearchFileHandler.class); @Override public void addHandlerListener(final IHandlerListener handlerListener) { } @Override public void dispose() { } @Override public Object execute(ExecutionEvent event) throws ExecutionException { final IWorkbenchWindow activeWorkbenchWindow = HandlerUtil.getActiveWorkbenchWindow(event); try { final Shell shell = activeWorkbenchWindow.getShell(); final IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getActiveWorkbenchWindow(event) .getActivePage().getSelection(); final Object selectionObject = selection.getFirstElement(); final IProjectManager projectManager = (IProjectManager) PlatformUI.getWorkbench().getService( IProjectManager.class); final Project currentProject = projectManager.getCurrentProject(); final IResearchFileService researchFileService = (IResearchFileService) PlatformUI.getWorkbench().getService( IResearchFileService.class); final IProjectService projectService = (IProjectService) PlatformUI.getWorkbench().getService( IProjectService.class); FileDialog fileDialog = new FileDialog(shell); fileDialog.setText("choose the file in it's new location"); final String newFilePath = fileDialog.open(); final File newFileObject = new File(newFilePath); if (!newFileObject.exists() || !newFileObject.canRead() || !newFileObject.isFile()) { MessageDialog.openError(shell, "Error", "The file you provided does not exist or is not readable."); return null; } String parentPathOfNewFile = newFileObject.getParent(); Folder folder = new Folder(new File(parentPathOfNewFile)); // Watched folder checking for (Folder existingFolder : currentProject.getFolders()) { if (existingFolder.getFolder().getAbsolutePath().equalsIgnoreCase(parentPathOfNewFile) || parentPathOfNewFile.startsWith(existingFolder.getFolder().getAbsolutePath())) { // means the new location is in a folder that is already being watched or in a sub-folder of a watched folder for (ResearchFile existingResearchFile : existingFolder.getFiles()) { if (existingResearchFile.getFile().equals(newFileObject)) { boolean confirmation = MessageDialog.openConfirm(shell, "", "The file you have chosen is already in the system in another location, by proceeding, that file and any associated metadata will be removed."); if (confirmation) { projectService.removeResearchFileFromSystem(existingResearchFile.getId()); ((ResearchFile) selectionObject).setFile(newFileObject); researchFileService.updateResearchFile((ResearchFile) selectionObject); researchFileService.changeAFilesParentFolder((ResearchFile) selectionObject, existingFolder.getId()); } return null; } } // if it hits this point it means that the folder is already watched or is a sub of a watched folder but the file is not currently in // the system ((ResearchFile) selectionObject).setFile(newFileObject); researchFileService.updateResearchFile((ResearchFile) selectionObject); return null; } else if(existingFolder.getFolder().getAbsolutePath().startsWith(parentPathOfNewFile)) {//means the location of the relocated file is now in the parent of a watched sub-folder //we know the file doesn't exist in the system because the file is in the parent of a watched //folder so is basically the same as being in an un-watched folder ((ResearchFile) selectionObject).setFile(newFileObject); researchFileService.updateResearchFile((ResearchFile) selectionObject); //add the parent folder to the list of watched folders and consolidate the files from the sub-folder projectService.mapFolderToProject(currentProject, folder); final List<Folder> subFoldersOfNewFolder = new ArrayList<Folder>(); subFoldersOfNewFolder.add(existingFolder); Job consolidateFolders = new ConsolidateFoldersJob(folder, subFoldersOfNewFolder); consolidateFolders.schedule(); } } // non-watched folder boolean startWatchingFolder = MessageDialog.openConfirm(shell, "Watch Folder?", "The file you selected is not currently within a watched folder, to change the location of this file to your selected directory the system must begin watching that directory, do you want to do this?"); if (startWatchingFolder) { ((ResearchFile) selectionObject).setFile(newFileObject); researchFileService.updateResearchFile((ResearchFile) selectionObject); projectService.mapFolderToProject(currentProject, folder); return null; } return null; } finally { final IHandlerService handlerService = (IHandlerService) activeWorkbenchWindow.getService(IHandlerService.class); try { handlerService.executeCommand("au.org.intersect.exsite9.commands.ReloadProjectCommand", null); } catch (NotDefinedException e) { LOG.error("Cannot execute reload project command", e); } catch (NotEnabledException e) { LOG.error("Cannot execute reload project command", e); } catch (NotHandledException e) { LOG.error("Cannot execute reload project command", e); } } } @Override public boolean isEnabled() { return true; } @Override public boolean isHandled() { return true; } @Override public void removeHandlerListener(final IHandlerListener handlerListener) { } }
IntersectAustralia/exsite9
exsite9/src/au/org/intersect/exsite9/commands/handlers/FindResearchFileHandler.java
Java
gpl-3.0
8,200
package de.skycoder42.kpt; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import keepass2android.pluginsdk.PluginActionBroadcastReceiver; import keepass2android.pluginsdk.PluginAccessException; import keepass2android.pluginsdk.Strings; public class TransferActionReceiver extends PluginActionBroadcastReceiver { private Intent _currentIntent; @Override protected void openEntry(OpenEntryAction oe) { try { oe.addEntryAction(oe.getContext().getString(R.string.action_entry), R.mipmap.ic_foreground, new Bundle()); } catch (PluginAccessException e) { Log.getStackTraceString(e); } } @Override protected void actionSelected(ActionSelectedAction actionSelected) { Intent intent = new Intent(actionSelected.getContext(), KptActivity.class); intent.putExtra(KptActivity.DataEntriesExtra, actionSelected.getEntryFields()); String[] protFields = actionSelected.getProtectedFieldsList(); if (protFields == null) {//in case it was fixed -> only if not successful (see https://github.com/PhilippC/keepass2android/issues/627) try { JSONArray fieldData = new JSONArray(_currentIntent.getStringExtra(Strings.EXTRA_PROTECTED_FIELDS_LIST)); protFields = new String[fieldData.length()]; for(int i = 0; i < fieldData.length(); i++) protFields[i] = fieldData.getString(i); } catch(JSONException e) { Log.getStackTraceString(e); protFields = new String[0]; } } intent.putExtra(KptActivity.GuardedEntriesExtra, protFields); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); actionSelected.getContext().startActivity(intent); } @Override public void onReceive(Context context, Intent intent) { _currentIntent = intent; super.onReceive(context, intent); _currentIntent = null; } }
Skycoder42/KeepassTransfer
clients/quick/android/src/de/skycoder42/kpt/TransferActionReceiver.java
Java
gpl-3.0
1,913
/** * @file test-tls-harry-chr.cpp * @brief Test code for Halloween Harry .CHR tilesets. * * Copyright (C) 2010-2015 Adam Nielsen <malvineous@shikadi.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "test-tileset.hpp" class test_tls_harry_chr: public test_tileset { public: test_tls_harry_chr() { this->type = "tls-harry-chr"; this->lenMaxFilename = -1; this->lenFilesizeFixed = 16 * 16; this->content[0] = this->tile1(); this->content[1] = this->tile2(); this->content[2] = this->tile3(); this->content[3] = this->tile4(); this->firstTileDims = {16, 16}; } void addTests() { this->test_tileset::addTests(); // c00: Initial state this->isInstance(ArchiveType::Certainty::PossiblyYes, this->initialstate()); // c01: All tiles present this->isInstance(ArchiveType::Certainty::DefinitelyYes, std::string(16 * 16 * 255, '\x00')); // c02: Wrong size this->isInstance(ArchiveType::Certainty::DefinitelyNo, STRING_WITH_NULLS( "\x00" )); } virtual std::string tile1() const { return STRING_WITH_NULLS( "\x0F\x00\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x09\x09\x09\x09\x09\x09\x09\x09\x09\x09\x09\x09\x09\x00\x0E" ); } virtual std::string tile2() const { return STRING_WITH_NULLS( "\x0F\x01\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x09\x09\x09\x09\x09\x09\x09\x09\x09\x09\x09\x09\x09\x01\x0E" ); } virtual std::string tile3() const { return STRING_WITH_NULLS( "\x0F\x02\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x09\x09\x09\x09\x09\x09\x09\x09\x09\x09\x09\x09\x09\x02\x0E" ); } virtual std::string tile4() const { return STRING_WITH_NULLS( "\x0F\x03\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0A" "\x0C\x09\x09\x09\x09\x09\x09\x09\x09\x09\x09\x09\x09\x09\x03\x0E" ); } virtual std::string initialstate() { return this->tile1() + this->tile2() ; } virtual std::string rename() { throw stream::error("This tileset does not have any tilenames."); } virtual std::string insert_end() { return this->tile1() + this->tile2() + this->tile3() ; } virtual std::string insert_mid() { return this->tile1() + this->tile3() + this->tile2() ; } virtual std::string insert2() { return this->tile1() + this->tile3() + this->tile4() + this->tile2() ; } virtual std::string remove() { return this->tile2() ; } virtual std::string remove2() { return {}; } virtual std::string insert_remove() { return this->tile3() + this->tile2() ; } virtual std::string move() { return this->tile2() + this->tile1() ; } virtual std::string resize_larger() { throw stream::error("Tiles in this format are a fixed size."); } virtual std::string resize_smaller() { throw stream::error("Tiles in this format are a fixed size."); } virtual std::string resize_write() { throw stream::error("Tiles in this format are a fixed size."); } }; IMPLEMENT_TESTS(tls_harry_chr);
Malvineous/libgamegraphics
tests/test-tls-harry-chr.cpp
C++
gpl-3.0
7,766
/*Jacob Meserve *Main *5/11/15 *The Main file */ import java.util.Scanner; import java.util.ArrayList; public class DungeonVania{ public static final long MAGIC = 0x57ddec8c; // The program will explode if this line is removed! private static Player player; private static Dungeon dungeon; private static Shop shop; private static Scanner input; private static Logger logan = Logger.getInstance(); public static void main(String[] args){ // try{ input = new Scanner(System.in); if(SaveGame.doesSaveFileExist()){ System.out.print("A save file exists, would you like to load it? (yes/no): "); if(yesNo()) player = SaveGame.load(); else{ System.out.print("Name: "); String name = input.nextLine(); player = new Player(name); } } else{ System.out.print("Name: "); String name = input.nextLine(); player = new Player(name); } shop = new Shop(player); System.out.println(player.getName() + ": starts in the town"); System.out.println(player.getName() + ": checks their pockets and finds " + player.getMoney() + " gold"); System.out.println("0. Go to Bed"); System.out.println("1. Go to the nearby dungeon"); System.out.println("2. Go to the store"); System.out.println("3. Check Inventory"); System.out.println("4. Save Game"); System.out.print("Choice: "); int intPut = input.nextInt(); getMenu(intPut); while(intPut != 0){ getMenuText(); intPut = input.nextInt(); getMenu(intPut); } // }catch(Exception e){ // System.out.println("A catastrophic error has ocurred, and the program must quit."); // logan.log_error("A catastrophic error has ocurred, and the program must quit."); // logan.log_error(e.getCause()); // logan.log_error(e.getLocalizedMessage()); // logan.log_error(e.getMessage()); // throw e; // } } /* Prompts the user for a yes/no answer. Returns true if yes, else returns false */ public static boolean yesNo(){ String yn = ""; while(true){ yn = input.nextLine(); if(yn.equalsIgnoreCase("yes") || yn.equalsIgnoreCase("y") || yn.equalsIgnoreCase("ye")) return true; else if(yn.equalsIgnoreCase("no") || yn.equalsIgnoreCase("n")) return false; else System.out.println("Yes or no please!"); // switch(yn){ // case "yes": // return true; // case "no": // return false; // default: // System.out.println("Yes or no please!"); // } } } /* Prints a menu of options. */ public static void getMenuText(){ System.out.println("0. Go to Bed"); System.out.println("1. Go to the nearby dungeon"); System.out.println("2. Go to the store"); System.out.println("3. Check Inventory"); System.out.println("4. Save Game"); System.out.print("Choice: "); } public static void printPlayerInventoryWithFormatting(){ ArrayList<Item> inv = player.getInventory(); Item wep = inv.get(2); Item arm = inv.get(1); Item pot = inv.get(0); int health = player.getHealth(); int money = player.getMoney(); String name = player.getName(); System.out.println("Name: " + name); System.out.println("Health: " + health); System.out.println("Money: " + money + "g"); System.out.println("Weapon Tier: " + wep.getItemAttribute("TIER")); System.out.println("Weapon damage: " + wep.getItemAttribute("MIN_DAMAGE") + " to " + wep.getItemAttribute("MAX_DAMAGE")); System.out.println("Armour Tier: " + arm.getItemAttribute("TIER")); System.out.println("Armour defense: " + arm.getItemAttribute("DEFENSE")); System.out.println("Amount of Potions: " + pot.getItemAttribute("AMOUNT")); } public static void getMenu(int choice){ if(choice == 1){ goToDungeon(); }else if(choice == 2){ System.out.println(player.getName() + ": walks to the nearby store."); goToStore(); }else if(choice == 3){ // System.out.println("Health: " + player.getHealth() // ArrayList<Item> playerInv = player.getInventory(); // for(int i = 0; i < playerInv.size(); i++) // System.out.println((i + 1) + ": " + playerInv.get(i).toString()); // System.out.println(player.toString()); printPlayerInventoryWithFormatting(); }else if(choice == 4){ if(SaveGame.doesSaveFileExist()){ System.out.print("A save file already exists, are you sure you would like to overwrite it? (yes/no) "); if(!yesNo()) return; } Logger.getInstance().log_std("Saving game..."); System.out.println("Saving game..."); SaveGame.save(player); }else if(choice == 0) endGame(); } public static void endGame(){ System.exit(0); } public static void goToDungeon(){ System.out.println(player.getName() + ": walks to the nearby dungeon."); dungeon = new Dungeon(); ArrayList<Enemy> enemies; int choice = -1; while(choice != 0 || dungeon.canMoveToNextRoom()){ enemies = dungeon.getCurrentRoom().getEnemies(); if(enemies.size()>0) System.out.println(player.getName() + ": encounters " + enemies.size() + " enemies"); for(int i = 0; i < enemies.size(); i++){ System.out.print(enemies.get(i).getName() + " " + (i + 1) + "\'s Health: " + enemies.get(i).getHealth() + "\t"); System.out.print("Defense: " + enemies.get(i).getDefense() + "\t"); System.out.println("Damage: " + enemies.get(i).getDamage()); } System.out.println(player.getName() + "\'s health: " + player.getHealth()); System.out.println(player.getName() + "\'s damage: " + player.getInventory().get(2).getItemAttribute("MIN_DAMAGE") + " to " + player.getInventory().get(2).getItemAttribute("MAX_DAMAGE")); if(dungeon.canMoveToNextRoom()){ System.out.println("1. Search room"); System.out.println("2. Check Inventory"); System.out.println("3. Use Items"); System.out.println("4. Move to next room"); System.out.println("0. Escape"); }else{ System.out.println("1. Attack"); System.out.println("2. Check Inventory"); System.out.println("3. Use Items"); System.out.println("4. Move to next room"); System.out.println("0. Escape"); } System.out.print("Choice: "); int intPut = input.nextInt(); if(intPut == 1){ if(dungeon.canMoveToNextRoom()){ player.searchRoom(dungeon.getCurrentRoom()); }else{ if(enemies.size() > 1){ System.out.println("Which enemy would you like to attack"); for(int i = 0; i < enemies.size(); i++){ System.out.print("Enemy " + (i+1) + "\t"); } System.out.print("\nChoice: "); intPut = input.nextInt()-1; int damageTaken = player.damageEnemy(enemies.get(intPut)); System.out.println(enemies.get(intPut).getName() + " " + (intPut + 1) + ": took " + damageTaken + " damage"); if(enemies.get(intPut).isDead()) System.out.println(enemies.get(intPut).getName() + " " + (intPut + 1) + " died!"); }else{ int damageTaken = player.damageEnemy(enemies.get(0)); System.out.println(enemies.get(0).getName() + " " + 1 + ": took " + damageTaken + " damage"); } } }else if(intPut == 2){ // System.out.println(player.toString()); printPlayerInventoryWithFormatting(); continue; }else if(intPut == 3){ // System.out.println(player.toString()); printPlayerInventoryWithFormatting(); System.out.print("How many potions would you like to use: "); intPut = input.nextInt(); for(int i = 0; i < intPut; i++) player.usePotion(); }else if(intPut == 4){ if(dungeon.moveToNextRoom()) System.out.println(player.getName() + " moves on from room " + (dungeon.getCRoom()-1) + ", and ventures further into the dungeon."); else System.out.println("Cannot move to the next room, because there are enemies in the way!"); continue; }else if(intPut == 0){ int damageAmount = (int)(Math.random()*(enemies.size())); System.out.println(player.getName() + " tried to escape, and took " + damageAmount + " damage in the process."); player.addHealth(-damageAmount); return; }else{ System.out.println("Invalid choice!"); continue; } dungeon.Execute(player); if(player.isDead()){ deathMessage(dungeon); return; } } } public static void goToStore(){ System.out.println(player.getName() + ": enters the store"); System.out.println(shop.menu()); } /* Prints the death message of the player. */ public static void deathMessage(Dungeon d){ System.out.println("After many battles, " + player.getName() + " was finally defeated in room #" + d.getCRoom() + " of the Dugeon " + d.getName() + "."); System.out.println(player.getName() + " died while carrying " + player.getMoney() + " gold and " + player.getInventory().get(0).getItemAttribute("AMOUNT") + " potions."); System.out.print("Would you like to load a previous save, or quit? (yes/no) "); if(yesNo()) player = SaveGame.load(); else endGame(); } }
AFlyingCar/DungeonVania
DungeonVania.java
Java
gpl-3.0
8,850
/* * 04/07/2005 * * RTextAreaBase.java - The base class for an RTextArea. * * This library is distributed under a modified BSD license. See the included * RSyntaxTextArea.License.txt file for details. */ package com.power.text.rtextarea; import java.awt.AWTEvent; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.ComponentEvent; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.event.CaretEvent; import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.TextUI; import javax.swing.text.AbstractDocument; import javax.swing.text.BadLocationException; import javax.swing.text.Caret; import javax.swing.text.StyleContext; /** * This is the base class for <code>RTextArea</code>; basically it's just an * extension of <code>javax.swing.JTextArea</code> adding a bunch of properties. * <p> * * This class is only supposed to be overridden by <code>RTextArea</code>. * * @author Robert Futrell * @version 0.8 */ public abstract class RTextAreaBase extends JTextArea { public static final String BACKGROUND_IMAGE_PROPERTY = "background.image"; public static final String CURRENT_LINE_HIGHLIGHT_COLOR_PROPERTY = "RTA.currentLineHighlightColor"; public static final String CURRENT_LINE_HIGHLIGHT_FADE_PROPERTY = "RTA.currentLineHighlightFade"; public static final String HIGHLIGHT_CURRENT_LINE_PROPERTY = "RTA.currentLineHighlight"; public static final String ROUNDED_SELECTION_PROPERTY = "RTA.roundedSelection"; private boolean tabsEmulatedWithSpaces; // If true, tabs will be expanded to spaces. private boolean highlightCurrentLine; // If true, the current line is highlighted. private Color currentLineColor; // The color used to highlight the current line. private boolean marginLineEnabled; // If true, paint a "margin line." private Color marginLineColor; // The color used to paint the margin line. private int marginLineX; // The x-location of the margin line. private int marginSizeInChars; // How many 'm' widths the margin line is over. private boolean fadeCurrentLineHighlight; // "Fade effect" for current line highlight. private boolean roundedSelectionEdges; private int previousCaretY; int currentCaretY; // Used to know when to rehighlight current line. private BackgroundPainterStrategy backgroundPainter; // Paints the background. private RTAMouseListener mouseListener; private static final Color DEFAULT_CARET_COLOR = new ColorUIResource(255,51,51); private static final Color DEFAULT_CURRENT_LINE_HIGHLIGHT_COLOR = new Color(255,255,170); private static final Color DEFAULT_MARGIN_LINE_COLOR = new Color(255,224,224); private static final int DEFAULT_TAB_SIZE = 4; private static final int DEFAULT_MARGIN_LINE_POSITION = 80; /** * Constructor. */ public RTextAreaBase() { init(); } /** * Constructor. * * @param doc The document for the editor. */ public RTextAreaBase(AbstractDocument doc) { super(doc); init(); } /** * Constructor. * * @param text The initial text to display. */ public RTextAreaBase(String text) { // Don't call super(text) to avoid NPE due to our funky RTextAreaUI... init(); setText(text); } /** * Constructor. * * @param rows The number of rows to display. * @param cols The number of columns to display. * @throws IllegalArgumentException If either <code>rows</code> or * <code>cols</code> is negative. */ public RTextAreaBase(int rows, int cols) { super(rows, cols); init(); } /** * Constructor. * * @param text The initial text to display. * @param rows The number of rows to display. * @param cols The number of columns to display. * @throws IllegalArgumentException If either <code>rows</code> or * <code>cols</code> is negative. */ public RTextAreaBase(String text, int rows, int cols) { // Don't call this super() due to NPE from our funky RTextAreaUI... //super(text, rows, cols); super(rows, cols); init(); setText(text); } /** * Constructor. * * @param doc The document for the editor. * @param text The initial text to display. * @param rows The number of rows to display. * @param cols The number of columns to display. * @throws IllegalArgumentException If either <code>rows</code> or * <code>cols</code> is negative. */ public RTextAreaBase(AbstractDocument doc, String text, int rows, int cols) { // Don't call super() with text due to NPE from our funky RTextAreaUI... super(doc, null/*text*/, rows, cols); init(); setText(text); } /** * Adds listeners that listen for changes to the current line, so we can * update our "current line highlight." This is needed only because of an * apparent difference between the JRE 1.4.2 and 1.5.0 (needed on 1.4.2, * not needed on 1.5.0). */ private void addCurrentLineHighlightListeners() { boolean add = true; MouseMotionListener[] mouseMotionListeners = getMouseMotionListeners(); for (int i=0; i<mouseMotionListeners.length; i++) { if (mouseMotionListeners[i]==mouseListener) { add = false; break; } } if (add) { //System.err.println("Adding mouse motion listener!"); addMouseMotionListener(mouseListener); } MouseListener[] mouseListeners = getMouseListeners(); for (int i=0; i<mouseListeners.length; i++) { if (mouseListeners[i]==mouseListener) { add = false; break; } } if (add) { //System.err.println("Adding mouse listener!"); addMouseListener(mouseListener); } } @Override public void addNotify() { super.addNotify(); // If the caret is not on the first line, we must recalculate the line // highlight y-offset after the text area is sized. This seems to be // the best way to do it. if (getCaretPosition() != 0) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { possiblyUpdateCurrentLineHighlightLocation(); } }); } } /* * TODO: Figure out why RTextArea doesn't work with RTL orientation! */ // public void applyComponentOrientation(ComponentOrientation orientation) { // super.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); // } /** * Converts all instances of a number of spaces equal to a tab size * into a tab in this text area. * * @see #convertTabsToSpaces * @see #getTabsEmulated * @see #setTabsEmulated */ public void convertSpacesToTabs() { // FIXME: This is inefficient and will yield an OutOfMemoryError if // done on a large document. We should scan 1 line at a time and // replace; it'll be slower but safer. int caretPosition = getCaretPosition(); int tabSize = getTabSize(); StringBuilder stringBuilder = new StringBuilder(); for (int i=0; i<tabSize; i++) { stringBuilder.append(" "); } String text = getText(); setText(text.replaceAll(stringBuilder.toString(), "\t")); int newDocumentLength = getDocument().getLength(); // Place the caret back in its proper position. if (caretPosition<newDocumentLength) { setCaretPosition(caretPosition); } else { setCaretPosition(newDocumentLength-1); } } /** * Converts all instances of a tab into a number of spaces equivalent * to a tab in this text area. * * @see #convertSpacesToTabs * @see #getTabsEmulated * @see #setTabsEmulated */ public void convertTabsToSpaces() { // FIXME: This is inefficient and will yield an OutOfMemoryError if // done on a large document. We should scan 1 line at a time and // replace; it'll be slower but safer. int caretPosition = getCaretPosition(); int tabSize = getTabSize(); StringBuilder tabInSpaces = new StringBuilder(); for (int i=0; i<tabSize; i++) { tabInSpaces.append(' '); } String text = getText(); setText(text.replaceAll("\t", tabInSpaces.toString())); // Put caret back at same place in document. setCaretPosition(caretPosition); } /** * Returns the caret event/mouse listener for <code>RTextArea</code>s. * * @return The caret event/mouse listener. */ protected abstract RTAMouseListener createMouseListener(); /** * Returns the a real UI to install on this text component. Subclasses * can override this method to return an extended version of * <code>RTextAreaUI</code>. * * @return The UI. */ protected abstract RTextAreaUI createRTextAreaUI(); /** * Forces the current line highlight to be repainted. This hack is * necessary for those situations when the view (appearance) changes * but the caret's location hasn't (and thus the current line highlight * coordinates won't get changed). Examples of this are when * word wrap is toggled and when syntax styles are changed in an * <code>RSyntaxTextArea</code>. */ protected void forceCurrentLineHighlightRepaint() { // Check isShowing() to prevent BadLocationException // in constructor if linewrap is set to true. if (isShowing()) { // Changing previousCaretY makes us sure to get a repaint. previousCaretY = -1; // Trick it into checking for the need to repaint by firing // a false caret event. fireCaretUpdate(mouseListener); } } /** * Returns the <code>java.awt.Color</code> used as the background color for * this text area. If a <code>java.awt.Image</code> image is currently * being used instead, <code>null</code> is returned. * * @return The current background color, or <code>null</code> if an image * is currently the background. */ @Override public final Color getBackground() { Object bg = getBackgroundObject(); return (bg instanceof Color) ? (Color)bg : null; } /** * Returns the image currently used for the background. * If the current background is currently a <code>java.awt.Color</code> and * not a <code>java.awt.Image</code>, then <code>null</code> is returned. * * @return A <code>java.awt.Image</code> used for the background, or * <code>null</code> if the background is not an image. * @see #setBackgroundImage */ public final Image getBackgroundImage() { Object bg = getBackgroundObject(); return (bg instanceof Image) ? (Image)bg : null; } /** * Returns the <code>Object</code> representing the background for all * documents in this tabbed pane; either a <code>java.awt.Color</code> or a * <code>java.lang.Image</code> containing the image used as the background * for this text area. * * @return The <code>Object</code> used for the background. * @see #setBackgroundObject(Object newBackground) */ public final Object getBackgroundObject() { if (backgroundPainter==null) { return null; } return (backgroundPainter instanceof ImageBackgroundPainterStrategy) ? (Object)((ImageBackgroundPainterStrategy)backgroundPainter). getMasterImage() : (Object)((ColorBackgroundPainterStrategy)backgroundPainter). getColor(); } /** * Gets the line number that the caret is on. * * @return The zero-based line number that the caret is on. */ public final int getCaretLineNumber() { try { return getLineOfOffset(getCaretPosition()); } catch (BadLocationException ble) { return 0; // Never happens } } /** * Gets the position from the beginning of the current line that the caret * is on. * * @return The zero-based position from the beginning of the current line * that the caret is on. */ public final int getCaretOffsetFromLineStart() { try { int pos = getCaretPosition(); return pos - getLineStartOffset(getLineOfOffset(pos)); } catch (BadLocationException ble) { return 0; // Never happens } } /** * Returns the y-offset of the caret. * * @return The y-offset of the caret. */ protected int getCurrentCaretY() { return currentCaretY; } /** * Returns the color being used to highlight the current line. Note that * if highlighting the current line is turned off, you will not be seeing * this highlight. * * @return The color being used to highlight the current line. * @see #getHighlightCurrentLine() * @see #setHighlightCurrentLine(boolean) * @see #setCurrentLineHighlightColor */ public Color getCurrentLineHighlightColor() { return currentLineColor; } /** * Returns the default caret color. * * @return The default caret color. */ public static final Color getDefaultCaretColor() { return DEFAULT_CARET_COLOR; } /** * Returns the "default" color for highlighting the current line. Note * that this color was chosen only because it looks nice (to me) against a * white background. * * @return The default color for highlighting the current line. */ public static final Color getDefaultCurrentLineHighlightColor() { return DEFAULT_CURRENT_LINE_HIGHLIGHT_COLOR; } /** * Returns the default font for text areas. * * @return The default font. */ public static final Font getDefaultFont() { // Use StyleContext to get a composite font for better Asian language // support; see Sun bug S282887. StyleContext sc = StyleContext.getDefaultStyleContext(); Font font = null; if (isOSX()) { // Snow Leopard (1.6) uses Menlo as default monospaced font, // pre-Snow Leopard used Monaco. font = sc.getFont("Menlo", Font.PLAIN, 12); if (!"Menlo".equals(font.getFamily())) { font = sc.getFont("Monaco", Font.PLAIN, 12); if (!"Monaco".equals(font.getFamily())) { // Shouldn't happen font = sc.getFont("Monospaced", Font.PLAIN, 13); } } } else { // Consolas added in Vista, used by VS2010+. font = sc.getFont("Consolas", Font.PLAIN, 13); if (!"Consolas".equals(font.getFamily())) { font = sc.getFont("Monospaced", Font.PLAIN, 13); } } //System.out.println(font.getFamily() + ", " + font.getName()); return font; } /** * Returns the default foreground color for text in this text area. * * @return The default foreground color. */ public static final Color getDefaultForeground() { return Color.BLACK; } /** * Returns the default color for the margin line. * * @return The default margin line color. * @see #getMarginLineColor() * @see #setMarginLineColor(Color) */ public static final Color getDefaultMarginLineColor() { return DEFAULT_MARGIN_LINE_COLOR; } /** * Returns the default margin line position. * * @return The default margin line position. * @see #getMarginLinePosition * @see #setMarginLinePosition */ public static final int getDefaultMarginLinePosition() { return DEFAULT_MARGIN_LINE_POSITION; } /** * Returns the default tab size, in spaces. * * @return The default tab size. */ public static final int getDefaultTabSize() { return DEFAULT_TAB_SIZE; } /** * Returns whether the current line highlight is faded. * * @return Whether the current line highlight is faded. * @see #setFadeCurrentLineHighlight */ public boolean getFadeCurrentLineHighlight() { return fadeCurrentLineHighlight; } /** * Returns whether or not the current line is highlighted. * * @return Whether or the current line is highlighted. * @see #setHighlightCurrentLine(boolean) * @see #getCurrentLineHighlightColor * @see #setCurrentLineHighlightColor */ public boolean getHighlightCurrentLine() { return highlightCurrentLine; } /** * Returns the offset of the last character of the line that the caret is * on. * * @return The last offset of the line that the caret is currently on. */ public final int getLineEndOffsetOfCurrentLine() { try { return getLineEndOffset(getCaretLineNumber()); } catch (BadLocationException ble) { return 0; // Never happens } } /** * Returns the height of a line of text in this text area. * * @return The height of a line of text. */ public int getLineHeight() { return getRowHeight(); } /** * Returns the offset of the first character of the line that the caret is * on. * * @return The first offset of the line that the caret is currently on. */ public final int getLineStartOffsetOfCurrentLine() { try { return getLineStartOffset(getCaretLineNumber()); } catch (BadLocationException ble) { return 0; // Never happens } } /** * Returns the color used to paint the margin line. * * @return The margin line color. * @see #setMarginLineColor(Color) */ public Color getMarginLineColor() { return marginLineColor; } /** * Returns the margin line position (in pixels) from the left-hand side of * the text area. * * @return The margin line position. * @see #getDefaultMarginLinePosition * @see #setMarginLinePosition */ public int getMarginLinePixelLocation() { return marginLineX; } /** * Returns the margin line position (which is the number of 'm' widths in * the current font the margin line is over). * * @return The margin line position. * @see #getDefaultMarginLinePosition * @see #setMarginLinePosition */ public int getMarginLinePosition() { return marginSizeInChars; } /** * Returns whether selection edges are rounded in this text area. * * @return Whether selection edges are rounded. * @see #setRoundedSelectionEdges(boolean) */ public boolean getRoundedSelectionEdges() { return roundedSelectionEdges; } /** * Returns whether or not tabs are emulated with spaces (i.e., "soft" * tabs). * * @return <code>true</code> if tabs are emulated with spaces; * <code>false</code> if they aren't. * @see #setTabsEmulated */ public boolean getTabsEmulated() { return tabsEmulatedWithSpaces; } /** * Initializes this text area. */ protected void init() { // Sets the UI. Note that setUI() is overridden in RTextArea to only // update the popup menu; this method must be called to set the real // UI. This is done because the look and feel of an RTextArea is // independent of the installed Java look and feels. setRTextAreaUI(createRTextAreaUI()); // So we get notified when the component is resized. enableEvents(AWTEvent.COMPONENT_EVENT_MASK|AWTEvent.KEY_EVENT_MASK); // Defaults for various properties. setHighlightCurrentLine(true); setCurrentLineHighlightColor(getDefaultCurrentLineHighlightColor()); setMarginLineEnabled(false); setMarginLineColor(getDefaultMarginLineColor()); setMarginLinePosition(getDefaultMarginLinePosition()); setBackgroundObject(Color.WHITE); setWrapStyleWord(true);// We only support wrapping at word boundaries. setTabSize(5); setForeground(Color.BLACK); setTabsEmulated(false); // Stuff needed by the caret listener below. previousCaretY = currentCaretY = getInsets().top; // Stuff to highlight the current line. mouseListener = createMouseListener(); // Also acts as a focus listener so we can update our shared actions // (cut, copy, etc. on the popup menu). addFocusListener(mouseListener); addCurrentLineHighlightListeners(); } /** * Returns whether or not the margin line is being painted. * * @return Whether or not the margin line is being painted. * @see #setMarginLineEnabled */ public boolean isMarginLineEnabled() { return marginLineEnabled; } /** * Returns whether the OS we're running on is OS X. * * @return Whether the OS we're running on is OS X. */ public static boolean isOSX() { // Recommended at: // http://developer.apple.com/mac/library/technotes/tn2002/tn2110.html String osName = System.getProperty("os.name").toLowerCase(); return osName.startsWith("mac os x"); } /** * Paints the text area. * * @param g The graphics context with which to paint. */ @Override protected void paintComponent(Graphics g) { //long startTime = System.currentTimeMillis(); backgroundPainter.paint(g, getVisibleRect()); // Paint the main part of the text area. TextUI ui = getUI(); if (ui != null) { // Not allowed to modify g, so make a copy. Graphics scratchGraphics = g.create(); try { ui.update(scratchGraphics, this); } finally { scratchGraphics.dispose(); } } //long endTime = System.currentTimeMillis(); //System.err.println(endTime-startTime); } /** * Updates the current line highlight location. */ protected void possiblyUpdateCurrentLineHighlightLocation() { int width = getWidth(); int lineHeight = getLineHeight(); int dot = getCaretPosition(); // If we're wrapping lines we need to check the actual y-coordinate // of the caret, not just the line number, since a single logical // line can span multiple physical lines. if (getLineWrap()) { try { Rectangle temp = modelToView(dot); if (temp!=null) { currentCaretY = temp.y; } } catch (BadLocationException ble) { ble.printStackTrace(); // Should never happen. } } // No line wrap - we can simply check the line number (quicker). else { // Document doc = getDocument(); // if (doc!=null) { // Element map = doc.getDefaultRootElement(); // int caretLine = map.getElementIndex(dot); // Rectangle alloc = ((RTextAreaUI)getUI()). // getVisibleEditorRect(); // if (alloc!=null) // currentCaretY = alloc.y + caretLine*lineHeight; // } // Modified for code folding requirements try { Rectangle temp = modelToView(dot); if (temp!=null) { currentCaretY = temp.y; } } catch (BadLocationException ble) { ble.printStackTrace(); // Should never happen. } } // Repaint current line (to fill in entire highlight), and old line // (to erase entire old highlight) if necessary. Always repaint // current line in case selection is added or removed. repaint(0,currentCaretY, width,lineHeight); if (previousCaretY!=currentCaretY) { repaint(0,previousCaretY, width,lineHeight); } previousCaretY = currentCaretY; } /** * Overridden so we can tell when the text area is resized and update the * current-line highlight, if necessary (i.e., if it is enabled and if * lineWrap is enabled. * * @param e The component event about to be sent to all registered * <code>ComponentListener</code>s. */ @Override protected void processComponentEvent(ComponentEvent e) { // In line wrap mode, resizing the text area means that the caret's // "line" could change - not to a different logical line, but a // different physical one. So, here we force a repaint of the current // line's highlight if necessary. if (e.getID()==ComponentEvent.COMPONENT_RESIZED && getLineWrap() && getHighlightCurrentLine()) { previousCaretY = -1; // So we are sure to repaint. fireCaretUpdate(mouseListener); } super.processComponentEvent(e); } /** * Sets the background color of this text editor. Note that this is * equivalent to calling <code>setBackgroundObject(bg)</code>.<p> * * NOTE: the opaque property is set to <code>true</code> when the * background is set to a color with 1.0 alpha (by this method). When an * image is used for the background, opaque is set to false. This is * because we perform better when setOpaque is true, but if we use an * image for the background when opaque is true, we get on-screen * garbage when the user scrolls via the arrow keys. Thus we * need setOpaque to be false in that case.<p> * You never have to change the opaque property yourself; it is always done * for you. * * @param bg The color to use as the background color. */ @Override public void setBackground(Color bg) { Object oldBG = getBackgroundObject(); if (oldBG instanceof Color) { // Just change color of strategy. ((ColorBackgroundPainterStrategy)backgroundPainter). setColor(bg); } else { // Was an image painter... backgroundPainter = new ColorBackgroundPainterStrategy(bg); } setOpaque(bg==null || bg.getAlpha()==0xff); firePropertyChange("background", oldBG, bg); repaint(); } /** * Sets this image as the background image. This method fires a * property change event of type {@link #BACKGROUND_IMAGE_PROPERTY}.<p> * * NOTE: the opaque property is set to <code>true</code> when the * background is set to a color. When an image is used for the * background (by this method), opaque is set to false. This is because * we perform better when setOpaque is true, but if we use an * image for the background when opaque is true, we get on-screen * garbage when the user scrolls via the arrow keys. Thus we * need setOpaque to be false in that case.<p> * You never have to change the opaque property yourself; it is always done * for you. * * @param image The image to use as this text area's background. * @see #getBackgroundImage */ public void setBackgroundImage(Image image) { Object oldBG = getBackgroundObject(); if (oldBG instanceof Image) { // Just change image being displayed. ((ImageBackgroundPainterStrategy)backgroundPainter). setImage(image); } else { // Was a color strategy... ImageBackgroundPainterStrategy strategy = new BufferedImageBackgroundPainterStrategy(this); strategy.setImage(image); backgroundPainter = strategy; } setOpaque(false); firePropertyChange(BACKGROUND_IMAGE_PROPERTY, oldBG, image); repaint(); } /** * Makes the background into this <code>Object</code>. * * @param newBackground The <code>java.awt.Color</code> or * <code>java.awt.Image</code> object. If <code>newBackground</code> * is not either of these, the background is set to plain white. */ public void setBackgroundObject(Object newBackground) { if (newBackground instanceof Color) { setBackground((Color)newBackground); } else if (newBackground instanceof Image) { setBackgroundImage((Image)newBackground); } else { setBackground(Color.WHITE); } } /* * TODO: Figure out why RTextArea doesn't work with RTL (e.g. Arabic) * and fix it! */ // public void setComponentOrientation(ComponentOrientation o) { // if (!o.isLeftToRight()) { // o = ComponentOrientation.LEFT_TO_RIGHT; // } // super.setComponentOrientation(o); // } /** * Sets the color to use to highlight the current line. Note that if * highlighting the current line is turned off, you will not be able to * see this highlight. This method fires a property change of type * {@link #CURRENT_LINE_HIGHLIGHT_COLOR_PROPERTY}. * * @param color The color to use to highlight the current line. * @throws NullPointerException if <code>color</code> is <code>null</code>. * @see #getHighlightCurrentLine() * @see #setHighlightCurrentLine(boolean) * @see #getCurrentLineHighlightColor */ public void setCurrentLineHighlightColor(Color color) { if (color==null) { throw new NullPointerException(); } if (!color.equals(currentLineColor)) { Color old = currentLineColor; currentLineColor = color; firePropertyChange(CURRENT_LINE_HIGHLIGHT_COLOR_PROPERTY, old, color); } } /** * Sets whether the current line highlight should have a "fade" effect. * This method fires a property change event of type * <code>CURRENT_LINE_HIGHLIGHT_FADE_PROPERTY</code>. * * @param fade Whether the fade effect should be enabled. * @see #getFadeCurrentLineHighlight */ public void setFadeCurrentLineHighlight(boolean fade) { if (fade!=fadeCurrentLineHighlight) { fadeCurrentLineHighlight = fade; if (getHighlightCurrentLine()) { forceCurrentLineHighlightRepaint(); } firePropertyChange(CURRENT_LINE_HIGHLIGHT_FADE_PROPERTY, !fade, fade); } } /** * Sets the font for this text area. This is overridden only so that we * can update the size of the "current line highlight" and the location of * the "margin line," if necessary. * * @param font The font to use for this text component. */ @Override public void setFont(Font font) { if (font!=null && font.getSize()<=0) { throw new IllegalArgumentException("Font size must be > 0"); } super.setFont(font); if (font!=null) { updateMarginLineX(); if (highlightCurrentLine) { possiblyUpdateCurrentLineHighlightLocation(); } } } /** * Sets whether or not the current line is highlighted. This method * fires a property change of type {@link #HIGHLIGHT_CURRENT_LINE_PROPERTY}. * * @param highlight Whether or not to highlight the current line. * @see #getHighlightCurrentLine() * @see #getCurrentLineHighlightColor * @see #setCurrentLineHighlightColor */ public void setHighlightCurrentLine(boolean highlight) { if (highlight!=highlightCurrentLine) { highlightCurrentLine = highlight; firePropertyChange(HIGHLIGHT_CURRENT_LINE_PROPERTY, !highlight, highlight); repaint(); // Repaint entire width of line. } } /** * Sets whether or not word wrap is enabled. This is overridden so that * the "current line highlight" gets updated if it needs to be. * * @param wrap Whether or not word wrap should be enabled. */ @Override public void setLineWrap(boolean wrap) { super.setLineWrap(wrap); forceCurrentLineHighlightRepaint(); } /** * Overridden to update the current line highlight location. * * @param insets The new insets. */ @Override public void setMargin(Insets insets) { Insets old = getInsets(); int oldTop = old!=null ? old.top : 0; int newTop = insets!=null ? insets.top : 0; if (oldTop!=newTop) { // The entire editor will be automatically repainted if it is // visible, so no need to call repaint() or forceCurrentLine...(). previousCaretY = currentCaretY = newTop; } super.setMargin(insets); } /** * Sets the color used to paint the margin line. * * @param color The new margin line color. * @see #getDefaultMarginLineColor() * @see #getMarginLineColor() */ public void setMarginLineColor(Color color) { marginLineColor = color; if (marginLineEnabled) { Rectangle visibleRect = getVisibleRect(); repaint(marginLineX,visibleRect.y, 1,visibleRect.height); } } /** * Enables or disables the margin line. * * @param enabled Whether or not the margin line should be enabled. * @see #isMarginLineEnabled */ public void setMarginLineEnabled(boolean enabled) { if (enabled!=marginLineEnabled) { marginLineEnabled = enabled; if (marginLineEnabled) { Rectangle visibleRect = getVisibleRect(); repaint(marginLineX,visibleRect.y, 1,visibleRect.height); } } } /** * Sets the number of 'm' widths the margin line is over. * * @param size The margin size. * #see #getDefaultMarginLinePosition * @see #getMarginLinePosition */ public void setMarginLinePosition(int size) { marginSizeInChars = size; if (marginLineEnabled) { Rectangle visibleRect = getVisibleRect(); repaint(marginLineX,visibleRect.y, 1,visibleRect.height); updateMarginLineX(); repaint(marginLineX,visibleRect.y, 1,visibleRect.height); } } /** * Sets whether the edges of selections are rounded in this text area. * This method fires a property change of type * {@link #ROUNDED_SELECTION_PROPERTY}. * * @param rounded Whether selection edges should be rounded. * @see #getRoundedSelectionEdges() */ public void setRoundedSelectionEdges(boolean rounded) { if (roundedSelectionEdges!=rounded) { roundedSelectionEdges = rounded; Caret c = getCaret(); if (c instanceof ConfigurableCaret) { ((ConfigurableCaret)c).setRoundedSelectionEdges(rounded); if (c.getDot()!=c.getMark()) { // e.g., there's is a selection repaint(); } } firePropertyChange(ROUNDED_SELECTION_PROPERTY, !rounded, rounded); } } /** * Sets the UI for this <code>RTextArea</code>. Note that, for instances * of <code>RTextArea</code>, <code>setUI</code> only updates the popup * menu; this is because <code>RTextArea</code>s' look and feels are * independent of the Java Look and Feel. This method is here so * subclasses can set a UI (subclass of <code>RTextAreaUI</code>) if they * have to. * * @param ui The new UI. * @see #setUI */ protected void setRTextAreaUI(RTextAreaUI ui) { super.setUI(ui); // Workaround as setUI makes the text area opaque, even if we don't // want it to be. setOpaque(getBackgroundObject() instanceof Color); } /** * Changes whether or not tabs should be emulated with spaces (i.e., soft * tabs). Note that this affects all tabs inserted AFTER this call, not * tabs already in the document. For that, see * {@link #convertTabsToSpaces} and {@link #convertSpacesToTabs}. * * @param areEmulated Whether or not tabs should be emulated with spaces. * @see #convertSpacesToTabs * @see #convertTabsToSpaces * @see #getTabsEmulated */ public void setTabsEmulated(boolean areEmulated) { tabsEmulatedWithSpaces = areEmulated; } /** * Workaround, since in JDK1.4 it appears that <code>setTabSize()</code> * doesn't work for a <code>JTextArea</code> unless you use the constructor * specifying the number of rows and columns...<p> * Sets the number of characters to expand tabs to. This will be multiplied * by the maximum advance for variable width fonts. A PropertyChange event * ("tabSize") is fired when the tab size changes. * * @param size Number of characters to expand to. */ @Override public void setTabSize(int size) { super.setTabSize(size); boolean b = getLineWrap(); setLineWrap(!b); setLineWrap(b); } /** * This is here so subclasses such as <code>RSyntaxTextArea</code> that * have multiple fonts can define exactly what it means, for example, for * the margin line to be "80 characters" over. */ protected void updateMarginLineX() { Font font = getFont(); if (font == null) { marginLineX = 0; return; } marginLineX = getFontMetrics(font).charWidth('m') * marginSizeInChars; } /** * Returns the y-coordinate of the specified line. * * @param line The line number. * @return The y-coordinate of the top of the line, or <code>-1</code> if * this text area doesn't yet have a positive size or the line is * hidden (i.e. from folding). * @throws BadLocationException If <code>line</code> isn't a valid line * number for this document. */ public int yForLine(int line) throws BadLocationException { return ((RTextAreaUI)getUI()).yForLine(line); } /** * Returns the y-coordinate of the line containing an offset. * * @param offs The offset info the document. * @return The y-coordinate of the top of the offset, or <code>-1</code> if * this text area doesn't yet have a positive size or the line is * hidden (i.e. from folding). * @throws BadLocationException If <code>offs</code> isn't a valid offset * into the document. */ public int yForLineContaining(int offs) throws BadLocationException { return ((RTextAreaUI)getUI()).yForLineContaining(offs); } /** * Listens for mouse events in this component. */ protected class RTAMouseListener extends CaretEvent implements MouseListener, MouseMotionListener, FocusListener { RTAMouseListener(RTextAreaBase textArea) { super(textArea); } @Override public void focusGained(FocusEvent e) {} @Override public void focusLost(FocusEvent e) {} @Override public void mouseDragged(MouseEvent e) {} @Override public void mouseMoved(MouseEvent e) {} @Override public void mouseClicked(MouseEvent e) {} @Override public void mousePressed(MouseEvent e) {} @Override public void mouseReleased(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} @Override public int getDot() { return dot; } @Override public int getMark() { return mark; } protected int dot; protected int mark; } }
Thecarisma/powertext
Power Text/src/com/power/text/rtextarea/RTextAreaBase.java
Java
gpl-3.0
37,262
/* Copyright 2014-2017 Travel Modelling Group, Department of Civil Engineering, University of Toronto This file is part of XTMF. XTMF is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. XTMF is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with XTMF. If not, see <http://www.gnu.org/licenses/>. */ using System; namespace Datastructure { /// <summary> /// This class represents a pair of objects /// </summary> /// <typeparam name="TF">The first type of object</typeparam> /// <typeparam name="TS">The second type of object</typeparam> public class Pair<TF, TS> : IComparable<Pair<TF, TS>> { public Pair(TF first, TS second) { First = first; Second = second; } /// <summary> /// The first object in the pair /// </summary> public TF First { get; } /// <summary> /// The second object in the pair /// </summary> public TS Second { get; } /// <summary> /// Attempts to compare, F then S and in the last case it tries to compare hashcodes /// </summary> /// <param name="other">The pair we want to compare with</param> /// <returns>Less than zero if it is less, 0 if equal, otherwise greater than zero</returns> public int CompareTo(Pair<TF, TS> other) { var compFirst = First as IComparable<TF>; var compSecond = Second as IComparable<TS>; // if they are both comparable then we will just see if they are both equal, if not -1 if ( compFirst != null & compSecond != null ) { int value; return ( ( value = compFirst.CompareTo( other.First ) ) == 0 ) ? ( ( ( value = compSecond.CompareTo( other.Second ) ) == 0 ) ? 0 : value ) : value; } // try to compare the first value if ( compFirst != null ) { var res = compFirst.CompareTo( other.First ); // second is always null at this point return res; } // if not, try the second if ( compSecond != null ) { return compSecond.CompareTo( other.Second ); } //see if they are equal if ( First.Equals( other.First ) && Second.Equals( other.Second ) ) { return 0; } // if they are not equal, subtract the total of the hashcodes, this can cause false equals return First.GetHashCode() + Second.GetHashCode() - other.First.GetHashCode() - other.Second.GetHashCode(); }//end CompareTo public override bool Equals(object obj) { if (obj is Pair<TF, TS> other) { return (First.Equals(other.First)) && (Second.Equals(other.Second)); } return false; } /// <summary> /// We need this to have a hashcode for every pair /// </summary> /// <returns></returns> public override int GetHashCode() { // Hopefully multiplying two "random" numbers is unique enough // To go into data structures, works best when large return (First.GetHashCode() * 2 ) * Second.GetHashCode(); } }//end class }//end namespace
TravelModellingGroup/XTMF
Datastructure/Pair.cs
C#
gpl-3.0
3,842
namespace Hurricane.Views.UserControls { /// <summary> /// Interaction logic for SettingsView.xaml /// </summary> public partial class SettingsView { public SettingsView() { InitializeComponent(); } } }
Alkalinee/Hurricane
Hurricane/Views/UserControls/SettingsView.xaml.cs
C#
gpl-3.0
266
/* * This file is part of cg3lib: https://github.com/cg3hci/cg3lib * This Source Code Form is subject to the terms of the GNU GPL 3.0 * * @author Alessandro Muntoni (muntoni.alessandro@gmail.com) */ #include "dcel_builder.h" namespace cg3 { CG3_INLINE DcelBuilder::DcelBuilder(Dcel startingDcel) : d(startingDcel), updateNormalOnInsertion(true) { for (cg3::Dcel::Vertex* v : d.vertexIterator()) { mapVertices[v->coordinate()] = v->id(); } for (cg3::Dcel::HalfEdge* he : d.halfEdgeIterator()){ mapHalfEdges[std::make_pair(he->fromVertex()->id(), he->toVertex()->id())] = he->id(); } } CG3_INLINE Dcel& DcelBuilder::dcel() { return d; } CG3_INLINE unsigned int DcelBuilder::addVertex(const Point3d& p, const Vec3d& n, const Color &c, int flag) { if (mapVertices.find(p) == mapVertices.end()){ cg3::Dcel::Vertex* v = d.addVertex(p, n, c); mapVertices[p] = v->id(); v->setFlag(flag); return v->id(); } else return mapVertices[p]; } CG3_INLINE int DcelBuilder::addFace( unsigned int vid1, unsigned int vid2, unsigned int vid3, const Color& c, int flag) { std::vector<uint> vids(3); vids[0] = vid1; vids[1] = vid2; vids[2] = vid3; return addFace(vids, c, flag); } CG3_INLINE int DcelBuilder::addFace( unsigned int vid1, unsigned int vid2, unsigned int vid3, unsigned int vid4, const Color& c, int flag) { std::vector<uint> vids(4); vids[0] = vid1; vids[1] = vid2; vids[2] = vid3; vids[3] = vid4; return addFace(vids, c, flag); } CG3_INLINE int DcelBuilder::addFace(const std::vector<uint>& vids, const Color& c, int flag) { //one of the ids does not exist in the dcel for (const uint& vid : vids) if (d.vertex(vid) == nullptr) return -1; std::vector<std::pair<uint, uint>> pes; for (uint i = 0; i < vids.size(); ++i){ pes.push_back(std::make_pair(vids[i], vids[(i+1)%vids.size()])); } // one of the three edges already exists in the dcel -> // bad orientation of face or non edge-manifold mesh for (const std::pair<uint, uint>& pe : pes) if (mapHalfEdges.find(pe) != mapHalfEdges.end()) return -1; //looking for twins... std::vector<std::pair<uint, uint>> tpes; for (const std::pair<uint, uint>& pe : pes) tpes.push_back(std::make_pair(pe.second, pe.first)); std::vector<cg3::Dcel::HalfEdge*> tes(tpes.size(), nullptr); std::map<std::pair<unsigned int, unsigned int>, unsigned int>::iterator it; for (uint i = 0; i < tpes.size(); ++i){ it = mapHalfEdges.find(tpes[i]); if (it != mapHalfEdges.end()){ tes[i] = d.halfEdge(it->second); if (tes[i]->twin() != nullptr){ std::cerr << "Warning Dcel Builder: Half Edge has already a twin! " "Possible Non-Manifold Mesh\n"; } } } //add face cg3::Dcel::Face* f = d.addFace(); std::vector<cg3::Dcel::Vertex*> vs; std::vector<cg3::Dcel::HalfEdge*> hes(vids.size()); //get vertices for (uint vid : vids) vs.push_back(d.vertex(vid)); //add half edges for (uint i = 0; i < hes.size(); i++) hes[i] = d.addHalfEdge(); for (uint i = 0; i < hes.size(); i++){ //from and to vertex hes[i]->setFromVertex(vs[i]); hes[i]->setToVertex(vs[(i+1)%hes.size()]); //twin hes[i]->setTwin(tes[i]); if (tes[i]) tes[i]->setTwin(hes[i]); //vertex incident vs[i]->setIncidentHalfEdge(hes[i]); //face hes[i]->setFace(f); //prev and next if (i > 0){ hes[i]->setPrev(hes[i-1]); hes[i-1]->setNext(hes[i]); } //mapHalfEdges mapHalfEdges.insert(std::make_pair( std::make_pair(vids[i], vids[(i+1)%vids.size()]), hes[i]->id())); } //prev and next hes[0]->setPrev(hes[hes.size()-1]); hes[hes.size()-1]->setNext(hes[0]); //other settings f f->setOuterHalfEdge(hes[0]); f->setColor(c); f->setFlag(flag); if (updateNormalOnInsertion) f->updateArea(); return f->id(); } CG3_INLINE int DcelBuilder::addFace( const Point3d& p1, const Point3d& p2, const Point3d& p3, const Color& c, int flag) { unsigned int vid1, vid2, vid3; //setting vids std::map<cg3::Point3d, unsigned int>::iterator it; it = mapVertices.find(p1); if (it == mapVertices.end()) vid1 = addVertex(p1); else vid1 = it->second; it = mapVertices.find(p2); if (it == mapVertices.end()) vid2 = addVertex(p2); else vid2 = it->second; it = mapVertices.find(p3); if (it == mapVertices.end()) vid3 = addVertex(p3); else vid3 = it->second; return addFace(vid1, vid2, vid3, c, flag); } CG3_INLINE int DcelBuilder::addFace( const Point3d& p1, const Point3d& p2, const Point3d& p3, const Point3d& p4, const Color& c, int flag) { unsigned int vid1, vid2, vid3, vid4; //setting vids std::map<cg3::Point3d, unsigned int>::iterator it; it = mapVertices.find(p1); if (it == mapVertices.end()) vid1 = addVertex(p1); else vid1 = it->second; it = mapVertices.find(p2); if (it == mapVertices.end()) vid2 = addVertex(p2); else vid2 = it->second; it = mapVertices.find(p3); if (it == mapVertices.end()) vid3 = addVertex(p3); else vid3 = it->second; it = mapVertices.find(p4); if (it == mapVertices.end()) vid4 = addVertex(p4); else vid4 = it->second; return addFace(vid1, vid2, vid3, vid4, c, flag); } CG3_INLINE int DcelBuilder::addFace(const std::vector<Point3d>& ps, const Color& c, int flag) { std::vector<uint> vids(ps.size()); std::map<cg3::Point3d, unsigned int>::iterator it; for (uint i = 0; i < ps.size(); i++){ it = mapVertices.find(ps[i]); if (it == mapVertices.end()) vids[i] = addVertex(ps[i]); else vids[i] = it->second; } return addFace(vids, c, flag); } CG3_INLINE void DcelBuilder::finalize() { d.updateBoundingBox(); if (updateNormalOnInsertion) d.updateVertexNormals(); } CG3_INLINE void DcelBuilder::setUpdateNormalOnInsertion(bool b) { updateNormalOnInsertion = b; } }
cg3hci/cg3lib
cg3/meshes/dcel/dcel_builder.cpp
C++
gpl-3.0
6,632
/******************************************************************************* * MASH 3D simulator * * Copyright (c) 2014 Idiap Research Institute, http://www.idiap.ch/ * Written by Philip Abbet <philip.abbet@idiap.ch> * * This file is part of mash-simulator. * * mash-simulator is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * mash-simulator is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with mash-simulator. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ #include <teachers/TeacherEatAllTargets.h> #include <Athena-Entities/Transforms.h> #include <Athena-Graphics/Debug/Axes.h> #include <Athena-Entities/ComponentsManager.h> using namespace Athena::Math; using namespace Athena::Entities; using namespace Athena::Graphics; using namespace Athena::Graphics::Visual; using namespace Athena::Utils; using namespace std; static Debug::Axes* pAxes = 0; /***************************** CONSTRUCTION / DESTRUCTION ******************************/ TeacherEatAllTargets::TeacherEatAllTargets(Map* pMap, Athena::Graphics::Visual::Camera* pCamera) : Teacher(pMap, pCamera), current_target(-1) { } TeacherEatAllTargets::~TeacherEatAllTargets() { } /************************************** METHODS ****************************************/ tAction TeacherEatAllTargets::computeNextAction() { if ((current_target == -1) && !m_detected_targets.empty()) { float min_distance = 0.0f; for (int i = 0; i < m_detected_targets.size(); ++i) { tPoint target = m_detected_targets[i]; if (isCellVisible(target.x, target.y)) { float distance = getDistanceToTarget(target); if ((current_target == -1) || (distance < min_distance)) { min_distance = distance; current_target = i; } } } } if (current_target >= 0) { Degree angle = getAngleToTarget(m_detected_targets[current_target]); if (angle.valueDegrees() >= 3.0f) return ACTION_TURN_RIGHT; else if (angle.valueDegrees() <= -3.0f) return ACTION_TURN_LEFT; else return ACTION_GO_FORWARD; } return ACTION_TURN_LEFT; } Mash::tActionsList TeacherEatAllTargets::notRecommendedActions() { Mash::tActionsList actions; if (m_nextAction == ACTIONS_COUNT) nextAction(); if (current_target >= 0) { if (m_nextAction == ACTION_GO_FORWARD) { actions.push_back(ACTION_GO_BACKWARD); } else if (m_nextAction == ACTION_TURN_RIGHT) { actions.push_back(ACTION_GO_BACKWARD); actions.push_back(ACTION_TURN_LEFT); } else if (m_nextAction == ACTION_TURN_LEFT) { actions.push_back(ACTION_GO_BACKWARD); actions.push_back(ACTION_TURN_RIGHT); } } else { actions.push_back(ACTION_GO_BACKWARD); } return actions; } void TeacherEatAllTargets::onTargetReached(tTarget* pTarget) { if (current_target >= 0) m_detected_targets.erase(m_detected_targets.begin() + current_target); current_target = -1; for (unsigned int i = 0; i < m_pMap->width * m_pMap->height; ++i) { if ((m_grid[i] != CELL_UNKNOWN) && (m_grid[i] != m_pMap->grid[i].type)) m_grid[i] = CELL_UNKNOWN; } }
idiap/mash-simulator
src/teachers/TeacherEatAllTargets.cpp
C++
gpl-3.0
3,863
require_relative 'concerns/exportable' class Location < ActiveRecord::Base has_many :posts include Exportable add_export prefix: 'location', export_fields: %i[ id instagram_id name ], export_methods: %i[ long_lat ] def long_lat [ lng, lat ] end end
ZubKonst/pirozhki
app/models/location.rb
Ruby
gpl-3.0
294
package net.foxopen.fox.logging; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FoxLogger { private static final Logger mLogger = LoggerFactory.getLogger("FoxLogger"); public static Logger getLogger() { return mLogger; } private FoxLogger() { } }
Fivium/FOXopen
src/main/java/net/foxopen/fox/logging/FoxLogger.java
Java
gpl-3.0
288
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Qry_relation_group_role extends Qry_root { public function __construct($Obj=FALSE) { //Import $this->load->model(CONSTANT_PATH.'con_relation_group_role'); //End parent::__construct($Obj); } public function delete_by_pk_group($pk_group, $log=FALSE) { //Message $message = "Multiple Delete by PK Group from table ".$this->con->table; //Execute $this->db->where($this->con->pk_group, $pk_group); return $this->delete_query($this->con->table, $message, $log); } public function pk_group($value = TRUE,$method = FALSE, $option=FALSE) { return array($this->con->alias.".".$this->con->pk_group, $value, $method, $option); } } /* End of file */
tvalentius/MarsColony
MarsColony/application/models/query/qry_relation_group_role.php
PHP
gpl-3.0
755
package com.sevixoo.android3dge; import android.opengl.GLES30; import android.util.Log; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; /** * Created by seweryn on 24.07.2017. */ public class GLContext { private static GLContext instance; public static GLContext get()throws RuntimeException{ if(instance == null){ throw new RuntimeException( ); } return instance; } public static void initialize() { Log.i("GL_VERSION", GLES30.glGetString(GLES30.GL_VERSION) ); Log.i("GL_EXTENSIONS", GLES30.glGetString(GLES30.GL_EXTENSIONS) ); instance = new GLContext(); } public static void destroy() { instance = null; } private GLContext(){ } public int createVertexShader(String source){ int shader = GLES30.glCreateShader(GLES30.GL_VERTEX_SHADER); GLES30.glShaderSource(shader, source); return shader; } public int createFragmentShader(String source){ int shader = GLES30.glCreateShader(GLES30.GL_FRAGMENT_SHADER); GLES30.glShaderSource(shader, source); return shader; } public String compileShader(int shader) { GLES30.glCompileShader(shader); IntBuffer status = IntBuffer.allocate(1); GLES30.glGetShaderiv( shader, GLES30.GL_COMPILE_STATUS , status ); int errorCode = status.get(); if(errorCode != GLES30.GL_TRUE){ return GLES30.glGetShaderInfoLog( shader ); } return null; } public void deleteShader(int shader){ GLES30.glDeleteShader(shader); } public void useProgram(int program) { GLES30.glUseProgram(program); } public void bindAttribLocation(int program, int attributeName, String name) { GLES30.glEnableVertexAttribArray(attributeName); GLES30.glBindAttribLocation(program,attributeName,name); GLES30.glDisableVertexAttribArray(attributeName); } public int createProgram(int vertexShader, int fragmentShader) { int program = GLES30.glCreateProgram(); GLES30.glAttachShader(program, vertexShader); GLES30.glAttachShader(program, fragmentShader); return program; } public String compileProgram(int program){ GLES30.glLinkProgram(program); IntBuffer status = IntBuffer.allocate(1); GLES30.glGetProgramiv( program, GLES30.GL_LINK_STATUS , status ); int errorCode = status.get(); if(errorCode == GLES30.GL_FALSE){ return GLES30.glGetProgramInfoLog( program ); } GLES30.glValidateProgram(program); status = IntBuffer.allocate(1); GLES30.glGetProgramiv( program, GLES30.GL_VALIDATE_STATUS , status ); errorCode = status.get(); if(errorCode == GLES30.GL_FALSE){ return GLES30.glGetProgramInfoLog( program ); } return null; } public void viewport(int x, int y, int width, int height) { GLES30.glViewport(x, y, width, height); } public void clearColor(float r, float g, float b, int a) { GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT|GLES30.GL_DEPTH_BUFFER_BIT); GLES30.glClearColor(r, g, b, a); GLES30.glEnable(GLES30.GL_DEPTH_TEST); } public int genVertexArray() { IntBuffer intBuffer = IntBuffer.allocate(1); GLES30.glGenVertexArrays( 1, intBuffer ); return intBuffer.get(); } public void bindVertexArray(int vao) { GLES30.glBindVertexArray(vao); } public int genBuffer() { IntBuffer intBuffer = IntBuffer.allocate(1); GLES30.glGenBuffers( 1, intBuffer); return intBuffer.get(); } public void bindArrayBuffer(int vbo) { GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER,vbo); } public void bindElementsArrayBuffer(int vbo) { GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER,vbo); } public IntBuffer arrayBufferDataWrite(int[] data) { IntBuffer buffer = IntBuffer.allocate(data.length); buffer.put(data); buffer.flip(); GLES30.glBufferData(GLES30.GL_ARRAY_BUFFER, data.length , buffer, GLES30.GL_STATIC_DRAW); return buffer; } public void elementsArrayBufferDataWrite(short[] data) { ShortBuffer buffer = ByteBuffer.allocateDirect ( data.length * 2 ).order ( ByteOrder.nativeOrder() ).asShortBuffer(); buffer.put ( data ).position ( 0 ); GLES30.glBufferData(GLES30.GL_ELEMENT_ARRAY_BUFFER, data.length * 2 , buffer, GLES30.GL_STATIC_DRAW); } public void arrayBufferDataWrite(float[] data) { FloatBuffer buffer = ByteBuffer.allocateDirect ( data.length * 4 ) .order ( ByteOrder.nativeOrder() ).asFloatBuffer(); buffer.put ( data ).position ( 0 ); GLES30.glBufferData(GLES30.GL_ARRAY_BUFFER, data.length * 4 , buffer, GLES30.GL_STATIC_DRAW); } public void vertexAttribPointerF(int attributeNumber, int dataSize) { GLES30.glVertexAttribPointer(attributeNumber,dataSize,GLES30.GL_FLOAT,false,0,0); } public void vertexAttribPointerU(int attributeNumber, int dataSize) { GLES30.glVertexAttribPointer(attributeNumber,dataSize,GLES30.GL_UNSIGNED_INT,false,0,0); } public void drawTriangleElements( int verticesCount ) { GLES30.glDrawElements(GLES30.GL_TRIANGLES, verticesCount, GLES30.GL_UNSIGNED_SHORT, 0); } public void drawPointsElements( int verticesCount ) { GLES30.glDrawElements(GLES30.GL_POINTS, verticesCount, GLES30.GL_UNSIGNED_SHORT, 0); } public void drawLinesElements( int verticesCount ) { GLES30.glDrawElements(GLES30.GL_LINE_STRIP, verticesCount, GLES30.GL_UNSIGNED_SHORT, 0); } public void enableVertexAttribArray(int index) { GLES30.glEnableVertexAttribArray(index); } public void disableVertexAttribArray(int index) { GLES30.glDisableVertexAttribArray(index); } public void uniform4f(int handle, float x, float y, float z, float w) { GLES30.glUniform4f(handle , x, y, z, w); } public void uniformMatrix4fv(int handle, float[] matrix) { FloatBuffer buffer = ByteBuffer.allocateDirect ( matrix.length * 4 ).order ( ByteOrder.nativeOrder() ).asFloatBuffer(); buffer.put ( matrix ).position ( 0 ); GLES30.glUniformMatrix4fv(handle, 1, false, buffer); } public int getUniformLocation(int program, String name) { return GLES30.glGetUniformLocation (program, name); } public void uniform1f(int handle, float value) { GLES30.glUniform1f(handle , value); } public void lineWidth(float width){ GLES30.glLineWidth(width); } public void uniform1i(int handle, int value) { GLES30.glUniform1i(handle,value); } public void activeTexture2D( int textureNum , int textureId ){ int glTexture = 0; switch (textureNum){ case 0: glTexture = GLES30.GL_TEXTURE0;break; case 1: glTexture = GLES30.GL_TEXTURE1;break; case 2: glTexture = GLES30.GL_TEXTURE2;break; case 3: glTexture = GLES30.GL_TEXTURE3;break; case 4: glTexture = GLES30.GL_TEXTURE4;break; case 5: glTexture = GLES30.GL_TEXTURE5;break; case 6: glTexture = GLES30.GL_TEXTURE6;break; case 7: glTexture = GLES30.GL_TEXTURE7;break; case 8: glTexture = GLES30.GL_TEXTURE8;break; } GLES30.glActiveTexture ( glTexture ); GLES30.glBindTexture ( GLES30.GL_TEXTURE_2D, textureId ); } public static final int TEXTURE_WRAP_REPEAT = 1; public static final int TEXTURE_WRAP_CLAMP_TO_EDGE = 2; public static final int TEXTURE_WRAP_MIRRORED_REPEAT = 3; private int wrapType(int type){ switch (type){ case TEXTURE_WRAP_REPEAT:return GLES30.GL_REPEAT; case TEXTURE_WRAP_CLAMP_TO_EDGE:return GLES30.GL_CLAMP_TO_EDGE; case TEXTURE_WRAP_MIRRORED_REPEAT:return GLES30.GL_MIRRORED_REPEAT; } return 0; } public void textParameterWrap_S( int type ){ GLES30.glTexParameteri ( GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, wrapType(type) ); } public void textParameterWrap_T( int type ){ GLES30.glTexParameteri ( GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, wrapType(type) ); } }
Sevixoo/3DGE
3DGE-android/src/main/java/com/sevixoo/android3dge/GLContext.java
Java
gpl-3.0
8,496
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using ECCentral.BizEntity; using ECCentral.BizEntity.IM; using ECCentral.Service.IBizInteract; using ECCentral.Service.IM.IDataAccess; using ECCentral.Service.Utility; namespace ECCentral.Service.IM.BizProcessor { [VersionExport(typeof(ProductResourceProcessor))] public class ProductResourceProcessor { private readonly IProductResourceDA _productResourceDA = ObjectFactory<IProductResourceDA>.Instance; public virtual bool IsExistFileName(string fileName) { if (string.IsNullOrEmpty(fileName)) { throw new BizException(ResouceManager.GetMessageString("IM.ProductResource", "FileNameIsNull")); } var result = _productResourceDA.GetProductGroupInfoImageSysNoByFileName(fileName); return result > 0; } /// <summary> /// 删除商品图片 /// </summary> /// <param name="entity"></param> public virtual void DeleteProductResource(ProductResourceForNewegg entity) { CheckProductResourceProcessor.CheckProductResource(entity); CheckProductResourceProcessor.CheckProductResourceSysNo(entity.Resource.ResourceSysNo); var productCommonInfoSysNo = entity.ProductCommonInfoSysNo; CheckProductResourceProcessor.CheckProductCommonInfoSysNo(productCommonInfoSysNo); if (entity.Resource.ResourceSysNo != null) _productResourceDA.DeleteProductResource(entity.Resource.ResourceSysNo.Value, productCommonInfoSysNo); } /// <summary> /// 修改商品图片 /// </summary> /// <param name="entity"></param> public virtual void ModifyProductResources(ProductResourceForNewegg entity) { CheckProductResourceProcessor.CheckProductResource(entity); CheckProductResourceProcessor.CheckProductResourceSysNo(entity.Resource.ResourceSysNo); var productCommonInfoSysNo = entity.ProductCommonInfoSysNo; CheckProductResourceProcessor.CheckProductCommonInfoSysNo(productCommonInfoSysNo); entity.Resource.ResourceURL = entity.Resource.ResourceURL.ToLower().Contains("http") ? Path.GetFileName(entity.Resource.ResourceURL) : entity.Resource.ResourceURL; _productResourceDA.UpdateProductResource(entity, productCommonInfoSysNo); } /// <summary> /// 创建商品图片 /// </summary> /// <param name="entity"></param> public virtual List<ProductResourceForNewegg> CreateProductResource(List<ProductResourceForNewegg> entity) { if (entity == null || entity.Count == 0) return entity; foreach (var item in entity) { /* if (ImageUtility.IsImages(item.Resource.TemporaryName)) { CreateImages(item.Resource.TemporaryName, item.Resource.ResourceURL, item.IsNeedWatermark); } else if (ImageUtility.IsFLV(item.Resource.TemporaryName)) { FlvOp.Save(item.Resource.TemporaryName, item.Resource.ResourceURL); } else { ImageOPFor360.Save(item.Resource.TemporaryName, item.Resource.ResourceURL); } */ CheckProductResourceProcessor.CheckProductResource(item); var productCommonInfoSysNo = item.ProductCommonInfoSysNo ; CheckProductResourceProcessor.CheckProductCommonInfoSysNo(productCommonInfoSysNo); var result = _productResourceDA.GetProductGroupInfoImageSysNoByFileName(item.Resource.ResourceURL); if (result <= 0) { _productResourceDA.InsertProductResource(item, productCommonInfoSysNo); } else { item.Resource.ResourceSysNo = result; } } return entity; } /// <summary> /// 生成套图 /// </summary> /// <param name="fileIdentity"></param> /// <param name="fileName"></param> private void CreateImages(string fileIdentity, string fileName, bool isNeedWatermark) { if (ImageUtility.IsImages(fileIdentity)) { ImageOp.OriginalImageSave(fileIdentity, fileName); ImageOp.CreateImagesByNewegg(fileIdentity, fileName, isNeedWatermark); } } /// <summary> /// 业务逻辑判断 /// </summary> private static class CheckProductResourceProcessor { /// <summary> /// 检查图片资源实体 /// </summary> /// <param name="entity"></param> public static void CheckProductResource(ProductResourceForNewegg entity) { if (entity == null) { throw new BizException(ResouceManager.GetMessageString("IM.ProductResource", "ProductResourceInvalid")); } if (entity.Resource == null) { throw new BizException(ResouceManager.GetMessageString("IM.ProductResource", "ProductResourceIsNull")); } } /// <summary> /// 检查图片资源编号 /// </summary> /// <param name="resourceSysNo"></param> public static void CheckProductResourceSysNo(int? resourceSysNo) { if (resourceSysNo == null || resourceSysNo.Value <= 0) { throw new BizException(ResouceManager.GetMessageString("IM.ProductResource", "ResourceSysNoIsNull")); } } /// <summary> /// 检查商品productCommonInfoSysNo /// </summary> /// <param name="productCommonInfoSysNo"></param> public static void CheckProductCommonInfoSysNo(int productCommonInfoSysNo) { if (productCommonInfoSysNo <= 0) { throw new BizException(ResouceManager.GetMessageString("IM.ProductResource", "ProductCommonInfoSysNoIsNull")); } } public static int CheckFileName(string fileName) { if (string.IsNullOrWhiteSpace(fileName)) { throw new BizException(ResouceManager.GetMessageString("IM.ProductResource", "FileNameIsNull")); } if(fileName.ToLower().Contains("http")) fileName = Path.GetFileName(fileName); var re = new Regex(@"^([^\.\-]+)(\-(([1-9][0-9])|(0[1-9])))?\..+?$", RegexOptions.IgnoreCase); if (fileName != null) { var match = re.Match(fileName); //Check上传文件名是否合法 if (match.Success) { string commonSKUNumber = match.Groups[1].Value; var productCommonInfoDA = ObjectFactory<IProductCommonInfoDA>.Instance; var result = productCommonInfoDA.GetProductCommonInfoByCommonInfoSkuNumber(commonSKUNumber); if (result < 0) { throw new BizException(ResouceManager.GetMessageString("IM.ProductResource", "IsExistsFileName")); } return result; } } throw new BizException(ResouceManager.GetMessageString("IM.ProductResource", "FileNameInvalid")); } } } /// <summary> /// 图片操作 /// </summary> internal class ImageOp { private enum Graph { //泰隆优选项目新增图片规格 //32*32 //P32, //50*50 //P50, //60*60 //90*90 //P90, //100*100 //P100, //120*120 //140*140 //P140, //150*150 //P150, //160*160 //200*200 //218*218 //P218, //450*450 //830*830 //P830, //泰隆优选项目ECC使用的图片尺寸: //125*125 //P125, ////144*144 //P144, ////泰隆优选项目SellerPortal使用的图片尺寸: ////80*80 //P80, ////泰隆优选项目手机端使用的图片尺寸: ////40*40 //P40, ////45*45 //P45, ////68*68 //P68, ////112*112 //P112, ////155*155 //P155, ////176*176 //P176, ////192*192 //P192, ////216*216 //P216, ////220*220 //P220, ////240*240 //P240, ////246*246 //P246, ////270*270 //P270, ////296*296 //P296, ////330*330 //P330, ////350*350 //P350, ////400*400 //P400, ////480*480 //P480, ////540*540 //P540, //800*800 P60, P120, P160, P200, P240, P450, P800 } private readonly static Dictionary<Graph, ImageSize> ImageList = new Dictionary<Graph, ImageSize>(); private static readonly string[] ImageFileExtensionName = new[] { ".JPG" };//文件后缀名 /// <summary> /// 保存文件标题 /// </summary> //private readonly static string SaveTitle = AppSettingManager.GetSetting("IM", "ProductImage_UploadFilePathTitle"); private readonly static string UploadURL = AppSettingManager.GetSetting("IM", "ProductImage_DFISUploadURL"); private readonly static string FileGroup = AppSettingManager.GetSetting("IM", "ProductImage_DFISFileGroup"); private static readonly string UserName; /// <summary> /// 保存文件地址 /// </summary> private readonly static string[] LocalPathList = AppSettingManager.GetSetting("IM", "ProductImage_UploadFilePath").Split(Char.Parse("|")); private class ImageSize { public Double Height { get; set; } public Double Width { get; set; } } static ImageOp() { //泰隆优选项目新增图片规格 //32*32 //50*50 //60*60 //90*90 //100*100 //120*120 //140*140 //150*150 //200*200 //218*218 //450*450 //830*830 //ImageList.Add(Graph.P32, new ImageSize { Height = 32, Width = 32 }); //ImageList.Add(Graph.P50, new ImageSize { Height = 50, Width = 50 }); //ImageList.Add(Graph.P60, new ImageSize { Height = 60, Width = 60 }); //ImageList.Add(Graph.P90, new ImageSize { Height = 90, Width = 90 }); //ImageList.Add(Graph.P100, new ImageSize { Height = 100, Width = 100 }); //ImageList.Add(Graph.P120, new ImageSize { Height = 120, Width = 120 }); //ImageList.Add(Graph.P140, new ImageSize { Height = 140, Width = 140 }); //ImageList.Add(Graph.P150, new ImageSize { Height = 150, Width = 150 }); //ImageList.Add(Graph.P200, new ImageSize { Height = 200, Width = 200 }); //ImageList.Add(Graph.P218, new ImageSize { Height = 218, Width = 218 }); //ImageList.Add(Graph.P450, new ImageSize { Height = 450, Width = 450 }); //ImageList.Add(Graph.P830, new ImageSize { Height = 830, Width = 830 }); //泰隆优选项目ECC使用的图片尺寸: //125*125 //144*144 //ImageList.Add(Graph.P125, new ImageSize { Height = 125, Width = 125 }); //ImageList.Add(Graph.P144, new ImageSize { Height = 144, Width = 144 }); ////泰隆优选项目SellerPortal使用的图片尺寸: ////80*80 //ImageList.Add(Graph.P80, new ImageSize { Height = 80, Width = 80 }); ////泰隆优选项目手机端使用的图片尺寸: ////40*40 ////45*45 ////68*68 ////112*112 ////155*155 ////176*176 ////192*192 ////216*216 ////220*220 ////240*240 ////246*246 ////270*270 ////296*296 ////330*330 ////350*350 ////400*400 ////480*480 ////540*540 ////800*800 //ImageList.Add(Graph.P40, new ImageSize { Height = 40, Width = 40 }); //ImageList.Add(Graph.P45, new ImageSize { Height = 45, Width = 45 }); //ImageList.Add(Graph.P68, new ImageSize { Height = 68, Width = 68 }); //ImageList.Add(Graph.P112, new ImageSize { Height = 112, Width = 112 }); //ImageList.Add(Graph.P155, new ImageSize { Height = 155, Width = 155 }); //ImageList.Add(Graph.P176, new ImageSize { Height = 176, Width = 176 }); //ImageList.Add(Graph.P192, new ImageSize { Height = 192, Width = 192 }); //ImageList.Add(Graph.P216, new ImageSize { Height = 216, Width = 216 }); //ImageList.Add(Graph.P220, new ImageSize { Height = 220, Width = 220 }); //ImageList.Add(Graph.P240, new ImageSize { Height = 240, Width = 240 }); //ImageList.Add(Graph.P246, new ImageSize { Height = 246, Width = 246 }); //ImageList.Add(Graph.P270, new ImageSize { Height = 270, Width = 270 }); //ImageList.Add(Graph.P296, new ImageSize { Height = 296, Width = 296 }); //ImageList.Add(Graph.P330, new ImageSize { Height = 330, Width = 330 }); //ImageList.Add(Graph.P350, new ImageSize { Height = 350, Width = 350 }); //ImageList.Add(Graph.P400, new ImageSize { Height = 400, Width = 400 }); //ImageList.Add(Graph.P480, new ImageSize { Height = 480, Width = 480 }); //ImageList.Add(Graph.P540, new ImageSize { Height = 540, Width = 540 }); //ImageList.Add(Graph.P800, new ImageSize { Height = 800, Width = 800 }); ImageList.Add(Graph.P60, new ImageSize { Height = 60, Width = 60 }); ImageList.Add(Graph.P120, new ImageSize { Height = 120, Width = 120 }); ImageList.Add(Graph.P160, new ImageSize { Height = 160, Width = 160 }); ImageList.Add(Graph.P200, new ImageSize { Height = 200, Width = 200 }); ImageList.Add(Graph.P240, new ImageSize { Height = 240, Width = 240 }); ImageList.Add(Graph.P450, new ImageSize { Height = 450, Width = 450 }); ImageList.Add(Graph.P800, new ImageSize { Height = 800, Width = 800 }); UserName = ObjectFactory<ICommonBizInteract>.Instance.GetUserFullName(ServiceContext.Current.UserSysNo.ToString(), true); } public static void CreateImagesByNewegg(string fileIdentity, string newFileName, bool isNeedWatermark) { if (ImageList.Count == 0) return; var result = FileUploadManager.FileExists(fileIdentity); if (!result) return; var bytes = FileUploadManager.GetFileData(fileIdentity); ImageList.ForEach(v => ThreadPool.QueueUserWorkItem( delegate { var imageHelp = new ImageUtility { FileName = newFileName, MidFilepath = v.Key.ToString() }; imageHelp.Upload += Upload; imageHelp.ZoomAuto(bytes, (int)v.Value.Width, (int)v.Value.Height, isNeedWatermark); })); } /// <summary> /// 生成一组套图 /// </summary> /// <param name="fileIdentity"></param> /// <param name="newFileName"></param> public static void CreateImages(string fileIdentity, string newFileName) { if (ImageList.Count == 0) return; var result = FileUploadManager.FileExists(fileIdentity); if (!result) return; var bytes = FileUploadManager.GetFileData(fileIdentity); ImageList.ForEach(v => ThreadPool.QueueUserWorkItem( delegate { var imgageHelp = new ImageUtility(); imgageHelp.ZoomAuto(bytes, (int)v.Value.Width, (int)v.Value.Height, true); })); } /// <summary> /// 生成标准图片 /// </summary> /// <param name="fileIdentity"></param> /// <param name="newFileName"></param> public static void CreateStandardImages(string fileIdentity, string newFileName) { if (ImageList.Count == 0) return; var result = FileUploadManager.FileExists(fileIdentity); if (!result) return; var filePath = FileUploadManager.GetFilePhysicalFullPath(fileIdentity); Image uploadImage = Image.FromFile(filePath); //判断是否为标准图片 if (!ImageUtility.CheckImagePixels(uploadImage)) { uploadImage.Dispose();//后面的zoomauto会删除的,资源要提前释放 //重命名文件 var bytes = FileUploadManager.GetFileData(fileIdentity); var imageHelp = new ImageUtility {SavePath = filePath}; imageHelp.ZoomAuto(bytes, 640, 480); } } /// <summary> /// 删除一组套图 /// </summary> /// <param name="fileIdentity"></param> public static void DeleteImages(string fileIdentity) { if (ImageList.Count == 0) return; var result = FileUploadManager.FileExists(fileIdentity); if (result) return; ImageList.ForEach(v => { var folderPath = Path.Combine(FileUploadManager.BaseFolder, v.Key.ToString()); if (!Directory.Exists(folderPath)) { return; } var filePath = Path.Combine(folderPath, fileIdentity); if (File.Exists(filePath)) { ThreadPool.QueueUserWorkItem(delegate { File.Delete(filePath); }); } }); } /// <summary> /// 原始图片保存 /// </summary> /// <param name="fileIdentity"></param> /// <param name="destFileName"></param> public static void OriginalImageSave(string fileIdentity, string destFileName) { if (string.IsNullOrWhiteSpace(fileIdentity) || string.IsNullOrWhiteSpace(destFileName)) return; var result = FileUploadManager.FileExists(fileIdentity); if (result) { var filePath = FileUploadManager.GetFilePhysicalFullPath(fileIdentity); CreateStandardImages(fileIdentity, destFileName); var fileExtensionName = FileUploadManager.GetFileExtensionName(fileIdentity); var savePath = FilePathHelp.GetFileSavePath(fileExtensionName.ToLower()); OriginalImageSave(fileIdentity, destFileName, savePath); } } public static void OriginalImageSaveByDFIS(string fileIdentity, string destFileName) { if (string.IsNullOrWhiteSpace(fileIdentity) || string.IsNullOrWhiteSpace(destFileName)) return; var result = FileUploadManager.FileExists(fileIdentity); if (result) { var filePath = FileUploadManager.GetFilePhysicalFullPath(fileIdentity); CreateStandardImages(fileIdentity, destFileName); HttpUploader.UploadFile(UploadURL, FileGroup, "Original", filePath, destFileName, "", UserName, UploadMethod.Update); } } /// <summary> /// 文件保存 /// </summary> /// <param name="fileIdentity"></param> /// <param name="destFileName"></param> /// <param name="savePath"></param> private static void OriginalImageSave(string fileIdentity, string destFileName, string savePath) { if (string.IsNullOrWhiteSpace(fileIdentity) || string.IsNullOrWhiteSpace(destFileName) || string.IsNullOrWhiteSpace(savePath)) return; var result = FileUploadManager.FileExists(fileIdentity); if (result) { var fileExtensionName = FileUploadManager.GetFileExtensionName(fileIdentity).ToUpper(); var filePath = FileUploadManager.GetFilePhysicalFullPath(fileIdentity); if (ImageFileExtensionName.Contains(fileExtensionName)) { if (destFileName.IndexOf(".") == -1) { destFileName = destFileName + "." + fileExtensionName; } savePath += FilePathHelp.GetSubFolderName(destFileName); foreach (string localPath in LocalPathList) { string path = localPath + savePath.Replace("/", "\\"); //判断文件夹是否存在 if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } destFileName = path + destFileName; //FLV文件重命名操作,不进行DFIS处理 File.Copy(filePath, destFileName, true); } } } } private static void Upload(object sender, UploadEventArgs args) { args.SaveFileName = GetSaveFilePath(args.FileName, FileGroup, args.MidFilepath); //var filePath = GetSaveFilePath(args.FileName, FileGroup, args.MidFilepath); //if (!string.IsNullOrWhiteSpace(filePath)) // args.UploadImage.Save(filePath); } private static void UploadByDFIS(object sender, UploadEventArgs args) { using (var ms = new MemoryStream()) { args.UploadImage.Save(ms, ImageFormat.Jpeg); ms.Seek(0, SeekOrigin.Begin); HttpUploader.UploadFile(ms, args.FileName, UploadURL, FileGroup, args.MidFilepath, "", UserName, UploadMethod.Update); } } /// <summary> /// 得到图片保存路径 /// </summary> /// <param name="fileName"></param> /// <param name="fileGroup"></param> /// <param name="midFilepath"></param> /// <returns></returns> private static string GetSaveFilePath(string fileName, string fileGroup, string midFilepath) { if (string.IsNullOrWhiteSpace(fileName) || string.IsNullOrWhiteSpace(fileGroup) || string.IsNullOrWhiteSpace(midFilepath)) return ""; if (LocalPathList == null || LocalPathList.Count() == 0) return ""; var diretory = FilePathHelp.GetSubFolderName(fileName).Replace("/", "\\"); var saveDirectory = String.Format(@"{0}{1}\{2}\{3}", LocalPathList[0], fileGroup, midFilepath, diretory); if (!Directory.Exists(saveDirectory)) { Directory.CreateDirectory(saveDirectory); } var filePath = saveDirectory + fileName; return filePath; } } /// <summary> /// 视频处理 /// </summary> internal class FlvOp { private static readonly string[] FLVFileExtensionName = new[] { ".FLV" };//文件后缀名 /// <summary> /// 保存文件地址 /// </summary> private readonly static string[] LocalPathList = AppSettingManager.GetSetting("IM", "ProductImage_UploadFilePath").Split(Char.Parse("|")); /// <summary> /// 保存文件标题 /// </summary> // private readonly static string SaveTitle = AppSettingManager.GetSetting("IM", "ProductImage_UploadFilePathTitle"); /// <summary> /// 保存视频文件 /// </summary> /// <param name="fileIdentity"></param> /// <param name="destFileName"></param> public static void Save(string fileIdentity, string destFileName) { if (string.IsNullOrWhiteSpace(fileIdentity) || string.IsNullOrWhiteSpace(destFileName)) return; var result = FileUploadManager.FileExists(fileIdentity); if (result) { var fileExtensionName = FileUploadManager.GetFileExtensionName(fileIdentity).ToUpper(); var filePath = FileUploadManager.GetFilePhysicalFullPath(fileIdentity); if (FLVFileExtensionName.Contains(fileExtensionName)) { if (destFileName.IndexOf(".") == -1) { destFileName = destFileName + "." + fileExtensionName; } var savePath = FilePathHelp.GetFileSavePath(fileExtensionName.ToLower()); savePath += FilePathHelp.GetSubFolderName(destFileName); foreach (string localPath in LocalPathList) { string path = localPath + savePath.Replace("/", "\\"); //判断文件夹是否存在 if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } destFileName = path + destFileName; //FLV文件重命名操作,不进行DFIS处理 File.Copy(filePath, destFileName, true); } } } } } /// <summary> /// 360图片 /// </summary> internal class ImageOPFor360 { /// <summary> /// 保存文件地址 /// </summary> private readonly static string SaveTitle = AppSettingManager.GetSetting("IM", "ProductImage_UploadFilePathTitle"); private readonly static string UploadURL = AppSettingManager.GetSetting("IM", "ProductImage_DFISUploadURL"); private static readonly string[] Image360FileExtensionName = new[] { ".SWF" };//文件后缀名 /// <summary> /// 保存文件地址 /// </summary> private readonly static string[] LocalPathList = AppSettingManager.GetSetting("IM", "ProductImage_UploadFilePath").Split(Char.Parse("|")); /// <summary> /// 支持多服务器保存 /// </summary> /// <param name="filePath"></param> /// <param name="newFileName"></param> /// <param name="fileSize"></param> /// <param name="userName"></param> public static void Save(string filePath, string newFileName, string fileSize, string userName) { //重命名文件 HttpUploader.UploadFile(UploadURL, SaveTitle, fileSize, filePath, newFileName, "", userName, UploadMethod.Update); } /// <summary> /// 保存视频文件 /// </summary> /// <param name="fileIdentity"></param> /// <param name="destFileName"></param> public static void Save(string fileIdentity, string destFileName) { if (string.IsNullOrWhiteSpace(fileIdentity) || string.IsNullOrWhiteSpace(destFileName)) return; var result = FileUploadManager.FileExists(fileIdentity); if (result) { var fileExtensionName = FileUploadManager.GetFileExtensionName(fileIdentity).ToUpper(); var filePath = FileUploadManager.GetFilePhysicalFullPath(fileIdentity); if (Image360FileExtensionName.Contains(fileExtensionName)) { if (destFileName.IndexOf(".") == -1) { destFileName = destFileName + "." + fileExtensionName; } var savePath = FilePathHelp.GetFileSavePath(fileExtensionName.ToLower()); savePath += FilePathHelp.GetSubFolderName(destFileName); foreach (string localPath in LocalPathList) { string path = localPath + savePath.Replace("/", "\\"); //判断文件夹是否存在 if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } destFileName = path + destFileName; //FLV文件重命名操作,不进行DFIS处理 File.Copy(filePath, destFileName, true); } } } } } }
ZeroOne71/ql
02_ECCentral/03_Service/02_IM/ECCentral.Service.IM.BizProcessor/ProductResourceProcessor.cs
C#
gpl-3.0
29,976
<?php namespace php\controls; class ControlDispatcher { private $control; private $action; public function __construct($control, $action) { $this->control = $control; $this->action = $action; } public function dispatch() { $klasseNaam = BASE_NAMESPACE.'controls\\'.ucFirst($this->control).'Controller'; if(!class_exists($klasseNaam)) { throw new \php\error\FrameworkException("controller $klasseNaam bestaat niet!"); } if(!is_subclass_of($klasseNaam,'\php\\controls\\AbstractController')) { throw new \php\error\FrameworkException("klas $klasseNaam implementeert overerft niet van framework AbstractController. dat is verplicht"); } $controller = new $klasseNaam($this->control,$this->action); $controller->execute(); } }
IPeev1/Training-website
app/php/controls/ControlDispatcher.php
PHP
gpl-3.0
815
<?php /** * @author Reverze <hawkmedia24@gmail.com> */ namespace Yumi\Bundler\View\Table; use Yumi\Bundler\View\Table\Exception\TableException; use Yumi\Bundler\View\ViewElement; class Table extends ViewElement { /** * @var \Yumi\Bundler\View\Table\Column[] */ private $columnContainer = array(); /** * Total amount of rows (sum of the rows on all pages) * @var int */ private $totalAmountOfRows = 0; /** * Source data * @var array */ private $sourceData = array(); /** * @var Row[] */ private $rows = array(); public function __construct() { parent::__construct(); $this->elementType = 'table_element'; } /** * Declares a new column * @param string $columnName * @param string $columnTitle * @param null|string $sourceColumnName * @return Column * @throws TableException */ public function declareColumn(string $columnName, string $columnTitle, ?string $sourceColumnName) : Column { $columnName = trim($columnName); if (empty($columnName)){ throw new TableException("Column name can not be empty"); } $columnTitle = trim($columnTitle); if (empty($columnTitle)){ throw new TableException("Column title can not be empty"); } $sourceColumnName = !empty($sourceColumnName) ? trim($sourceColumnName) : null; $column = new Column(); $column->setName($columnName); $column->setTitle($columnTitle); $column->setSourceName($sourceColumnName); $this->addColumn($column); return $column; } /** * Adds a new column * @param Column $column * @throws TableException * @return Table */ public function addColumn(Column $column) : self { $columnName = $column->getName(); $columnTitle = $column->getTitle(); if (empty($columnName)){ throw new TableException("Name of the column was not declared"); } if (empty($columnTitle)){ throw new TableException("Title of the column '$columnName' was not defined"); } unset($columnTitle); $columnName = trim($columnName); if (isset($this->columnContainer[$columnName])){ throw new TableException("Column '$columnName' is already declared"); } $this->columnContainer[$columnName] = $column; return $this; } /** * Adds column modifier * @param string $columnName * @param callable $modifier * @throws TableException * @return Table */ public function addColumnModifier(string $columnName, callable $modifier) : self { $columnName = trim($columnName); if (!isset($this->columnContainer[$columnName])){ throw new TableException("Column '$columnName' was not found"); } $this->columnContainer[$columnName]->addModifier($modifier); return $this; } /** * Sets total amount of rows (sum of the rows on all pages) * @param int $totalAmountOfRows * @return Table */ public function setTotalAmountOfRows(int $totalAmountOfRows) : self { $this->totalAmountOfRows = $totalAmountOfRows; return $this; } /** * Gets total amount of rows (sum of the rows on all pages) * @return int */ public function getTotalAmountOfRows() : int { return $this->totalAmountOfRows; } /** * Adds a new row * @param Row $row * @return Table */ public function addRow(Row $row) : self { $this->rows[] = $row; return $this; } /** * Sets source data * @param array $sourceData * @return Table */ public function setSourceData(array &$sourceData) : self { $this->sourceData = $sourceData; $sourceDataSize = \count($this->sourceData); for($rowIndex = 0; $rowIndex < $sourceDataSize; $rowIndex++){ $row = new Row($rowIndex + 1, $this->columnContainer, $this->sourceData[$rowIndex], $this->sourceData); $this->addRow($row); } return $this; } /** * Gets source data * @return array */ public function & getSourceData() : array { return $this->sourceData; } /** * Renders table * @return array */ public function & render() : array { $renderResult = parent::render(); $renderResult['total_rows'] = $this->getTotalAmountOfRows(); $renderResult['columns'] = $this->renderColumns(); $renderResult['rows'] = $this->renderRows(); return $renderResult; } /** * Renders columns * @return array */ private function & renderColumns() : array { $renderedColumns = array(); foreach($this->columnContainer as $columnName => $column){ $renderedColumns[] = $column->render(); } return $renderedColumns; } /** * Renders rows * @return array */ private function & renderRows() : array { $renderedRows = array(); foreach($this->rows as &$row){ $renderedRows[] = $row->render(); } return $renderedRows; } }
DamixSwayware/yumi-bundler
src/View/Table/Table.php
PHP
gpl-3.0
5,395
#! /usr/bin/env python from state_ai import StateAi import rospy from math import pi from std_msgs.msg import Bool class Practice(StateAi): def __init__(self): super(Practice, self).__init__("practice") def on_start(self): self.generate_circle(1.8, pi/4, 2 * pi - pi/4, pi/270.0, -1) def on_goal_changed(self, goal_msg): pass def on_last_goal_reached(self, msg): pass if __name__ == "__main__": try: a = Practice() except rospy.ROSInterruptException: pass
clubcapra/Ibex
src/capra_ai/scripts/practice.py
Python
gpl-3.0
536
"use strict"; /* global global: false */ var ko = require("knockout"); var $ = require("jquery"); var console = require("console"); var tinymce = require("tinymce"); var timeout; var render = function() { timeout = undefined; if (typeof tinymce.activeEditor !== 'undefined' && tinymce.activeEditor !== null && typeof tinymce.activeEditor.theme !== 'undefined' && tinymce.activeEditor.theme !== null && typeof tinymce.activeEditor.theme.panel !== 'undefined' && tinymce.activeEditor.theme.panel !== null && typeof tinymce.activeEditor.theme.panel.visible !== 'undefined') { // @see FloatPanel.js function repositionPanel(panel) // First condition group is for Tinymce 4.0/4.1 // Second condition group is for Tinymce 4.2/4.3 where "._property" are now available as ".state.get('property')". if ((typeof tinymce.activeEditor.theme.panel._visible !== 'undefined' && tinymce.activeEditor.theme.panel._visible && tinymce.activeEditor.theme.panel._fixed) || (typeof tinymce.activeEditor.theme.panel.state !== 'undefined' && tinymce.activeEditor.theme.panel.state.get('visible') && tinymce.activeEditor.theme.panel.state.get('fixed'))) { tinymce.activeEditor.theme.panel.fixed(false); } tinymce.activeEditor.nodeChanged(); // Don't force tinymce to be visible on scrolls // If setteed, This will show the tinymce controls event when non are selected // https://github.com/goodenough/mosaico/issues/7#issuecomment-236853305 // tinymce.activeEditor.theme.panel.visible(true); if (tinymce.activeEditor.theme.panel.layoutRect().y <= 40) tinymce.activeEditor.theme.panel.moveBy(0, 40 - tinymce.activeEditor.theme.panel.layoutRect().y); } }; ko.bindingHandlers.wysiwygScrollfix = { 'scroll': function(event) { if (timeout) global.clearTimeout(timeout); timeout = global.setTimeout(render, 50); }, 'init': function(element) { ko.utils.domNodeDisposal.addDisposeCallback(element, function() { $(element).off("scroll", ko.bindingHandlers.wysiwygScrollfix.scroll); }); $(element).on("scroll", ko.bindingHandlers.wysiwygScrollfix.scroll); } };
goodenough/mosaico
src/js/bindings/scrollfix.js
JavaScript
gpl-3.0
2,159
import { UnitPage } from './app.po'; describe('unit App', () => { let page: UnitPage; beforeEach(() => { page = new UnitPage(); }); it('should display welcome message', () => { page.navigateTo(); expect(page.getParagraphText()).toEqual('Welcome to app!'); }); });
ycsoft/FraUI
e2e/app.e2e-spec.ts
TypeScript
gpl-3.0
289
<?php $PAGE_TITLE = "Register - Cheqout"; require_once("../lib/utilities.php"); require_once(dirname(__DIR__)) . "/php/class/autoload.php"; if(session_status() !== PHP_SESSION_ACTIVE) { session_start(); } ?> <header> <?php require_once("../lib/header.php"); ?> </header> <div class="container registerform"> <div class="col-md-6"> <h2>Register with Cheqout</h2> <form id='register' class="form-group" action='register.php' role="form" method='post' accept-charset='UTF-8'> <!-- <div class="form-group">--> <!-- <input type='email' name='email' id='email' maxlength="128" placeholder="your@email.here"/>--> <!-- </div>--> <div class="form-group row"> <label for="email"></label> <input type="email" id="email" maxlength="128" name="email" placeholder="your@email.here" class="form-control"> </div> <!-- <div class="form-group">--> <!-- <input type='password' name='password' id='password' maxlength="128" placeholder="Password" />--> <!-- </div>--> <div class="form-group row"> <label for="password"></label> <input type="password" id="password" maxlength="128" name="password" placeholder="Password" class="form-control"> </div> <!-- <div class="form-group">--> <!-- <input type='password' name='password2' id='password2' maxlength="128" placeholder="Retype Password"/>--> <!-- </div>--> <div class="form-group row"> <label for="password2"></label> <input type="password" id="password2" maxlength="128" name="password2" placeholder="Retype Password" class="form-control"> </div> <input type='submit' name='Submit' value='Submit' class="btn btn-primary pull-right" /> <span class="col-md-6" id="registerOutput"></span> </form> </div> </div>
jameswlhill/cheqout
register/index.php
PHP
gpl-3.0
1,722
/* * googlehashcode2017_qualification - Copyright (C) 2017 iGoogle team's * * googlehashcode2017_qualification is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * googlehashcode2017_qualification is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with googlehashcode2017_qualification. If not, see <http://www.gnu.org/licenses/>. */ package it.univaq.google.hashcode.model; import java.util.LinkedList; import java.util.List; public class CacheServer { private int id; private int size; private int usedSpace; private List<Video> videos; public CacheServer() { this.videos = new LinkedList<Video>(); this.usedSpace = 0; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public int getUsedSpace() { return usedSpace; } public void setUsedSpace(int usedSpace) { this.usedSpace = usedSpace; } public List<Video> getVideos() { return videos; } public void setVideos(List<Video> videos) { this.videos = videos; } public void addVideo(Video video) { this.videos.add(video); usedSpace += usedSpace + video.getSize(); } }
prednaxela/googlehashcode2017_qualification
src/main/java/it/univaq/google/hashcode/model/CacheServer.java
Java
gpl-3.0
1,656
/* TC Plyer Total Commander Audio Player plugin & standalone player written in C#, based on bass.dll components Copyright (C) 2016 Webmaster442 aka. Ruzsinszki Gábor This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ using ManagedBass; using ManagedBass.Cd; using ManagedBass.Fx; using ManagedBass.Midi; using ManagedBass.Mix; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Runtime.InteropServices; using System.Text; using TCPlayer.Properties; using WPFSoundVisualizationLib; namespace TCPlayer.Code { internal sealed class Player : IDisposable, ISpectrumPlayer { private static readonly Player _instance = new Player(); private readonly int _maxfft; private readonly DownloadProcedure _callback; private readonly PeakEQParameters _eq; private EqConfig _eqConfig; private GCHandle _handle; private bool _initialized; private bool _isplaying; private bool _isstream; private float _lastvol; private bool _paused; private int _source, _mixer, _fx; private Player() { var enginedir = AppDomain.CurrentDomain.BaseDirectory; if (Is64Bit) enginedir = Path.Combine(enginedir, @"Engine\x64"); else enginedir = Path.Combine(enginedir, @"Engine\x86"); Bass.Load(enginedir); BassMix.Load(enginedir); BassCd.Load(enginedir); BassFx.Load(enginedir); Bass.PluginLoad(enginedir + "\\bass_aac.dll"); Bass.PluginLoad(enginedir + "\\bass_ac3.dll"); Bass.PluginLoad(enginedir + "\\bass_ape.dll"); Bass.PluginLoad(enginedir + "\\bass_mpc.dll"); Bass.PluginLoad(enginedir + "\\bass_spx.dll"); Bass.PluginLoad(enginedir + "\\bass_tta.dll"); Bass.PluginLoad(enginedir + "\\bassalac.dll"); Bass.PluginLoad(enginedir + "\\bassdsd.dll"); Bass.PluginLoad(enginedir + "\\bassflac.dll"); Bass.PluginLoad(enginedir + "\\bassopus.dll"); Bass.PluginLoad(enginedir + "\\basswma.dll"); Bass.PluginLoad(enginedir + "\\basswv.dll"); Bass.PluginLoad(enginedir + "\\bassmidi.dll"); _callback = MyDownloadProc; _maxfft = (int)(DataFlags.Available | DataFlags.FFT2048); _eq = new PeakEQParameters(); _handle = GCHandle.Alloc(_eq, GCHandleType.Pinned); } /// <summary> /// Display Error message /// </summary> /// <param name="message"></param> private void Error(string message) { var error = Bass.LastError; string text = string.Format(Resources.Engine_Error, message, (int)error, error); throw new Exception(text); } private void InitEq(ref int chHandle, float fGain = 0.0f) { if (_eqConfig == null) _eqConfig = new EqConfig(); // set peaking equalizer effect with no bands _fx = Bass.ChannelSetFX(chHandle, EffectType.PeakEQ, 0); // BASS_ChannelSetFX(chan, BASS_FX_BFX_PEAKEQ, 0); _eq.fGain = fGain; _eq.fQ = EqConstants.fQ; _eq.fBandwidth = EqConstants.fBandwidth; _eq.lChannel = FXChannelFlags.All; // create 1st band for bass _eq.lBand = 0; _eq.fCenter = EqConstants.fCenter_Bass; Bass.FXSetParameters(_fx, _handle.AddrOfPinnedObject()); // create 2nd band for mid _eq.lBand = 1; _eq.fCenter = EqConstants.fCenter_Mid; Bass.FXSetParameters(_fx, _handle.AddrOfPinnedObject()); // create 3rd band for treble _eq.lBand = 2; _eq.fCenter = EqConstants.fCenter_Treble; Bass.FXSetParameters(_fx, _handle.AddrOfPinnedObject()); UpdateFxConfiguration(_eqConfig); } private void MyDownloadProc(IntPtr buffer, int length, IntPtr user) { var ptr = Bass.ChannelGetTags(_source, TagType.META); if (ptr != IntPtr.Zero) { var array = Native.IntPtrToArray(ptr); if (array != null && MetaChanged != null) MetaChanged(this, PtocessTags(array)); } else { ptr = Bass.ChannelGetTags(_source, TagType.OGG); if (ptr != null) { var array = Native.IntPtrToArray(ptr); if (array != null && MetaChanged != null) MetaChanged(this, PtocessTags(array, true)); } } } private void NotifyPropertyChanged(string info) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info)); } private string PtocessTags(string[] array, bool icecast = false) { StringBuilder ret = new StringBuilder(); if (icecast) { foreach (var item in array) { if (item.StartsWith("ARTIST")) ret.Append(item.Replace("ARTIST=", "")); else if (item.StartsWith("TITLE")) ret.Append(item.Replace("TITLE=", " - ")); } } else { var contents = array[0].Split(';'); foreach (var item in contents) { if (item.StartsWith("StreamTitle='")) ret.Append(item.Replace("StreamTitle='", "").Replace("'", "")); } } return ret.ToString(); } private void RemoveEq(ref int chHandle) { Bass.ChannelRemoveFX(chHandle, _fx); } private void UpdateFxConfiguration(EqConfig eqConfig) { for (int band = 0; band < 3; ++band) { _eq.lBand = band; Bass.FXGetParameters(_fx, _handle.AddrOfPinnedObject()); _eq.fGain = eqConfig[band]; Bass.FXSetParameters(_fx, _handle.AddrOfPinnedObject()); } } public event EventHandler<string> MetaChanged; public event PropertyChangedEventHandler PropertyChanged; public static Player Instance { get { return _instance; } } /// <summary> /// Currently used device index. Used for setting saving /// </summary> public int CurrentDeviceID { get; private set; } public EqConfig EqConfig { get { return _eqConfig; } set { _eqConfig = value; UpdateFxConfiguration(_eqConfig); } } public bool Is64Bit { get { return IntPtr.Size == 8; } } /// <summary> /// IsPaused state /// </summary> public bool IsPaused { get { return _paused || (_mixer == 0); } } public bool IsPlaying { get { return _isplaying; } set { if (value == _isplaying) return; _isplaying = value; NotifyPropertyChanged(nameof(IsPlaying)); } } public bool IsStream { get { return _isstream; } } /// <summary> /// Gets the channel length /// </summary> public double Length { get { var len = Bass.ChannelGetLength(_source); return Bass.ChannelBytes2Seconds(_source, len); } } /// <summary> /// Returns mixer handle /// </summary> public int MixerHandle { get { return _mixer; } } public double Position { get { var pos = Bass.ChannelGetPosition(_source); return Bass.ChannelBytes2Seconds(_source, pos); } set { var pos = Bass.ChannelSeconds2Bytes(_source, value); Bass.ChannelSetPosition(_source, pos); } } /// <summary> /// Player source handle /// </summary> public int SourceHandle { get { return _source; } } /// <summary> /// Gets or sets the Channel volume /// </summary> public float Volume { get { float temp = 0.0f; Bass.ChannelGetAttribute(_mixer, ChannelAttribute.Volume, out temp); return temp; } set { Bass.ChannelSetAttribute(_mixer, ChannelAttribute.Volume, value); _lastvol = value; } } /// <summary> /// Change output device /// </summary> /// <param name="name">string device</param> public void ChangeDevice(string name = null) { if (name == null) { CurrentDeviceID = -1; if (Properties.Settings.Default.SaveDevice) CurrentDeviceID = Properties.Settings.Default.DeviceID; _initialized = Bass.Init(CurrentDeviceID, 48000, DeviceInitFlags.Frequency, IntPtr.Zero); if (!_initialized) { Properties.Settings.Default.DeviceID = 0; Properties.Settings.Default.Save(); Error(Resources.Engine_ErrorBass); return; } Bass.Start(); } for (int i = 0; i < Bass.DeviceCount; i++) { var device = Bass.GetDeviceInfo(i); if (device.Name == name) { if (_initialized) { Bass.Free(); _initialized = false; } _initialized = Bass.Init(i, Settings.Default.SampleRate, DeviceInitFlags.Frequency, IntPtr.Zero); CurrentDeviceID = i; if (!_initialized) { Error(Resources.Engine_ErrorBass); return; } Bass.Start(); } } } /// <summary> /// Free used resources /// </summary> public void Dispose() { if (_source != 0) { if (_mixer != 0) { Stop(); } RemoveEq(ref _mixer); Bass.StreamFree(_source); Bass.MusicFree(_source); Bass.StreamFree(_mixer); _mixer = 0; _source = 0; } if (_handle.IsAllocated) _handle.Free(); if (_initialized) Bass.Free(); BassCd.Unload(); BassFx.Unload(); BassMix.Unload(); Bass.PluginFree(0); } public bool GetChannelData(out short[] data, float seconds) { var length = (int)Bass.ChannelSeconds2Bytes(_mixer, seconds); if (length > 0) { data = new short[length / 2]; length = Bass.ChannelGetData(_mixer, data, length); return true; } data = null; return false; } /// <summary> /// Gets the available output devices /// </summary> /// <returns>device names in an array</returns> public string[] GetDevices() { List<string> _devices = new List<string>(Bass.DeviceCount); for (int i = 1; i < Bass.DeviceCount; i++) { var device = Bass.GetDeviceInfo(i); if (device.IsEnabled) _devices.Add(device.Name); } return _devices.ToArray(); } public bool GetFFTData(float[] fftDataBuffer) { return Bass.ChannelGetData(_mixer, fftDataBuffer, _maxfft) > 0; } public int GetFFTFrequencyIndex(int frequency) { var length = (int)FFTDataSize.FFT2048; int num = (int)Math.Round((double)length * (double)frequency / (double)Properties.Settings.Default.SampleRate); if (num > length / 2 - 1) num = length / 2 - 1; return num; } /// <summary> /// Load a file for playback /// </summary> /// <param name="file">File to load</param> public void Load(string file) { _isstream = false; if (Helpers.IsMidi(file)) { if (!File.Exists(Properties.Settings.Default.SoundfontPath)) { Error(Resources.Engine_ErrorSoundfont); return; } BassMidi.DefaultFont = Properties.Settings.Default.SoundfontPath; } if (_source != 0) { Bass.StreamFree(_source); _source = 0; IsPlaying = false; } if (_mixer != 0) { RemoveEq(ref _mixer); Bass.StreamFree(_mixer); _mixer = 0; IsPlaying = false; } const BassFlags sourceflags = BassFlags.Decode | BassFlags.Loop | BassFlags.Float | BassFlags.Prescan; const BassFlags mixerflags = BassFlags.MixerDownMix | BassFlags.MixerPositionEx | BassFlags.AutoFree; if (file.StartsWith("http://") || file.StartsWith("https://")) { _source = Bass.CreateStream(file, 0, sourceflags, _callback, IntPtr.Zero); _isstream = true; App.RecentUrls.Add(file); } else if (file.StartsWith("cd://")) { string[] info = file.Replace("cd://", "").Split('/'); _source = BassCd.CreateStream(Convert.ToInt32(info[0]), Convert.ToInt32(info[1]), sourceflags); } else if (Helpers.IsTracker(file)) { _source = Bass.MusicLoad(file, 0, 0, sourceflags); } else { _source = Bass.CreateStream(file, 0, 0, sourceflags); } if (_source == 0) { Error("Load failed"); IsPlaying = false; _isstream = false; return; } var ch = Bass.ChannelGetInfo(_source); _mixer = BassMix.CreateMixerStream(ch.Frequency, ch.Channels, mixerflags); if (_mixer == 0) { Error(Resources.Engine_ErrorMixer); IsPlaying = false; return; } if (!BassMix.MixerAddChannel(_mixer, _source, BassFlags.MixerDownMix)) { Error(Resources.Engine_ErrorMixerChannel); IsPlaying = false; return; } Bass.ChannelSetAttribute(_mixer, ChannelAttribute.Volume, _lastvol); InitEq(ref _mixer); Bass.ChannelPlay(_mixer, false); _paused = false; IsPlaying = true; } /// <summary> /// Play / Pause /// </summary> public void PlayPause() { if (_paused) { Bass.ChannelPlay(_mixer, false); _paused = false; IsPlaying = true; } else { Bass.ChannelPause(_mixer); _paused = true; IsPlaying = false; } } /// <summary> /// Stop /// </summary> public void Stop() { Bass.ChannelStop(_mixer); IsPlaying = false; _paused = false; } public void VolumeValues(out int left, out int right) { left = Bass.ChannelGetLevelLeft(_mixer); right = Bass.ChannelGetLevelRight(_mixer); } } }
webmaster442/TCPlayer
TCPlayer/Code/Player.cs
C#
gpl-3.0
17,120
function geojsonToPath( geojson ) { var points = []; var features; if (geojson.type === "FeatureCollection") features = geojson.features; else if (geojson.type === "Feature") features = [geojson]; else features = [{type:"Feature", properties: {}, geometry: geojson}]; features.forEach(function mapFeature(f) { switch (f.geometry.type) { // POIs // LineStrings case "LineString": case "MultiLineString": var coords = f.geometry.coordinates; if (f.geometry.type == "LineString") coords = [coords]; coords.forEach(function(coordinates) { coordinates.forEach(function(c) { points.push("" + c[1] + "," + c[0]); }); }); break; default: console.log("warning: unsupported geometry type: "+f.geometry.type); } }); gpx_str = points.join(':'); return gpx_str; } module.exports = geojsonToPath;
Wilkins/geojson-to-path
index.js
JavaScript
gpl-3.0
903
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); /** * This module contains code for State Parameters. * * See [[ParamDeclaration]] * * @packageDocumentation @preferred */ __exportStar(require("./interface"), exports); __exportStar(require("./param"), exports); __exportStar(require("./paramTypes"), exports); __exportStar(require("./stateParams"), exports); __exportStar(require("./paramType"), exports); //# sourceMappingURL=index.js.map
statusengine/interface
public/node_modules/@uirouter/core/lib/params/index.js
JavaScript
gpl-3.0
962
require 'spec_helper' require 'helper_funcs' describe ReactionRepository do let(:repository) { ReactionRepository.new } let(:quiz_id) { 1 } before do HelperFuncs::Database.new.full_database_setup end it 'queries reactions of the specified stimulus, person and quiz' do repository.get_reactions_of(1, 1, quiz_id).last[:reaction].must_equal 'reac1' repository.get_reactions_of(1, 1).last[:reaction].must_equal 'reac1' repository.get_reactions_of(1).last[:reaction].must_equal 'reac1-2' repository.get_reactions_of(1).to_a.size.must_equal 2 end it 'inserts multiple records at once' do list = [ { reaction: 'reac1', person_id: 1, stimulus_id: 1, quiz_id: quiz_id }, { reaction: 'reac1', person_id: 1, stimulus_id: 1, quiz_id: quiz_id } ] result = repository.create_many(list) result.count.must_equal 2 end describe ReactionRepository.new.get_dictionary do before do HelperFuncs::Database.new.fill_with_reactions end it 'shows selection of type straight' do result = repository.get_dictionary(type: :straight) result[0].reaction.must_equal 'reac1' result[0].stimulus.must_equal 'stim1' result[0].pair_count.must_equal 22 result.last.reaction.must_equal 'reac3-2' result.last.stimulus.must_equal 'stim3' result.last.pair_count.must_equal 1 end it 'shows selection of type reversed' do result = repository.get_dictionary(type: :reversed) result[0].reaction.must_be_nil result[0].stimulus.must_equal 'stim1' result[0].pair_count.must_equal 3 result.last.reaction.must_equal 'reac6' result.last.stimulus.must_equal 'stim1' result.last.pair_count.must_equal 10 end it 'shows selection of type incidence' do result = repository.get_dictionary(type: :incidence) result[0].reaction.must_be_nil result[0].stimulus.must_equal 'stim1' result[0].pair_count.must_equal 3 result.last.reaction.must_equal 'reac3-2' result.last.stimulus.must_equal 'stim3' result.last.pair_count.must_equal 1 end def assert_reactions_belong_to_person1(result) result[0].reaction.must_equal 'reac1' result[0].stimulus.must_equal 'stim1' result[0].pair_count.must_equal 22 result.map(&:reaction).wont_include 'reac1-2' result.map(&:reaction).wont_include 'reac2-2' result.map(&:reaction).wont_include 'reac3-2' end it 'shows selection according to sex' do result = repository.get_dictionary( options: { reactions: {}, people: { sex: 'male' } } ) assert_reactions_belong_to_person1(result) end it 'shows selection according to nationality' do result = repository.get_dictionary( options: { reactions: {}, people: { nationality1: 'Russian' } } ) assert_reactions_belong_to_person1(result) end it 'shows selection according to quiz id' do result = repository.get_dictionary( options: { reactions: { quiz_id: 1 }, people: {} } ) assert_reactions_belong_to_person1(result) end it 'shows selection according to region' do result = repository.get_dictionary( options: { reactions: {}, people: { region: 'Moscow' } } ) assert_reactions_belong_to_person1(result) end it 'shows selection according to native_language' do result = repository.get_dictionary( options: { reactions: {}, people: { native_language: 'Russian' } } ) assert_reactions_belong_to_person1(result) end it 'shows selection according to age' do result = repository.get_dictionary( options: { reactions: {}, people: { age_from: '18' } } ) assert_reactions_belong_to_person1(result) end it 'shows selection according to date' do result = repository.get_dictionary( options: { reactions: {}, people: { date_to: Time.new(2018, 1, 4) } } ) assert_reactions_belong_to_person1(result) end it 'shows selection for one stimulus' do result = repository.get_dictionary(word_list: ['stim1']) result[0].reaction.must_equal 'reac1' result[0].stimulus.must_equal 'stim1' result[0].pair_count.must_equal 22 result.map(&:stimulus).wont_include 'stim2' result.map(&:stimulus).wont_include 'stim3' end it 'shows selection for a list of stimuli' do result = repository.get_dictionary(word_list: ['stim2', 'stim3']) result[0].reaction.must_equal 'reac2' result[0].stimulus.must_equal 'stim2' result[0].pair_count.must_equal 1 result.map(&:stimulus).wont_include 'stim1' end it 'shows selection for one reaction' do result = repository.get_dictionary( options: { reactions: { reaction: 'reac2' }, people: {} } ) result[0].reaction.must_equal 'reac2' result[0].stimulus.must_equal 'stim1' result[0].pair_count.must_equal 18 result.map(&:reaction).uniq.must_equal ['reac2'] end end end
greenfork/associative-experiment
spec/assoc/repositories/reaction_repository_spec.rb
Ruby
gpl-3.0
5,125
# -*- coding: utf-8 -*- ## ## ## This file is part of Indico. ## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN). ## ## Indico is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 3 of the ## License, or (at your option) any later version. ## ## Indico is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Indico;if not, see <http://www.gnu.org/licenses/>. # ZODB imports import ZODB from ZODB import ConflictResolution, MappingStorage from indico.tests.python.functional.seleniumTestCase import SeleniumTestCase import transaction from ZODB.POSException import ConflictError # legacy imports from indico.core.db import DBMgr # indico imports from indico.tests.python.unit.util import IndicoTestFeature from indico.tests import default_actions class TestMemStorage(MappingStorage.MappingStorage, ConflictResolution.ConflictResolvingStorage): """ Test memory storage - useful for conflicts """ def __init__(self, name='foo'): MappingStorage.MappingStorage.__init__(self, name) ConflictResolution.ConflictResolvingStorage.__init__(self) @ZODB.utils.locked(MappingStorage.MappingStorage.opened) def store(self, oid, serial, data, version, transaction): assert not version, "Versions are not supported" if transaction is not self._transaction: raise ZODB.POSException.StorageTransactionError(self, transaction) old_tid = None tid_data = self._data.get(oid) if tid_data: old_tid = tid_data.maxKey() if serial != old_tid: data = self.tryToResolveConflict(oid, old_tid, serial, data) self._tdata[oid] = data return self._tid class Database_Feature(IndicoTestFeature): """ Connects/disconnects the database """ _requires = [] def start(self, obj): super(Database_Feature, self).start(obj) obj._dbmgr = DBMgr.getInstance() retries = 10 # quite prone to DB conflicts while retries: try: with obj._context('database', sync=True) as conn: obj._home = default_actions.initialize_new_db(conn.root()) break except ConflictError: retries -= 1 def _action_startDBReq(obj): obj._dbmgr.startRequest() obj._conn = obj._dbmgr.getDBConnection() return obj._conn def _action_stopDBReq(obj): transaction.commit() obj._conn.close() obj._conn = None def _context_database(self, sync=False): conn = self._startDBReq() if sync: conn.sync() try: yield conn finally: self._stopDBReq() def destroy(self, obj): obj._conn = None class DummyUser_Feature(IndicoTestFeature): """ Creates a dummy user - needs database """ _requires = ['db.Database'] def start(self, obj): super(DummyUser_Feature, self).start(obj) use_password = isinstance(obj, SeleniumTestCase) with obj._context('database', sync=True): obj._avatars = default_actions.create_dummy_users(use_password) for i in xrange(1, 5): setattr(obj, '_avatar%d' % i, obj._avatars[i]) setattr(obj, '_dummy', obj._avatars[0]) class DummyGroup_Feature(IndicoTestFeature): """ Creates a dummy group - needs database """ _requires = ['db.Database'] def start(self, obj): super(DummyGroup_Feature, self).start(obj) with obj._context('database', sync=True): obj._group_with_users = default_actions.create_dummy_group() for usr in obj._avatars: obj._group_with_users.addMember(usr) obj._empty_group = default_actions.create_dummy_group() setattr(obj, '_dummy_group_with_users', obj._group_with_users) setattr(obj, '_dummy_empty_group', obj._empty_group)
pferreir/indico-backup
indico/tests/python/unit/db.py
Python
gpl-3.0
4,383
/* * Copyright (C) 2010 Le Tuan Anh <tuananh.ke@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dakside.reports; import java.util.HashMap; /** * Simple Report data * @author LeTuanAnh <tuananh.ke@gmail.com> */ public class SimpleReportData implements ReportData { private HashMap<String, Object> dataMap = new HashMap<String, Object>(); public Object getData(String key) { if (dataMap.containsKey(key)) { return dataMap.get(key); } else { return ""; } } public boolean contains(String key) { return dataMap.containsKey(key); } public void setData(String key, Object data) { this.dataMap.put(key, data); } public String[] getKeys() { return this.dataMap.keySet().toArray(new String[0]); } }
dakside/shacc
ReportEngine/src/dakside/reports/SimpleReportData.java
Java
gpl-3.0
1,445