id
int64
file_name
string
file_path
string
content
string
size
int64
language
string
extension
string
total_lines
int64
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
repo_name
string
repo_stars
int64
repo_forks
int64
repo_open_issues
int64
repo_license
string
repo_extraction_date
string
exact_duplicates_redpajama
bool
near_duplicates_redpajama
bool
exact_duplicates_githubcode
bool
exact_duplicates_stackv2
bool
exact_duplicates_stackv1
bool
near_duplicates_githubcode
bool
near_duplicates_stackv1
bool
near_duplicates_stackv2
bool
length
int64
3,426,112
LockAllocator.java
insightfullogic_insightfullogic-soot/src/soot/jimple/toolkits/thread/synchronization/LockAllocator.java
package soot.jimple.toolkits.thread.synchronization; import java.util.*; import soot.*; import soot.util.Chain; import soot.jimple.*; import soot.jimple.toolkits.pointer.*; import soot.jimple.toolkits.thread.ThreadLocalObjectsAnalysis; import soot.jimple.toolkits.thread.mhp.MhpTester; import soot.jimple.toolkits.thread.mhp.SynchObliviousMhpAnalysis; import soot.jimple.toolkits.callgraph.*; import soot.jimple.toolkits.infoflow.*; import soot.jimple.spark.pag.*; import soot.jimple.spark.sets.*; import soot.toolkits.scalar.*; import soot.toolkits.graph.*; public class LockAllocator extends SceneTransformer { public LockAllocator(Singletons.Global g){} public static LockAllocator v() { return G.v().soot_jimple_toolkits_thread_synchronization_LockAllocator(); } List<CriticalSection> criticalSections = null; CriticalSectionInterferenceGraph interferenceGraph = null; DirectedGraph deadlockGraph = null; // Lock options boolean optionOneGlobalLock = false; boolean optionStaticLocks = false; boolean optionUseLocksets = false; boolean optionLeaveOriginalLocks = false; boolean optionIncludeEmptyPossibleEdges = false; // Semantic options boolean optionAvoidDeadlock = true; boolean optionOpenNesting = true; // Analysis options boolean optionDoMHP = false; boolean optionDoTLO = false; boolean optionOnFlyTLO = false; // not a CLI option yet // on-fly is more efficient, but harder to measure in time // Output options boolean optionPrintMhpSummary = true; // not a CLI option yet boolean optionPrintGraph = false; boolean optionPrintTable = false; boolean optionPrintDebug = false; protected void internalTransform(String phaseName, Map options) { // Get phase options String lockingScheme = PhaseOptions.getString( options, "locking-scheme" ); if(lockingScheme.equals("fine-grained")) { optionOneGlobalLock = false; optionStaticLocks = false; optionUseLocksets = true; optionLeaveOriginalLocks = false; } // if(lockingScheme.equals("fine-static")) // { // optionOneGlobalLock = false; // optionStaticLocks = true; // optionUseLocksets = true; // optionLeaveOriginalLocks = false; // } if(lockingScheme.equals("medium-grained")) // rename to coarse-grained { optionOneGlobalLock = false; optionStaticLocks = false; optionUseLocksets = false; optionLeaveOriginalLocks = false; } if(lockingScheme.equals("coarse-grained")) // rename to coarse-static { optionOneGlobalLock = false; optionStaticLocks = true; optionUseLocksets = false; optionLeaveOriginalLocks = false; } if(lockingScheme.equals("single-static")) { optionOneGlobalLock = true; optionStaticLocks = true; optionUseLocksets = false; optionLeaveOriginalLocks = false; } if(lockingScheme.equals("leave-original")) { optionOneGlobalLock = false; optionStaticLocks = false; optionUseLocksets = false; optionLeaveOriginalLocks = true; } optionAvoidDeadlock = PhaseOptions.getBoolean( options, "avoid-deadlock" ); optionOpenNesting = PhaseOptions.getBoolean( options, "open-nesting" ); optionDoMHP = PhaseOptions.getBoolean( options, "do-mhp" ); optionDoTLO = PhaseOptions.getBoolean( options, "do-tlo" ); // optionOnFlyTLO = PhaseOptions.getBoolean( options, "on-fly-tlo" ); // not a real option yet // optionPrintMhpSummary = PhaseOptions.getBoolean( options, "print-mhp" ); // not a real option yet optionPrintGraph = PhaseOptions.getBoolean( options, "print-graph" ); optionPrintTable = PhaseOptions.getBoolean( options, "print-table" ); optionPrintDebug = PhaseOptions.getBoolean( options, "print-debug" ); // optionIncludeEmptyPossibleEdges = PhaseOptions.getBoolean( options, "include-empty-edges" ); // not a real option yet // *** Build May Happen In Parallel Info *** MhpTester mhp = null; if(optionDoMHP && Scene.v().getPointsToAnalysis() instanceof PAG) { G.v().out.println("[wjtp.tn] *** Build May-Happen-in-Parallel Info *** " + (new Date())); mhp = new SynchObliviousMhpAnalysis(); if(optionPrintMhpSummary) { mhp.printMhpSummary(); } } // *** Find Thread-Local Objects *** ThreadLocalObjectsAnalysis tlo = null; if(optionDoTLO) { G.v().out.println("[wjtp.tn] *** Find Thread-Local Objects *** " + (new Date())); if(mhp != null) tlo = new ThreadLocalObjectsAnalysis(mhp); else tlo = new ThreadLocalObjectsAnalysis(new SynchObliviousMhpAnalysis()); if(!optionOnFlyTLO) { tlo.precompute(); G.v().out.println("[wjtp.tn] TLO totals (#analyzed/#encountered): " + SmartMethodInfoFlowAnalysis.counter + "/" + ClassInfoFlowAnalysis.methodCount); } else G.v().out.println("[wjtp.tn] TLO so far (#analyzed/#encountered): " + SmartMethodInfoFlowAnalysis.counter + "/" + ClassInfoFlowAnalysis.methodCount); } // *** Find and Name Transactions *** // The transaction finder finds the start, end, and preparatory statements // for each transaction. It also calculates the non-transitive read/write // sets for each transaction. // For all methods, run the intraprocedural analysis (TransactionAnalysis) Date start = new Date(); G.v().out.println("[wjtp.tn] *** Find and Name Transactions *** " + start); Map<SootMethod, FlowSet> methodToFlowSet = new HashMap<SootMethod, FlowSet>(); Map<SootMethod, ExceptionalUnitGraph> methodToExcUnitGraph = new HashMap<SootMethod, ExceptionalUnitGraph>(); Iterator runAnalysisClassesIt = Scene.v().getApplicationClasses().iterator(); while (runAnalysisClassesIt.hasNext()) { SootClass appClass = (SootClass) runAnalysisClassesIt.next(); Iterator methodsIt = appClass.getMethods().iterator(); while (methodsIt.hasNext()) { SootMethod method = (SootMethod) methodsIt.next(); if(method.isConcrete()) { Body b = method.retrieveActiveBody(); ExceptionalUnitGraph eug = new ExceptionalUnitGraph(b); methodToExcUnitGraph.put(method, eug); // run the intraprocedural analysis SynchronizedRegionFinder ta = new SynchronizedRegionFinder(eug, b, optionPrintDebug, optionOpenNesting, tlo); Chain units = b.getUnits(); Unit lastUnit = (Unit) units.getLast(); FlowSet fs = (FlowSet) ta.getFlowBefore(lastUnit); // add the results to the list of results methodToFlowSet.put(method, fs); } } } // Create a composite list of all transactions criticalSections = new Vector<CriticalSection>(); for(FlowSet fs : methodToFlowSet.values()) { List fList = fs.toList(); for(int i = 0; i < fList.size(); i++) criticalSections.add(((SynchronizedRegionFlowPair) fList.get(i)).tn); } // Assign Names To Transactions assignNamesToTransactions(criticalSections); if(optionOnFlyTLO) { G.v().out.println("[wjtp.tn] TLO so far (#analyzed/#encountered): " + SmartMethodInfoFlowAnalysis.counter + "/" + ClassInfoFlowAnalysis.methodCount); } // *** Find Transitive Read/Write Sets *** // Finds the transitive read/write set for each transaction using a given // nesting model. G.v().out.println("[wjtp.tn] *** Find Transitive Read/Write Sets *** " + (new Date())); PointsToAnalysis pta = Scene.v().getPointsToAnalysis(); CriticalSectionAwareSideEffectAnalysis tasea = null; tasea = new CriticalSectionAwareSideEffectAnalysis( pta, Scene.v().getCallGraph(), (optionOpenNesting ? criticalSections : null), tlo); Iterator<CriticalSection> tnIt = criticalSections.iterator(); while(tnIt.hasNext()) { CriticalSection tn = tnIt.next(); for(Unit unit : tn.invokes) { Stmt stmt = (Stmt) unit; HashSet uses = new HashSet(); RWSet stmtRead = tasea.readSet(tn.method, stmt, tn, uses); if(stmtRead != null) tn.read.union(stmtRead); RWSet stmtWrite = tasea.writeSet(tn.method, stmt, tn, uses); if(stmtWrite != null) tn.write.union(stmtWrite); } } long longTime = ((new Date()).getTime() - start.getTime()) / 100; float time = ((float) longTime) / 10.0f; if(optionOnFlyTLO) { G.v().out.println("[wjtp.tn] TLO totals (#analyzed/#encountered): " + SmartMethodInfoFlowAnalysis.counter + "/" + ClassInfoFlowAnalysis.methodCount); G.v().out.println("[wjtp.tn] Time for stages utilizing on-fly TLO: " + time + "s"); } // *** Find Stray Reads/Writes *** (DISABLED) // add external data races as one-line transactions // note that finding them isn't that hard (though it is time consuming) // For all methods, run the intraprocedural analysis (transaction finder) // Note that these will only be transformed if they are either added to // methodToFlowSet or if a loop and new body transformer are used for methodToStrayRWSet /* Map methodToStrayRWSet = new HashMap(); Iterator runRWFinderClassesIt = Scene.v().getApplicationClasses().iterator(); while (runRWFinderClassesIt.hasNext()) { SootClass appClass = (SootClass) runRWFinderClassesIt.next(); Iterator methodsIt = appClass.getMethods().iterator(); while (methodsIt.hasNext()) { SootMethod method = (SootMethod) methodsIt.next(); Body b = method.retrieveActiveBody(); UnitGraph g = (UnitGraph) methodToExcUnitGraph.get(method); // run the interprocedural analysis // PTFindStrayRW ptfrw = new PTFindStrayRW(new ExceptionalUnitGraph(b), b, AllTransactions); PTFindStrayRW ptfrw = new PTFindStrayRW(g, b, AllTransactions); Chain units = b.getUnits(); Unit firstUnit = (Unit) units.iterator().next(); FlowSet fs = (FlowSet) ptfrw.getFlowBefore(firstUnit); // add the results to the list of results methodToStrayRWSet.put(method, fs); } } //*/ // *** Calculate Locking Groups *** // Search for data dependencies between transactions, and split them into disjoint sets G.v().out.println("[wjtp.tn] *** Calculate Locking Groups *** " + (new Date())); CriticalSectionInterferenceGraph ig = new CriticalSectionInterferenceGraph( criticalSections, mhp, optionOneGlobalLock, optionLeaveOriginalLocks, optionIncludeEmptyPossibleEdges); interferenceGraph = ig; // save in field for later retrieval // *** Detect the Possibility of Deadlock *** G.v().out.println("[wjtp.tn] *** Detect the Possibility of Deadlock *** " + (new Date())); DeadlockDetector dd = new DeadlockDetector(optionPrintDebug, optionAvoidDeadlock, true, criticalSections); if(!optionUseLocksets) // deadlock detection for all single-lock-per-region allocations deadlockGraph = dd.detectComponentBasedDeadlock(); // *** Calculate Locking Objects *** // Get a list of all dependencies for each group G.v().out.println("[wjtp.tn] *** Calculate Locking Objects *** " + (new Date())); if(!optionStaticLocks) { // Calculate per-group contributing RWSet // (Might be preferable to use per-transaction contributing RWSet) for(CriticalSection tn : criticalSections) { if(tn.setNumber <= 0) continue; for(CriticalSectionDataDependency tdd : tn.edges) tn.group.rwSet.union(tdd.rw); } } // Inspect each group's RW dependencies to determine if there's a possibility // of a shared lock object (if all dependencies are fields/localobjs of the same object) Map<Value, Integer> lockToLockNum = null; List<PointsToSetInternal> lockPTSets = null; if(optionLeaveOriginalLocks) { analyzeExistingLocks(criticalSections, ig); } else if(optionStaticLocks) { setFlagsForStaticAllocations(ig); } else // for locksets and dynamic locks { setFlagsForDynamicAllocations(ig); // Data structures for determining lock numbers lockPTSets = new ArrayList<PointsToSetInternal>(); lockToLockNum = new HashMap<Value, Integer>(); findLockableReferences(criticalSections, pta, tasea, lockToLockNum,lockPTSets); // print out locksets if(optionUseLocksets) { for( CriticalSection tn : criticalSections ) { if( tn.group != null ) { G.v().out.println("[wjtp.tn] " + tn.name + " lockset: " + locksetToLockNumString(tn.lockset, lockToLockNum) + (tn.group.useLocksets ? "" : " (placeholder)")); } } } } // *** Detect the Possibility of Deadlock for Locksets *** if(optionUseLocksets) // deadlock detection and lock ordering for lockset allocations { G.v().out.println("[wjtp.tn] *** Detect " + (optionAvoidDeadlock ? "and Correct " : "") + "the Possibility of Deadlock for Locksets *** " + (new Date())); deadlockGraph = dd.detectLocksetDeadlock(lockToLockNum, lockPTSets); if(optionPrintDebug) ((HashMutableEdgeLabelledDirectedGraph) deadlockGraph).printGraph(); G.v().out.println("[wjtp.tn] *** Reorder Locksets to Avoid Deadlock *** " + (new Date())); dd.reorderLocksets(lockToLockNum, (HashMutableEdgeLabelledDirectedGraph) deadlockGraph); } // *** Print Output and Transform Program *** G.v().out.println("[wjtp.tn] *** Print Output and Transform Program *** " + (new Date())); // Print topological graph in graphviz format if(optionPrintGraph) printGraph(criticalSections, ig, lockToLockNum); // Print table of transaction information if(optionPrintTable) { printTable(criticalSections, mhp); printGroups(criticalSections, ig); } // For all methods, run the lock transformer if(!optionLeaveOriginalLocks) { // Create an array of booleans to keep track of which global locks have been inserted into the program boolean[] insertedGlobalLock = new boolean[ig.groupCount()]; insertedGlobalLock[0] = false; for(int i = 1; i < ig.groupCount(); i++) { CriticalSectionGroup tnGroup = ig.groups().get(i); insertedGlobalLock[i] = (!optionOneGlobalLock) && (tnGroup.useDynamicLock || tnGroup.useLocksets); } for(SootClass appClass : Scene.v().getApplicationClasses()) { for(SootMethod method : appClass.getMethods()) { if(method.isConcrete()) { FlowSet fs = methodToFlowSet.get(method); if(fs != null) // (newly added methods need not be transformed) LockAllocationBodyTransformer.v().internalTransform(method.getActiveBody(), fs, ig.groups(), insertedGlobalLock); } } } } } protected void findLockableReferences(List<CriticalSection> AllTransactions, PointsToAnalysis pta, CriticalSectionAwareSideEffectAnalysis tasea, Map<Value, Integer> lockToLockNum, List<PointsToSetInternal> lockPTSets) { // For each transaction, if the group's R/Ws may be fields of the same object, // then check for the transaction if they must be fields of the same RUNTIME OBJECT Iterator<CriticalSection> tnIt9 = AllTransactions.iterator(); while(tnIt9.hasNext()) { CriticalSection tn = tnIt9.next(); int group = tn.setNumber - 1; if(group < 0) continue; if(tn.group.useDynamicLock || tn.group.useLocksets) // if attempting to use a dynamic lock or locksets { // Get list of objects (FieldRef or Local) to be locked (lockset analysis) G.v().out.println("[wjtp.tn] * " + tn.name + " *"); LockableReferenceAnalysis la = new LockableReferenceAnalysis(new BriefUnitGraph(tn.method.retrieveActiveBody())); tn.lockset = la.getLocksetOf(tasea, tn.group.rwSet, tn); // Determine if list is suitable for the selected locking scheme // TODO check for nullness if(optionUseLocksets) { // Post-process the locksets if(tn.lockset == null || tn.lockset.size() <= 0) { // If the lockset is invalid, revert the entire group to static locks: tn.group.useLocksets = false; // Create a lockset containing a single placeholder static lock for each tn in the group Value newStaticLock = new NewStaticLock(tn.method.getDeclaringClass()); EquivalentValue newStaticLockEqVal = new EquivalentValue(newStaticLock); for(CriticalSection groupTn : tn.group) { groupTn.lockset = new ArrayList<EquivalentValue>(); groupTn.lockset.add(newStaticLockEqVal); } // Assign a lock number to the placeholder Integer lockNum = new Integer(-lockPTSets.size()); // negative indicates a static lock G.v().out.println("[wjtp.tn] Lock: num " + lockNum + " type " + newStaticLock.getType() + " obj " + newStaticLock); lockToLockNum.put(newStaticLockEqVal, lockNum); lockToLockNum.put(newStaticLock, lockNum); PointsToSetInternal dummyLockPT = new HashPointsToSet(newStaticLock.getType(), (PAG) pta); // KILLS CHA-BASED ANALYSIS (pointer exception) lockPTSets.add(dummyLockPT); } else { // If the lockset is valid // Assign a lock number for each lock in the lockset for( EquivalentValue lockEqVal : tn.lockset ) { Value lock = lockEqVal.getValue(); // Get reaching objects for this lock PointsToSetInternal lockPT; if(lock instanceof Local) lockPT = (PointsToSetInternal) pta.reachingObjects((Local) lock); else if(lock instanceof StaticFieldRef) // needs special treatment: could be primitive lockPT = null; else if(lock instanceof InstanceFieldRef) { Local base = (Local) ((InstanceFieldRef) lock).getBase(); if(base instanceof FakeJimpleLocal) lockPT = (PointsToSetInternal) pta.reachingObjects(((FakeJimpleLocal)base).getRealLocal(), ((FieldRef) lock).getField()); else lockPT = (PointsToSetInternal) pta.reachingObjects(base, ((FieldRef) lock).getField()); } else if(lock instanceof NewStaticLock) // placeholder for anything that needs a static lock lockPT = null; else lockPT = null; if( lockPT != null ) { // Assign an existing lock number if possible boolean foundLock = false; for(int i = 0; i < lockPTSets.size(); i++) { PointsToSetInternal otherLockPT = lockPTSets.get(i); if(lockPT.hasNonEmptyIntersection(otherLockPT)) // will never happen for empty, negative numbered sets { G.v().out.println("[wjtp.tn] Lock: num " + i + " type " + lock.getType() + " obj " + lock); lockToLockNum.put(lock, new Integer(i)); otherLockPT.addAll(lockPT, null); foundLock = true; break; } } // Assign a brand new lock number otherwise if(!foundLock) { G.v().out.println("[wjtp.tn] Lock: num " + lockPTSets.size() + " type " + lock.getType() + " obj " + lock); lockToLockNum.put(lock, new Integer(lockPTSets.size())); PointsToSetInternal otherLockPT = new HashPointsToSet(lockPT.getType(), (PAG) pta); lockPTSets.add(otherLockPT); otherLockPT.addAll(lockPT, null); } } else // static field locks and pathological cases... { // Assign an existing lock number if possible if( lockToLockNum.get(lockEqVal) != null ) { Integer lockNum = lockToLockNum.get(lockEqVal); G.v().out.println("[wjtp.tn] Lock: num " + lockNum + " type " + lock.getType() + " obj " + lock); lockToLockNum.put(lock, lockNum); } else { Integer lockNum = new Integer(-lockPTSets.size()); // negative indicates a static lock G.v().out.println("[wjtp.tn] Lock: num " + lockNum + " type " + lock.getType() + " obj " + lock); lockToLockNum.put(lockEqVal, lockNum); lockToLockNum.put(lock, lockNum); PointsToSetInternal dummyLockPT = new HashPointsToSet(lock.getType(), (PAG) pta); lockPTSets.add(dummyLockPT); } } } } } else { if(tn.lockset == null || tn.lockset.size() != 1) {// Found too few or too many locks // So use a static lock instead tn.lockObject = null; tn.group.useDynamicLock = false; tn.group.lockObject = null; } else {// Found exactly one lock // Use it! tn.lockObject = (Value) tn.lockset.get(0); // If it's the best lock we've found in the group yet, use it for display if(tn.group.lockObject == null || tn.lockObject instanceof Ref) tn.group.lockObject = tn.lockObject; } } } } if(optionUseLocksets) { // If any lock has only a singleton reaching object, treat it like a static lock for(int i = 0; i < lockPTSets.size(); i++) { PointsToSetInternal pts = lockPTSets.get(i); if(pts.size() == 1 && false) // isSingleton(pts)) // It's NOT easy to find a singleton: single alloc node must be run just once { for(Object e : lockToLockNum.entrySet()) { Map.Entry entry = (Map.Entry) e; Integer value = (Integer) entry.getValue(); if(value == i) { entry.setValue(new Integer(-i)); } } } } } } public void setFlagsForDynamicAllocations(CriticalSectionInterferenceGraph ig) { for(int group = 0; group < ig.groupCount() - 1; group++) { CriticalSectionGroup tnGroup = ig.groups().get(group + 1); if(optionUseLocksets) { tnGroup.useLocksets = true; // initially, guess that this is true } else { tnGroup.isDynamicLock = (tnGroup.rwSet.getGlobals().size() == 0); tnGroup.useDynamicLock = true; tnGroup.lockObject = null; } // empty groups don't get locks if(tnGroup.rwSet.size() <= 0) // There are no edges in this group { if(optionUseLocksets) { tnGroup.useLocksets = false; } else { tnGroup.isDynamicLock = false; tnGroup.useDynamicLock = false; } continue; } } } public void setFlagsForStaticAllocations(CriticalSectionInterferenceGraph ig) { // Allocate one new static lock for each group. for(int group = 0; group < ig.groupCount() - 1; group++) { CriticalSectionGroup tnGroup = ig.groups().get(group + 1); tnGroup.isDynamicLock = false; tnGroup.useDynamicLock = false; tnGroup.lockObject = null; } } private void analyzeExistingLocks(List<CriticalSection> AllTransactions, CriticalSectionInterferenceGraph ig) { setFlagsForStaticAllocations(ig); // if for any lock there is any def to anything other than a static field, then it's a local lock. // for each transaction, check every def of the lock Iterator<CriticalSection> tnAIt = AllTransactions.iterator(); while(tnAIt.hasNext()) { CriticalSection tn = tnAIt.next(); if(tn.setNumber <= 0) continue; ExceptionalUnitGraph egraph = new ExceptionalUnitGraph(tn.method.retrieveActiveBody()); SmartLocalDefs sld = new SmartLocalDefs(egraph, new SimpleLiveLocals(egraph)); if(tn.origLock == null || !(tn.origLock instanceof Local)) // || tn.begin == null) continue; List<Unit> rDefs = sld.getDefsOfAt( (Local) tn.origLock , tn.entermonitor ); if(rDefs == null) continue; Iterator<Unit> rDefsIt = rDefs.iterator(); while (rDefsIt.hasNext()) { Stmt next = (Stmt) rDefsIt.next(); if(next instanceof DefinitionStmt) { Value rightOp = ((DefinitionStmt) next).getRightOp(); if(rightOp instanceof FieldRef) { if(((FieldRef) rightOp).getField().isStatic()) { // lock may be static tn.group.lockObject = rightOp; } else { // this lock must be dynamic tn.group.isDynamicLock = true; tn.group.useDynamicLock = true; tn.group.lockObject = tn.origLock; } } else { // this lock is probably dynamic (but it's hard to tell for sure) tn.group.isDynamicLock = true; tn.group.useDynamicLock = true; tn.group.lockObject = tn.origLock; } } else { // this lock is probably dynamic (but it's hard to tell for sure) tn.group.isDynamicLock = true; tn.group.useDynamicLock = true; tn.group.lockObject = tn.origLock; } } } } public static String locksetToLockNumString(List<EquivalentValue> lockset, Map<Value, Integer> lockToLockNum) { if( lockset == null ) return "null"; String ret = "["; boolean first = true; for( EquivalentValue lockEqVal : lockset ) { if(!first) ret = ret + " "; first = false; ret = ret + lockToLockNum.get(lockEqVal.getValue()); } return ret + "]"; } public void assignNamesToTransactions(List<CriticalSection> AllTransactions) { // Give each method a unique, deterministic identifier // Sort transactions into bins... one for each method name // Get list of method names List<String> methodNamesTemp = new ArrayList<String>(); Iterator<CriticalSection> tnIt5 = AllTransactions.iterator(); while (tnIt5.hasNext()) { CriticalSection tn1 = tnIt5.next(); String mname = tn1.method.getSignature(); //tn1.method.getSignature() + "." + tn1.method.getName(); if(!methodNamesTemp.contains(mname)) methodNamesTemp.add(mname); } String methodNames[] = new String[1]; methodNames = methodNamesTemp.toArray(methodNames); Arrays.sort(methodNames); // Initialize method-named bins // this matrix is <# method names> wide and <max txns possible in one method> + 1 tall int identMatrix[][] = new int[methodNames.length][CriticalSection.nextIDNum - methodNames.length + 2]; for(int i = 0; i < methodNames.length; i++) { identMatrix[i][0] = 0; for(int j = 1; j < CriticalSection.nextIDNum - methodNames.length + 1; j++) { identMatrix[i][j] = 50000; } } // Put transactions into bins Iterator<CriticalSection> tnIt0 = AllTransactions.iterator(); while(tnIt0.hasNext()) { CriticalSection tn1 = tnIt0.next(); int methodNum = Arrays.binarySearch(methodNames, tn1.method.getSignature()); identMatrix[methodNum][0]++; identMatrix[methodNum][identMatrix[methodNum][0]] = tn1.IDNum; } // Sort bins by transaction IDNum // IDNums vary, but always increase in code-order within a method for(int j = 0; j < methodNames.length; j++) { identMatrix[j][0] = 0; // set the counter to 0 so it sorts out (into slot 0). Arrays.sort(identMatrix[j]); // sort this subarray } // Generate a name based on the bin number and location within the bin Iterator<CriticalSection> tnIt4 = AllTransactions.iterator(); while(tnIt4.hasNext()) { CriticalSection tn1 = tnIt4.next(); int methodNum = Arrays.binarySearch(methodNames, tn1.method.getSignature()); int tnNum = Arrays.binarySearch(identMatrix[methodNum], tn1.IDNum) - 1; tn1.name = "m" + (methodNum < 10? "00" : (methodNum < 100? "0" : "")) + methodNum + "n" + (tnNum < 10? "0" : "") + tnNum; } } public void printGraph(Collection<CriticalSection> AllTransactions, CriticalSectionInterferenceGraph ig, Map<Value, Integer> lockToLockNum) { final String[] colors = {"black", "blue", "blueviolet", "chartreuse", "crimson", "darkgoldenrod1", "darkseagreen", "darkslategray", "deeppink", "deepskyblue1", "firebrick1", "forestgreen", "gold", "gray80", "navy", "pink", "red", "sienna", "turquoise1", "yellow"}; Map<Integer, String> lockColors = new HashMap<Integer, String>(); int colorNum = 0; HashSet<CriticalSection> visited = new HashSet<CriticalSection>(); G.v().out.println("[transaction-graph]" + (optionUseLocksets ? "" : " strict") + " graph transactions {"); // "\n[transaction-graph] start=1;"); for(int group = 0; group < ig.groups().size(); group++) { boolean printedHeading = false; Iterator<CriticalSection> tnIt = AllTransactions.iterator(); while(tnIt.hasNext()) { CriticalSection tn = tnIt.next(); if(tn.setNumber == group + 1) { if(!printedHeading) { // if(localLock[group] && lockObject[group] != null) if(tn.group.useDynamicLock && tn.group.lockObject != null) { String typeString = ""; // if(lockObject[group].getType() instanceof RefType) // typeString = ((RefType) lockObject[group].getType()).getSootClass().getShortName(); // else // typeString = lockObject[group].getType().toString(); if(tn.group.lockObject.getType() instanceof RefType) typeString = ((RefType) tn.group.lockObject.getType()).getSootClass().getShortName(); else typeString = tn.group.lockObject.getType().toString(); G.v().out.println("[transaction-graph] subgraph cluster_" + (group + 1) + " {\n[transaction-graph] color=blue;\n[transaction-graph] label=\"Lock: a \\n" + typeString + " object\";"); } else if(tn.group.useLocksets) { G.v().out.println("[transaction-graph] subgraph cluster_" + (group + 1) + " {\n[transaction-graph] color=blue;\n[transaction-graph] label=\"Locksets\";"); } else { String objString = ""; // if(lockObject[group] == null) if(tn.group.lockObject == null) { objString = "lockObj" + (group + 1); } // else if(lockObject[group] instanceof FieldRef) else if(tn.group.lockObject instanceof FieldRef) { // SootField field = ((FieldRef) lockObject[group]).getField(); SootField field = ((FieldRef) tn.group.lockObject).getField(); objString = field.getDeclaringClass().getShortName() + "." + field.getName(); } else objString = tn.group.lockObject.toString(); // objString = lockObject[group].toString(); G.v().out.println("[transaction-graph] subgraph cluster_" + (group + 1) + " {\n[transaction-graph] color=blue;\n[transaction-graph] label=\"Lock: \\n" + objString + "\";"); } printedHeading = true; } if(Scene.v().getReachableMethods().contains(tn.method)) G.v().out.println("[transaction-graph] " + tn.name + " [name=\"" + tn.method.toString() + "\" style=\"setlinewidth(3)\"];"); else G.v().out.println("[transaction-graph] " + tn.name + " [name=\"" + tn.method.toString() + "\" color=cadetblue1 style=\"setlinewidth(1)\"];"); if(tn.group.useLocksets) // print locks instead of dependence edges { for(EquivalentValue lockEqVal : tn.lockset) { Integer lockNum = lockToLockNum.get(lockEqVal.getValue()); for(CriticalSection tn2 : tn.group) { if(!visited.contains(tn2) && ig.mayHappenInParallel(tn, tn2)) { for(EquivalentValue lock2EqVal : tn2.lockset) { Integer lock2Num = lockToLockNum.get(lock2EqVal.getValue()); if(lockNum.intValue() == lock2Num.intValue()) { // Get the color for this lock if(!lockColors.containsKey(lockNum)) { lockColors.put(lockNum, colors[colorNum % colors.length]); colorNum++; } String color = lockColors.get(lockNum); // Draw an edge for this lock G.v().out.println("[transaction-graph] " + tn.name + " -- " + tn2.name + " [color=" + color + " style=" + (lockNum >= 0 ? "dashed" : "solid") + " exactsize=1 style=\"setlinewidth(3)\"];"); } } } } visited.add(tn); } } else { Iterator<CriticalSectionDataDependency> tnedgeit = tn.edges.iterator(); while(tnedgeit.hasNext()) { CriticalSectionDataDependency edge = tnedgeit.next(); CriticalSection tnedge = edge.other; if(tnedge.setNumber == group + 1) G.v().out.println("[transaction-graph] " + tn.name + " -- " + tnedge.name + " [color=" + (edge.size > 0 ? "black" : "cadetblue1") + " style=" + (tn.setNumber > 0 && tn.group.useDynamicLock ? "dashed" : "solid") + " exactsize=" + edge.size + " style=\"setlinewidth(3)\"];"); } } } } if(printedHeading) G.v().out.println("[transaction-graph] }"); } // Print nodes with no group { boolean printedHeading = false; Iterator<CriticalSection> tnIt = AllTransactions.iterator(); while(tnIt.hasNext()) { CriticalSection tn = tnIt.next(); if(tn.setNumber == -1) { if(!printedHeading) { // putting these nodes in a "source" ranked subgraph makes them appear above all the clusters G.v().out.println("[transaction-graph] subgraph lone {\n[transaction-graph] rank=source;"); printedHeading = true; } if(Scene.v().getReachableMethods().contains(tn.method)) G.v().out.println("[transaction-graph] " + tn.name + " [name=\"" + tn.method.toString() + "\" style=\"setlinewidth(3)\"];"); else G.v().out.println("[transaction-graph] " + tn.name + " [name=\"" + tn.method.toString() + "\" color=cadetblue1 style=\"setlinewidth(1)\"];"); Iterator<CriticalSectionDataDependency> tnedgeit = tn.edges.iterator(); while(tnedgeit.hasNext()) { CriticalSectionDataDependency edge = tnedgeit.next(); CriticalSection tnedge = edge.other; if(tnedge.setNumber != tn.setNumber || tnedge.setNumber == -1) G.v().out.println("[transaction-graph] " + tn.name + " -- " + tnedge.name + " [color=" + (edge.size > 0 ? "black" : "cadetblue1") + " style=" + (tn.setNumber > 0 && tn.group.useDynamicLock ? "dashed" : "solid") + " exactsize=" + edge.size + " style=\"setlinewidth(1)\"];"); } } } if(printedHeading) G.v().out.println("[transaction-graph] }"); } G.v().out.println("[transaction-graph] }"); } public void printTable(Collection<CriticalSection> AllTransactions, MhpTester mhp) { G.v().out.println("[transaction-table] "); Iterator<CriticalSection> tnIt7 = AllTransactions.iterator(); while(tnIt7.hasNext()) { CriticalSection tn = tnIt7.next(); // Figure out if it's reachable, and if it MHP itself boolean reachable = false; boolean mhpself = false; { ReachableMethods rm = Scene.v().getReachableMethods(); reachable = rm.contains(tn.method); if(mhp != null) mhpself = mhp.mayHappenInParallel(tn.method, tn.method); } G.v().out.println("[transaction-table] Transaction " + tn.name + (reachable ? " reachable" : " dead") + (mhpself ? " [called from >= 2 threads]" : " [called from <= 1 thread]")); G.v().out.println("[transaction-table] Where: " + tn.method.getDeclaringClass().toString() + ":" + tn.method.toString() + ": "); G.v().out.println("[transaction-table] Orig : " + tn.origLock); G.v().out.println("[transaction-table] Prep : " + tn.prepStmt); G.v().out.println("[transaction-table] Begin: " + tn.entermonitor); G.v().out.print("[transaction-table] End : early:" + tn.earlyEnds.toString() + " exc:" + tn.exceptionalEnd + " through:" + tn.end + " \n"); G.v().out.println("[transaction-table] Size : " + tn.units.size()); if(tn.read.size() < 100) G.v().out.print("[transaction-table] Read : " + tn.read.size() + "\n[transaction-table] " + tn.read.toString().replaceAll("\\[", " : [").replaceAll("\n", "\n[transaction-table] ")); else G.v().out.print("[transaction-table] Read : " + tn.read.size() + " \n[transaction-table] "); if(tn.write.size() < 100) G.v().out.print("Write: " + tn.write.size() + "\n[transaction-table] " + tn.write.toString().replaceAll("\\[", " : [").replaceAll("\n", "\n[transaction-table] ")); // label provided by previous print statement else G.v().out.print("Write: " + tn.write.size() + "\n[transaction-table] "); // label provided by previous print statement G.v().out.print("Edges: (" + tn.edges.size() + ") "); // label provided by previous print statement Iterator<CriticalSectionDataDependency> tnedgeit = tn.edges.iterator(); while(tnedgeit.hasNext()) G.v().out.print(tnedgeit.next().other.name + " "); if(tn.group != null && tn.group.useLocksets) { G.v().out.println("\n[transaction-table] Locks: " + tn.lockset); } else G.v().out.println("\n[transaction-table] Lock : " + (tn.setNumber == -1 ? "-" : (tn.lockObject == null ? "Global" : (tn.lockObject.toString() + (tn.lockObjectArrayIndex == null ? "" : "[" + tn.lockObjectArrayIndex + "]")) ))); G.v().out.println("[transaction-table] Group: " + tn.setNumber + "\n[transaction-table] "); } } public void printGroups(Collection<CriticalSection> AllTransactions, CriticalSectionInterferenceGraph ig) { G.v().out.print("[transaction-groups] Group Summaries\n[transaction-groups] "); for(int group = 0; group < ig.groupCount() - 1; group++) { CriticalSectionGroup tnGroup = ig.groups().get(group + 1); if(tnGroup.size() > 0) { G.v().out.print("Group " + (group + 1) + " "); G.v().out.print("Locking: " + (tnGroup.useLocksets ? "using " : (tnGroup.isDynamicLock && tnGroup.useDynamicLock ? "Dynamic on " : "Static on ")) + (tnGroup.useLocksets ? "locksets" : (tnGroup.lockObject == null ? "null" : tnGroup.lockObject.toString())) ); G.v().out.print("\n[transaction-groups] : "); Iterator<CriticalSection> tnIt = AllTransactions.iterator(); while(tnIt.hasNext()) { CriticalSection tn = tnIt.next(); if(tn.setNumber == group + 1) G.v().out.print(tn.name + " "); } G.v().out.print("\n[transaction-groups] " + tnGroup.rwSet.toString().replaceAll("\\[", " : [").replaceAll("\n", "\n[transaction-groups] ")); } } G.v().out.print("Erasing \n[transaction-groups] : "); Iterator<CriticalSection> tnIt = AllTransactions.iterator(); while(tnIt.hasNext()) { CriticalSection tn = tnIt.next(); if(tn.setNumber == -1) G.v().out.print(tn.name + " "); } G.v().out.println("\n[transaction-groups] "); } public CriticalSectionInterferenceGraph getInterferenceGraph() { return interferenceGraph; } public DirectedGraph getDeadlockGraph() { return deadlockGraph; } public List<CriticalSection> getCriticalSections() { return criticalSections; } }
38,331
Java
.java
893
37.058231
281
0.666182
insightfullogic/insightfullogic-soot
3
0
0
LGPL-2.1
9/4/2024, 11:25:38 PM (Europe/Amsterdam)
false
false
false
true
true
true
true
true
38,331
1,317,218
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameType/testFail94/in/A.java
package p; class A{} class B{ native void m(A a); }
52
Java
.java
5
9.4
20
0.6875
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
52
5,031,827
TaskPathProjectEvaluator.java
cams7_gradle-samples/plugin/core/src/main/groovy/org/gradle/execution/TaskPathProjectEvaluator.java
/* * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.execution; import org.gradle.api.BuildCancelledException; import org.gradle.api.Project; import org.gradle.api.internal.project.ProjectInternal; import org.gradle.initialization.BuildCancellationToken; public class TaskPathProjectEvaluator implements ProjectConfigurer { private final BuildCancellationToken cancellationToken; public TaskPathProjectEvaluator(BuildCancellationToken cancellationToken) { this.cancellationToken = cancellationToken; } public void configure(ProjectInternal project) { if (cancellationToken.isCancellationRequested()) { throw new BuildCancelledException(); } project.evaluate(); } public void configureHierarchy(ProjectInternal project) { if (cancellationToken.isCancellationRequested()) { throw new BuildCancelledException(); } project.evaluate(); for (Project sub : project.getSubprojects()) { if (cancellationToken.isCancellationRequested()) { throw new BuildCancelledException(); } ((ProjectInternal) sub).evaluate(); } } }
1,773
Java
.java
44
34.863636
79
0.733759
cams7/gradle-samples
1
0
0
GPL-2.0
9/5/2024, 12:39:20 AM (Europe/Amsterdam)
true
true
true
true
true
true
true
true
1,773
1,318,045
A_test12_in.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractConstant/canExtract/A_test12_in.java
// 9, 19 -> 9, 24 package p; class A { void foob() { int e= (2 + 2) * 3 * 1; int f= 5 *3* 1 *(1 + 1); } }
119
Java
.java
8
12.375
27
0.428571
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
119
4,948,008
LockboxDao.java
ua-eas_ua-kfs-5_3/work/src/org/kuali/kfs/module/ar/dataaccess/LockboxDao.java
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.module.ar.dataaccess; import java.util.Collection; import java.util.Iterator; import org.kuali.kfs.module.ar.businessobject.Lockbox; public interface LockboxDao { public Iterator<Lockbox> getByLockboxNumber(String lockboxNumber); public Collection<Lockbox> getAllLockboxes(); /** * * Returns the highest (numerically) value for the Lockbox * invoiceSequenceNumber. * * @return The max Lockbox.invoiceSequenceNumber */ public Long getMaxLockboxSequenceNumber(); }
1,404
Java
.java
34
36.911765
97
0.746313
ua-eas/ua-kfs-5.3
1
0
0
AGPL-3.0
9/5/2024, 12:36:54 AM (Europe/Amsterdam)
false
false
true
true
false
true
false
true
1,404
1,317,747
A_test60_in.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractTemp/canExtract/A_test60_in.java
//7, 17 -> 7, 18 package p; class A { private void foo() { int s= 0; int z= -s; } }
90
Java
.java
8
9.5
21
0.536585
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
90
3,425,981
EnhancedUnitGraph.java
insightfullogic_insightfullogic-soot/src/soot/toolkits/graph/pdg/EnhancedUnitGraph.java
/* Soot - a J*va Optimization Framework * Copyright (C) 1999-2010 Hossein Sadat-Mohtasham * * This library 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 library 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 library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ package soot.toolkits.graph.pdg; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import soot.Body; import soot.Trap; import soot.Unit; import soot.jimple.ThrowStmt; import soot.jimple.internal.JNopStmt; import soot.toolkits.graph.DominatorNode; import soot.toolkits.graph.MHGDominatorsFinder; import soot.toolkits.graph.MHGPostDominatorsFinder; import soot.toolkits.graph.UnitGraph; import soot.util.Chain; /** * * This class represents a control flow graph which behaves like an ExceptionalUnitGraph and * BriefUnitGraph when there are no exception handling construct in the method; at the presence * of such constructs, the CFG is constructed from a brief graph by addition a concise representation * of the exceptional flow as well as START/STOP auxiliary nodes. In a nutshell, the exceptional flow * is represented at the level of try-catch-finally blocks instead of the Unit level to allow a more * useful region analysis. * * @author Hossein Sadat-Mohtasham * */ public class EnhancedUnitGraph extends UnitGraph { //This keeps a map from the beginning of each guarded block //to the corresponding special EHNopStmt. //protected Hashtable<GuardedBlock, Unit> try2nop = null; protected Hashtable<Unit, Unit> try2nop = null; //Keep the real header of the handler block protected Hashtable<Unit, Unit> handler2header = null; public EnhancedUnitGraph(Body body) { super(body); //try2nop = new Hashtable<GuardedBlock, Unit>(); try2nop = new Hashtable<Unit, Unit>(); handler2header = new Hashtable<Unit, Unit>(); //there could be a maximum of traps.size() of nop //units added to the CFG plus potentially START/STOP nodes. int size = unitChain.size() + body.getTraps().size() + 2; unitToSuccs = new HashMap<Unit, List<Unit>>(size * 2 + 1, 0.7f); unitToPreds = new HashMap<Unit, List<Unit>>(size * 2 + 1, 0.7f); /* * Compute the head and tails at each phase because other phases * might rely on them. */ buildUnexceptionalEdges(unitToSuccs, unitToPreds); addAuxiliaryExceptionalEdges(); buildHeadsAndTails(); handleExplicitThrowEdges(); buildHeadsAndTails(); handleMultipleReturns(); buildHeadsAndTails(); /** * Remove bogus heads (these are useless goto's) */ removeBogusHeads(); buildHeadsAndTails(); makeMappedListsUnmodifiable(unitToSuccs); makeMappedListsUnmodifiable(unitToPreds); } /** * This method adds a STOP node to the graph, if necessary, to make the CFG * single-tailed. */ protected void handleMultipleReturns() { if(this.getTails().size() > 1) { Unit stop = new ExitStmt(); List<Unit> predsOfstop = new ArrayList<Unit>(); for(Iterator<Unit> tailItr = this.getTails().iterator(); tailItr.hasNext(); ) { Unit tail = tailItr.next(); predsOfstop.add(tail); List<Unit> tailSuccs = this.unitToSuccs.get(tail); tailSuccs.add(stop); } this.unitToPreds.put(stop, predsOfstop); this.unitToSuccs.put(stop, new ArrayList<Unit>()); Chain<Unit> units = body.getUnits().getNonPatchingChain(); if(!units.contains(stop)) units.addLast(stop); } } /** * This method removes all the heads in the CFG except the one * that corresponds to the first unit in the method. */ protected void removeBogusHeads() { Chain<Unit> units = body.getUnits(); Unit trueHead = units.getFirst(); while(this.getHeads().size() > 1) { for(Iterator<Unit> headItr = this.getHeads().iterator(); headItr.hasNext(); ) { Unit head = headItr.next(); if(trueHead == head) continue; this.unitToPreds.remove(head); List<Unit> succs = this.unitToSuccs.get(head); for(Iterator<Unit> succsItr = succs.iterator(); succsItr.hasNext(); ) { List<Unit> tobeRemoved = new ArrayList<Unit>(); Unit succ = succsItr.next(); List<Unit> predOfSuccs = this.unitToPreds.get(succ); for(Iterator<Unit> predItr = predOfSuccs.iterator(); predItr.hasNext(); ) { Unit pred = predItr.next(); if(pred == head) tobeRemoved.add(pred); } predOfSuccs.removeAll(tobeRemoved); } this.unitToSuccs.remove(head); if(units.contains(head)) units.remove(head); } this.buildHeadsAndTails(); } } @SuppressWarnings("unchecked") protected void handleExplicitThrowEdges() { MHGDominatorTree dom = new MHGDominatorTree(new MHGDominatorsFinder<Unit>(this)); MHGDominatorTree pdom = new MHGDominatorTree(new MHGPostDominatorsFinder(this)); //this keeps a map from the entry of a try-catch-block to a selected merge point Hashtable<Unit, Unit> x2mergePoint = new Hashtable<Unit, Unit>(); List<Unit> tails = this.getTails(); TailsLoop: for(Iterator<Unit> itr = tails.iterator(); itr.hasNext(); ) { Unit tail = itr.next(); if(!(tail instanceof ThrowStmt)) continue; DominatorNode x = dom.getDode(tail); DominatorNode parentOfX = dom.getParentOf(x); Object xgode = x.getGode(); DominatorNode xpdomDode = pdom.getDode(xgode); Object parentXGode = parentOfX.getGode(); DominatorNode parentpdomDode = pdom.getDode(parentXGode); //while x post-dominates its dominator (parent in dom) while(pdom.isDominatorOf(xpdomDode, parentpdomDode)) { x = parentOfX; parentOfX = dom.getParentOf(x); //If parent is null we must be at the head of the graph if(parentOfX == null) //throw new RuntimeException("This should never have happened!"); break; xgode = x.getGode(); xpdomDode = pdom.getDode(xgode); parentXGode = parentOfX.getGode(); parentpdomDode = pdom.getDode(parentXGode); } if(parentOfX != null) x = parentOfX; xgode = x.getGode(); xpdomDode = pdom.getDode(xgode); Unit mergePoint = null; if(x2mergePoint.containsKey(xgode)) mergePoint = x2mergePoint.get(xgode); else { //Now get all the children of x in the dom List<DominatorNode> domChilds = dom.getChildrenOf(x); Object child1god = null; Object child2god = null; for(Iterator<DominatorNode> domItr = domChilds.iterator(); domItr.hasNext(); ) { DominatorNode child = domItr.next(); Object childGode = child.getGode(); DominatorNode childpdomDode = pdom.getDode(childGode); //we don't want to make a loop! List<Unit> path = this.getExtendedBasicBlockPathBetween((Unit)childGode, tail); //if(dom.isDominatorOf(child, dom.getDode(tail))) if(!(path == null || path.size() == 0)) continue; if(pdom.isDominatorOf(childpdomDode, xpdomDode)) { mergePoint = (Unit) child.getGode(); break; } //gather two eligible childs if(child1god == null) child1god = childGode; else if(child2god == null) child2god = childGode; } if(mergePoint == null) { if(child1god != null && child2god != null) { DominatorNode child1 = pdom.getDode(child1god); DominatorNode child2 = pdom.getDode(child2god); //go up the pdom tree and find the common parent of child1 and child2 DominatorNode comParent = child1.getParent(); while(comParent != null) { if(pdom.isDominatorOf(comParent, child2)) { mergePoint = (Unit) comParent.getGode(); break; } comParent = comParent.getParent(); } } else if(child1god != null || child2god != null){ DominatorNode y = null; if(child1god != null) y = pdom.getDode(child1god); else if(child2god != null) y = pdom.getDode(child2god); DominatorNode initialY = dom.getDode(y.getGode()); DominatorNode yDodeInDom = initialY; while(dom.isDominatorOf(x, yDodeInDom)) { y = y.getParent(); //If this is a case where the childs of a conditional //are all throws, or returns, just forget it! if(y == null) { break ; } yDodeInDom = dom.getDode(y.getGode()); } if(y != null) mergePoint = (Unit) y.getGode(); else mergePoint = (Unit) initialY.getGode(); } } //This means no (dom) child of x post-dominates x, so just use the child that is //immediately /*if(mergePoint == null) { //throw new RuntimeException("No child post-dominates x."); mergePoint = potentialMergePoint; }*/ //This means no (dom) child of x post-dominates x, so just use the child that is //immediately. this means there is no good reliable merge point. So we just fetch the succ //of x in CFg so that the succ does not dominate the throw, and find the first //post-dom of the succ so that x does not dom it. // if(mergePoint == null) { List<Unit> xSucc = this.unitToSuccs.get(x.getGode()); for(Iterator<Unit> uItr = xSucc.iterator(); uItr.hasNext(); ) { Unit u = uItr.next(); if(dom.isDominatorOf(dom.getDode(u), dom.getDode(tail))) continue; DominatorNode y = pdom.getDode(u); while(dom.isDominatorOf(x, y)) { y = y.getParent(); //If this is a case where the childs of a conditional //are all throws, or returns, just forget it! if(y == null) { continue TailsLoop; } } mergePoint = (Unit) y.getGode(); break; } } //the following happens if the throw is the only exit in the method (even if return stmt is present.) else if(dom.isDominatorOf(dom.getDode(mergePoint), dom.getDode(tail))) continue TailsLoop; if(mergePoint == null) throw new RuntimeException("This should not have happened!"); x2mergePoint.put((Unit) xgode, mergePoint); } //add an edge from the tail (throw) to the merge point if(!this.unitToSuccs.containsKey(tail)) this.unitToSuccs.put(tail, new ArrayList<Unit>()); List<Unit> throwSuccs = this.unitToSuccs.get(tail); throwSuccs.add(mergePoint); List<Unit> mergePreds = this.unitToPreds.get(mergePoint); mergePreds.add(tail); } } /** * Add an exceptional flow edge for each handler from the corresponding * auxiliary nop node to the beginning of the handler. */ protected void addAuxiliaryExceptionalEdges() { //Do some preparation for each trap in the method for (Iterator<Trap> trapIt = body.getTraps().iterator(); trapIt.hasNext(); ) { Trap trap = trapIt.next(); /** * Find the real header of this handler block * */ Unit handler = trap.getHandlerUnit(); Unit pred = handler; while(this.unitToPreds.get(pred).size() > 0) pred = this.unitToPreds.get(pred).get(0); handler2header.put(handler, pred); /***********/ /* * Keep this here for possible future changes. */ /*GuardedBlock gb = new GuardedBlock(trap.getBeginUnit(), trap.getEndUnit()); Unit ehnop; if(try2nop.containsKey(gb)) ehnop = try2nop.get(gb); else { ehnop = new EHNopStmt(); try2nop.put(gb, ehnop); }*/ Unit ehnop; if(try2nop.containsKey(trap.getBeginUnit())) ehnop = try2nop.get(trap.getBeginUnit()); else { ehnop = new EHNopStmt(); try2nop.put(trap.getBeginUnit(), ehnop); } } //Only add a nop once Hashtable<Unit, Boolean> nop2added = new Hashtable<Unit, Boolean>(); // Now actually add the edge AddExceptionalEdge: for (Iterator<Trap> trapIt = body.getTraps().iterator(); trapIt.hasNext(); ) { Trap trap = trapIt.next(); Unit b = trap.getBeginUnit(); Unit handler = trap.getHandlerUnit(); handler = handler2header.get(handler); /** * Check if this trap is a finally trap that handles exceptions of an adjacent catch block; * what differentiates such trap is that it's guarded region has the same parent as the * handler of the trap itself, in the dom tree. * * The problem is that we don't have a complete DOM tree at this transient state. * * The work-around is to not process a trap that has already an edge pointing to it. * */ if(this.unitToPreds.containsKey(handler)) { List<Unit> handlerPreds = this.unitToPreds.get(handler); for(Iterator<Unit> preditr = handlerPreds.iterator(); preditr.hasNext(); ) if(try2nop.containsValue(preditr.next())) continue AddExceptionalEdge; } else continue; //GuardedBlock gb = new GuardedBlock(b, e); Unit ehnop = try2nop.get(b); if(!nop2added.containsKey(ehnop)) { List<Unit> predsOfB = getPredsOf(b); List<Unit> predsOfehnop = new ArrayList<Unit>(predsOfB); for(Iterator<Unit> itr = predsOfB.iterator(); itr.hasNext(); ) { Unit a = itr.next(); List<Unit> succsOfA = this.unitToSuccs.get(a); succsOfA.remove(b); succsOfA.add((Unit)ehnop); } predsOfB.clear(); predsOfB.add((Unit)ehnop); this.unitToPreds.put((Unit)ehnop, predsOfehnop); } if(!this.unitToSuccs.containsKey(ehnop)) this.unitToSuccs.put(ehnop, new ArrayList<Unit>()); List<Unit> succsOfehnop = this.unitToSuccs.get(ehnop); if(!succsOfehnop.contains(b)) succsOfehnop.add(b); succsOfehnop.add(handler); if(!this.unitToPreds.containsKey(handler)) this.unitToPreds.put(handler, new ArrayList<Unit>()); List<Unit> predsOfhandler = this.unitToPreds.get(handler); predsOfhandler.add((Unit)ehnop); Chain<Unit> units = body.getUnits().getNonPatchingChain(); if(!units.contains(ehnop)) units.insertBefore((Unit)ehnop, b); nop2added.put(ehnop, Boolean.TRUE); } } } /** * This class represents a block of code guarded by a trap. Currently, this * is not used but it might well be put to use in later updates. * * @author Hossein Sadat-Mohtasham * */ class GuardedBlock { Unit start, end; public GuardedBlock(Unit s, Unit e) { this.start = s; this.end = e; } public int hashCode() { // Following Joshua Bloch's recipe in "Effective Java", Item 8: int result = 17; result = 37 * result + this.start.hashCode(); result = 37 * result + this.end.hashCode(); return result; } public boolean equals(Object rhs) { if (rhs == this) { return true; } if (! (rhs instanceof GuardedBlock)) { return false; } GuardedBlock rhsGB = (GuardedBlock) rhs; return ((this.start == rhsGB.start) && (this.end == rhsGB.end)); } } /** * * @author Hossein Sadat-Mohtasham * Feb 2010 * * This class represents a special nop statement that marks the * beginning of a try block at the Jimple level. This is going * to be used in the CFG enhancement. * */ @SuppressWarnings("serial") class EHNopStmt extends JNopStmt { public EHNopStmt() { } public Object clone() { return new EHNopStmt(); } public boolean fallsThrough(){return true;} public boolean branches(){return false;} } /** * * @author Hossein Sadat-Mohtasham * Feb 2010 * * This class represents a special nop statement that marks the * beginning of method body at the Jimple level. This is going * to be used in the CFG enhancement. * */ @SuppressWarnings("serial") class EntryStmt extends JNopStmt { public EntryStmt() { } public Object clone() { return new EntryStmt(); } public boolean fallsThrough(){return true;} public boolean branches(){return false;} } /** * * @author Hossein Sadat-Mohtasham * Feb 2010 * * This class represents a special nop statement that marks the * exit of method body at the Jimple level. This is going * to be used in the CFG enhancement. * */ @SuppressWarnings("serial") class ExitStmt extends JNopStmt { public ExitStmt() { } public Object clone() { return new ExitStmt(); } public boolean fallsThrough(){return true;} public boolean branches(){return false;} }
17,519
Java
.java
515
27.978641
105
0.677052
insightfullogic/insightfullogic-soot
3
0
0
LGPL-2.1
9/4/2024, 11:25:38 PM (Europe/Amsterdam)
false
false
false
true
true
true
true
true
17,519
2,866,063
StandardSQLTableManager.java
exoplatform_core/exo.core.component.database/src/main/java/org/exoplatform/services/database/StandardSQLTableManager.java
/* * Copyright (C) 2009 eXo Platform SAS. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.services.database; import org.exoplatform.services.database.annotation.Table; import org.exoplatform.services.database.annotation.TableField; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; /** * Created by The eXo Platform SAS * Author : Tuan Nguyen [email protected] Apr 4, 2006 */ public class StandardSQLTableManager extends DBTableManager { /** * Logger. */ private static final Log LOG = ExoLogger .getLogger("exo.core.component.organization.database.StandardSQLTableManager"); private ExoDatasource exoDatasource; public StandardSQLTableManager(ExoDatasource datasource) { exoDatasource = datasource; } public <T extends DBObject> void createTable(Class<T> type, boolean dropIfExist) throws Exception { Table table = type.getAnnotation(Table.class); if (table == null) { throw new Exception("Cannot find the annotation for class " + type.getClass().getName()); } StringBuilder builder = new StringBuilder(1000); builder.append("CREATE TABLE ").append(table.name()).append(" ("); appendId(builder); TableField[] fields = table.field(); for (int i = 0; i < fields.length; i++) { TableField field = fields[i]; String fieldType = field.type(); if ("string".equals(fieldType)) { appendStringField(field, builder); } else if ("int".equals(fieldType)) { appendIntegerField(field, builder); } else if ("long".equals(fieldType)) { appendLongField(field, builder); } else if ("float".equals(fieldType)) { appendFloatField(field, builder); } else if ("double".equals(fieldType)) { appendDoubleField(field, builder); } else if ("boolean".equals(fieldType)) { appendBooleanField(field, builder); } else if ("date".equals(fieldType)) { appendDateField(field, builder); } else if ("binary".equals(fieldType)) { appendBinaryField(field, builder); } if (i != fields.length - 1) builder.append(", "); } builder.append(")"); // print out the sql string Connection conn = exoDatasource.getConnection(); conn.setAutoCommit(false); Statement statement = conn.createStatement(); LOG.debug("QUERY: \n " + builder + "\n"); if (dropIfExist && hasTable(type)) statement.execute("DROP TABLE IF EXISTS " + table.name()); statement.execute(builder.toString()); statement.close(); conn.commit(); exoDatasource.closeConnection(conn); } public <T extends DBObject> void dropTable(Class<T> type) throws Exception { Table table = type.getAnnotation(Table.class); if (table == null) { throw new Exception("Can not find the annotation for class " + type.getClass().getName()); } Connection conn = exoDatasource.getConnection(); Statement s = conn.createStatement(); s.execute("DROP TABLE " + table.name()); s.close(); conn.commit(); exoDatasource.closeConnection(conn); } public <T extends DBObject> boolean hasTable(Class<T> type) throws Exception { Table table = type.getAnnotation(Table.class); if (table == null) { throw new Exception("Can not find the annotation for class " + type.getClass().getName()); } Connection connection = exoDatasource.getConnection(); Statement statement = connection.createStatement(); try { if (statement.execute("SELECT 1 FROM " + table.name()) == true) return true; } catch (SQLException ex) { return false; } finally { statement.close(); exoDatasource.closeConnection(connection); } return false; } protected void appendId(StringBuilder builder) { builder.append("ID BIGINT NOT NULL PRIMARY KEY, "); } protected void appendStringField(TableField field, StringBuilder builder) throws Exception { if (field.length() < 1) { throw new Exception("You forget to specify the length for field " + field.name() + " , type " + field.type()); } builder.append(field.name()).append(" ").append("VARCHAR(" + field.length() + ")"); if (!field.nullable()) builder.append(" NOT NULL "); } protected void appendIntegerField(TableField field, StringBuilder builder) { builder.append(field.name()).append(" INTEGER"); } protected void appendLongField(TableField field, StringBuilder builder) { builder.append(field.name()).append(" BIGINT"); } protected void appendFloatField(TableField field, StringBuilder builder) { builder.append(field.name()).append(" REAL"); } protected void appendDoubleField(TableField field, StringBuilder builder) { builder.append(field.name()).append(" DOUBLE"); } protected void appendBooleanField(TableField field, StringBuilder builder) { builder.append(field.name()).append(" BIT"); } protected void appendDateField(TableField field, StringBuilder builder) { builder.append(field.name()).append(" DATE"); } protected void appendDateTimeField(TableField field, StringBuilder builder) { builder.append(field.name()).append(" DATETIME"); } protected void appendBinaryField(TableField field, StringBuilder builder) { builder.append(field.name()).append(" VARBINARY"); } }
6,677
Java
.java
191
28.612565
120
0.659706
exoplatform/core
5
27
2
LGPL-3.0
9/4/2024, 10:29:34 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
6,677
4,837,573
FigInclude.java
kopl_misc/JaMoPP Performance Test/testcode/argouml-usecase-variant/src/org/argouml/uml/diagram/use_case/ui/FigInclude.java
//@#$LPS-USECASEDIAGRAM:GranularityType:Package // $Id: FigInclude.java 89 2010-07-31 23:06:12Z marcusvnac $ // Copyright (c) 1996-2009 The Regents of the University of California. All // Rights Reserved. Permission to use, copy, modify, and distribute this // software and its documentation without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph appear in all copies. This software program and // documentation are copyrighted by The Regents of the University of // California. The software program and documentation are supplied "AS // IS", without any accompanying services from The Regents. The Regents // does not warrant that the operation of the program will be // uninterrupted or error-free. The end-user understands that the program // was developed for research purposes and is advised not to rely // exclusively on the program for any reason. IN NO EVENT SHALL THE // UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, // SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, // ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF // THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE // PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF // CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, // UPDATES, ENHANCEMENTS, OR MODIFICATIONS. package org.argouml.uml.diagram.use_case.ui; import java.awt.Graphics; import java.awt.Rectangle; import org.argouml.uml.diagram.DiagramSettings; import org.argouml.uml.diagram.ui.FigEdgeModelElement; import org.argouml.uml.diagram.ui.FigSingleLineText; import org.argouml.uml.diagram.ui.PathItemPlacement; import org.tigris.gef.presentation.ArrowHeadGreater; import org.tigris.gef.presentation.Fig; /** * A fig for use with include relationships on use case diagrams.<p> * * Realised as a dotted line with an open arrow head and the label * <<include>> alongside a la stereotype.<p> * * @author Jeremy Bennett */ public class FigInclude extends FigEdgeModelElement { /** * Serial version - generated by Eclipse for rev. 1.14 */ private static final long serialVersionUID = 6199364390483239154L; /* * Text fig to hold the <<include>> label */ private FigSingleLineText label; private ArrowHeadGreater endArrow = new ArrowHeadGreater(); /** * The default constructor, but should never be called directly (use * {@link #FigInclude(Object, DiagramSettings)}. However we can't * mark it as private, since GEF expects to be able to call this when * creating the diagram. * * @deprecated only for use by PGML parser */ @SuppressWarnings("deprecation") @Deprecated public FigInclude() { label = new FigSingleLineText(X0, Y0 + 20, 90, 20, false); initialize(); } private void initialize() { // The <<include>> label. // It's not a true stereotype, so don't use the stereotype support label.setTextColor(TEXT_COLOR); label.setTextFilled(false); label.setFilled(false); label.setLineWidth(0); label.setEditable(false); label.setText("<<include>>"); addPathItem(label, new PathItemPlacement(this, label, 50, 10)); // Make the line dashed setDashed(true); // Add an arrow with an open arrow head setDestArrowHead(endArrow); // Make the edge go between nearest points setBetweenNearestPoints(true); } /** * <p>The main constructor. Builds the FigEdge required and makes the given * edge object its owner.</p> * * @param edge The edge that will own the fig * @deprecated for 0.27.3 by tfmorris. Use * {@link #FigInclude(Object, DiagramSettings)}. */ @SuppressWarnings("deprecation") @Deprecated public FigInclude(Object edge) { this(); setOwner(edge); } /** * Construct a fig owned by the given UML element with the provided render * settings. * @param edge owning UML element * @param settings rendering settings */ public FigInclude(Object edge, DiagramSettings settings) { super(edge, settings); label = new FigSingleLineText(edge, new Rectangle(X0, Y0 + 20, 90, 20), settings, false); initialize(); } /** * <p>Set a new fig to represent this edge.</p> * * <p>We invoke the superclass accessor. Then change aspects of the * new fig that are not as we want. In this case to use dashed lines.</p> * * @param f The fig to use. */ @Override public void setFig(Fig f) { super.setFig(f); setDashed(true); } /** * <p>Define whether the given fig can be edited (it can't).</p> * * @param f The fig about which the enquiry is being made. Ignored in this * implementation. * * @return <code>false</code> under all circumstances. */ @Override protected boolean canEdit(Fig f) { return false; } /* * @see org.tigris.gef.presentation.Fig#paint(java.awt.Graphics) */ @Override public void paint(Graphics g) { endArrow.setLineColor(getLineColor()); super.paint(g); } }
5,786
Java
.java
142
34.21831
81
0.678636
kopl/misc
1
0
0
EPL-1.0
9/5/2024, 12:33:21 AM (Europe/Amsterdam)
false
false
true
true
false
true
true
true
5,786
1,644,596
BEConnectionManager.java
mru00_jade_agents/src/jade/core/BEConnectionManager.java
/***************************************************************** JADE - Java Agent DEvelopment Framework is a framework to develop multi-agent systems in compliance with the FIPA specifications. Copyright (C) 2000 CSELT S.p.A. GNU Lesser General Public License This library 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, version 2.1 of the License. This library 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 library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *****************************************************************/ package jade.core; //#APIDOC_EXCLUDE_FILE import jade.util.leap.Properties; /** @author Giovanni Caire - TILAB */ public interface BEConnectionManager { /** Return a stub of the remote FrontEnd that is connected to the local BackEnd. @param be The local BackEnd @param props Additional (implementation dependent) connection configuration properties. @return A stub of the remote FrontEnd. */ FrontEnd getFrontEnd(BackEnd be, Properties props) throws IMTPException; /** Shut down the permanent connection to the remote FrontEnd */ void shutdown(); }
1,643
Java
.java
39
38.282051
74
0.703797
mru00/jade_agents
11
9
0
LGPL-2.1
9/4/2024, 8:11:13 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
1,643
431,288
EnumAttributePropertyType.java
eclipse_vorto/model/src/main/java/org/eclipse/vorto/model/EnumAttributePropertyType.java
/** * Copyright (c) 2020 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * https://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.eclipse.vorto.model; public enum EnumAttributePropertyType { MEASUREMENT_UNIT }
506
Java
.java
16
29.6875
75
0.782787
eclipse/vorto
225
106
175
EPL-2.0
9/4/2024, 7:07:11 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
506
1,319,034
A_test722.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/return_in/A_test722.java
package return_in; public class A_test722 { void f(){ for (int i = 0; i < 10; i++) { /*[*/for (int j = 0; j < 10; j++) { }/*]*/ } } }
147
Java
.java
9
13.888889
38
0.459854
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
147
1,317,544
A_test11_out.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/InlineTemp/canInline/A_test11_out.java
package p; class A { boolean d; public void test() { boolean t= (d); } }
78
Java
.java
7
9.428571
21
0.625
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
78
2,592,995
LineMap.java
JPortal-system_system/jdk12-06222165c35f/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/tree/LineMap.java
/* * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.nashorn.api.tree; /** * Provides methods to convert between character positions and line numbers * for a compilation unit. * * @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool * are deprecated with the intent to remove them in a future release. * * @since 9 */ @Deprecated(since="11", forRemoval=true) public interface LineMap { /** * Find the line containing a position; a line termination * character is on the line it terminates. * * @param pos character offset of the position * @return the line number of pos (first line is 1) */ long getLineNumber(long pos); /** * Find the column for a character position. * Tab characters preceding the position on the same line * will be expanded when calculating the column number. * * @param pos character offset of the position * @return the tab-expanded column number of pos (first column is 1) */ long getColumnNumber(long pos); }
2,224
Java
.java
54
38.055556
78
0.737886
JPortal-system/system
7
2
1
GPL-3.0
9/4/2024, 9:49:36 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
2,224
1,316,021
InitializerProblem.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractClass/testInitializerProblem/out/InitializerProblem.java
/******************************************************************************* * Copyright (c) 2007 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package p; import java.util.ArrayList; class A { public int foo() { return 5; } } public class InitializerProblem extends A{ public InitializerProblemParameter parameterObject = new InitializerProblemParameter(foo(), new ArrayList()); }
796
Java
.java
23
32.782609
110
0.612192
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
796
79,049
GameMessageCommandFactory.java
jwpttcg66_NettyGameServer/game-code-generate/src/main/java/com/snowcattle/game/service/net/GameMessageCommandFactory.java
package com.snowcattle.game.service.net; import com.snowcattle.game.service.message.command.MessageCommand; import com.snowcattle.game.service.message.command.MessageCommandFactory; import org.springframework.stereotype.Service; /** * Created by jiangwenping on 2017/5/10. */ @Service public class GameMessageCommandFactory extends MessageCommandFactory { public MessageCommand[] getAllCommands(){ MessageCommand[] messageCommands = super.getAllCommands(); GameMessageCommandEnum[] set = GameMessageCommandEnum.values(); MessageCommand[] gameMessageCommands = new MessageCommand[set.length]; for(int i = 0; i < set.length; ++i) { GameMessageCommandEnum gameMessageCommandEnum = set[i]; MessageCommand messageCommand = new MessageCommand(gameMessageCommandEnum.command_id, gameMessageCommandEnum.bo_id, gameMessageCommandEnum.is_need_filter); gameMessageCommands[i] = messageCommand; } MessageCommand[] result = new MessageCommand[messageCommands.length + gameMessageCommands.length]; System.arraycopy(messageCommands, 0, result, 0, messageCommands.length); System.arraycopy(gameMessageCommands, 0, result, messageCommands.length, gameMessageCommands.length); return result; } }
1,299
Java
.java
24
48.083333
167
0.763365
jwpttcg66/NettyGameServer
1,597
670
3
GPL-3.0
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
false
false
false
true
true
false
true
true
1,299
4,132,424
SlideMenuItem.java
lucastanziano_Blockbuster/sidemenu/src/main/java/yalantis/com/sidemenu/model/SlideMenuItem.java
package yalantis.com.sidemenu.model; import yalantis.com.sidemenu.interfaces.Resourceble; /** * Created by Konstantin on 23.12.2014. */ public class SlideMenuItem implements Resourceble { private String name; private int imageRes; public SlideMenuItem(String name, int imageRes) { this.name = name; this.imageRes = imageRes; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getImageRes() { return imageRes; } public void setImageRes(int imageRes) { this.imageRes = imageRes; } }
644
Java
.java
25
20.56
53
0.673203
lucastanziano/Blockbuster
2
0
0
GPL-2.0
9/5/2024, 12:03:50 AM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
644
1,316,930
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/PushDown/testVisibility3/out/A.java
package p; class A { static class T{} } class B extends A { public T f() { return new T(); } }
101
Java
.java
9
9.555556
19
0.637363
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
101
1,701,640
DynamicTheme.java
CyanogenMod_android_external_whispersystems_TextSecure/src/org/thoughtcrime/securesms/util/DynamicTheme.java
package org.thoughtcrime.securesms.util; import android.app.Activity; import android.content.Intent; import android.os.Build; import android.preference.PreferenceManager; import org.thoughtcrime.securesms.ApplicationPreferencesActivity; import org.thoughtcrime.securesms.ConversationListActivity; import org.thoughtcrime.securesms.R; public class DynamicTheme { private int currentTheme; public void onCreate(Activity activity) { currentTheme = getSelectedTheme(activity); activity.setTheme(currentTheme); } public void onResume(Activity activity) { if (currentTheme != getSelectedTheme(activity)) { Intent intent = activity.getIntent(); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); activity.startActivity(intent); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) { OverridePendingTransition.invoke(activity); } activity.finish(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) { OverridePendingTransition.invoke(activity); } } } private static int getSelectedTheme(Activity activity) { String theme = TextSecurePreferences.getTheme(activity); if (theme.equals("light")) { if (activity instanceof ConversationListActivity) return R.style.TextSecure_LightTheme_NavigationDrawer; else return R.style.TextSecure_LightTheme; } else if (theme.equals("dark")) { if (activity instanceof ConversationListActivity) return R.style.TextSecure_DarkTheme_NavigationDrawer; else return R.style.TextSecure_DarkTheme; } return R.style.TextSecure_LightTheme; } private static final class OverridePendingTransition { static void invoke(Activity activity) { activity.overridePendingTransition(0, 0); } } }
1,871
Java
.java
45
36.822222
110
0.726972
CyanogenMod/android_external_whispersystems_TextSecure
11
9
0
GPL-3.0
9/4/2024, 8:15:17 PM (Europe/Amsterdam)
false
false
true
true
false
true
false
true
1,871
4,041,853
UriTemplate.java
deathspeeder_class-guard/apache-tomcat-7.0.53-src/java/org/apache/tomcat/websocket/server/UriTemplate.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.websocket.server; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.websocket.DeploymentException; import org.apache.tomcat.util.res.StringManager; /** * Extracts path parameters from URIs used to create web socket connections * using the URI template defined for the associated Endpoint. */ public class UriTemplate { private static final StringManager sm = StringManager.getManager(Constants.PACKAGE_NAME); private final String normalized; private final List<Segment> segments = new ArrayList<Segment>(); private final boolean hasParameters; public UriTemplate(String path) throws DeploymentException { if (path == null || path.length() ==0 || !path.startsWith("/")) { throw new DeploymentException( sm.getString("uriTemplate.invalidPath", path)); } StringBuilder normalized = new StringBuilder(path.length()); Set<String> paramNames = new HashSet<String>(); // Include empty segments. String[] segments = path.split("/", -1); int paramCount = 0; int segmentCount = 0; for (int i = 0; i < segments.length; i++) { String segment = segments[i]; if (segment.length() == 0) { if (i == 0 || (i == segments.length - 1 && paramCount == 0)) { // Ignore the first empty segment as the path must always // start with '/' // Ending with a '/' is also OK for instances used for // matches but not for parameterised templates. continue; } else { // As per EG discussion, all other empty segments are // invalid throw new IllegalArgumentException(sm.getString( "uriTemplate.emptySegment", path)); } } normalized.append('/'); int index = -1; if (segment.startsWith("{") && segment.endsWith("}")) { index = segmentCount; segment = segment.substring(1, segment.length() - 1); normalized.append('{'); normalized.append(paramCount++); normalized.append('}'); if (!paramNames.add(segment)) { throw new IllegalArgumentException(sm.getString( "uriTemplate.duplicateParameter", segment)); } } else { if (segment.contains("{") || segment.contains("}")) { throw new IllegalArgumentException(sm.getString( "uriTemplate.invalidSegment", segment, path)); } normalized.append(segment); } this.segments.add(new Segment(index, segment)); segmentCount++; } this.normalized = normalized.toString(); this.hasParameters = paramCount > 0; } public Map<String,String> match(UriTemplate candidate) { Map<String,String> result = new HashMap<String, String>(); // Should not happen but for safety if (candidate.getSegmentCount() != getSegmentCount()) { return null; } Iterator<Segment> candidateSegments = candidate.getSegments().iterator(); Iterator<Segment> targetSegments = segments.iterator(); while (candidateSegments.hasNext()) { Segment candidateSegment = candidateSegments.next(); Segment targetSegment = targetSegments.next(); if (targetSegment.getParameterIndex() == -1) { // Not a parameter - values must match if (!targetSegment.getValue().equals( candidateSegment.getValue())) { // Not a match. Stop here return null; } } else { // Parameter result.put(targetSegment.getValue(), candidateSegment.getValue()); } } return result; } public boolean hasParameters() { return hasParameters; } public int getSegmentCount() { return segments.size(); } public String getNormalizedPath() { return normalized; } private List<Segment> getSegments() { return segments; } private static class Segment { private final int parameterIndex; private final String value; public Segment(int parameterIndex, String value) { this.parameterIndex = parameterIndex; this.value = value; } public int getParameterIndex() { return parameterIndex; } public String getValue() { return value; } } }
5,854
Java
.java
142
30.71831
78
0.596195
deathspeeder/class-guard
2
2
0
GPL-2.0
9/5/2024, 12:00:55 AM (Europe/Amsterdam)
true
true
true
true
true
true
true
true
5,854
1,313,660
PluginTransferDropAdapter.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PluginTransferDropAdapter.java
/******************************************************************************* * Copyright (c) 2000, 2008 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.packageview; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.Transfer; import org.eclipse.jface.util.TransferDropTargetListener; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.ui.part.PluginDropAdapter; import org.eclipse.ui.part.PluginTransfer; public class PluginTransferDropAdapter extends PluginDropAdapter implements TransferDropTargetListener { public PluginTransferDropAdapter(StructuredViewer viewer) { super(viewer); setFeedbackEnabled(false); } @Override public Transfer getTransfer() { return PluginTransfer.getInstance(); } @Override public boolean isEnabled(DropTargetEvent event) { return PluginTransfer.getInstance().isSupportedType(event.currentDataType); } }
1,340
Java
.java
34
37.352941
104
0.717257
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
1,340
2,280,201
BatchSQLJob.java
huang-up_mycat-src-1_6_1-RELEASE/src/main/java/io/mycat/sqlengine/BatchSQLJob.java
package io.mycat.sqlengine; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import io.mycat.MycatServer; public class BatchSQLJob { private ConcurrentHashMap<Integer, SQLJob> runningJobs = new ConcurrentHashMap<Integer, SQLJob>(); private ConcurrentLinkedQueue<SQLJob> waitingJobs = new ConcurrentLinkedQueue<SQLJob>(); private volatile boolean noMoreJobInput = false; public void addJob(SQLJob newJob, boolean parallExecute) { if (parallExecute) { runJob(newJob); } else { waitingJobs.offer(newJob); if (runningJobs.isEmpty()) { SQLJob job = waitingJobs.poll(); if (job != null) { runJob(job); } } } } public void setNoMoreJobInput(boolean noMoreJobInput) { this.noMoreJobInput = noMoreJobInput; } private void runJob(SQLJob newJob) { // EngineCtx.LOGGER.info("run job " + newJob); runningJobs.put(newJob.getId(), newJob); MycatServer.getInstance().getBusinessExecutor().execute(newJob); } public boolean jobFinished(SQLJob sqlJob) { if (EngineCtx.LOGGER.isDebugEnabled()) { EngineCtx.LOGGER.info("job finished " + sqlJob); } runningJobs.remove(sqlJob.getId()); SQLJob job = waitingJobs.poll(); if (job != null) { runJob(job); return false; } else { if (noMoreJobInput) { return runningJobs.isEmpty() && waitingJobs.isEmpty(); } else { return false; } } } }
1,413
Java
.java
47
26.851064
99
0.738201
huang-up/mycat-src-1.6.1-RELEASE
9
2
0
GPL-2.0
9/4/2024, 8:49:28 PM (Europe/Amsterdam)
true
true
true
true
true
true
true
true
1,413
434,867
DdsTexture.java
Retera_WarsmashModEngine/core/src/com/etheller/warsmash/viewer5/handlers/blp/DdsTexture.java
package com.etheller.warsmash.viewer5.handlers.blp; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; import com.etheller.warsmash.viewer5.ModelViewer; import com.etheller.warsmash.viewer5.PathSolver; import com.etheller.warsmash.viewer5.RawOpenGLTextureResource; import com.etheller.warsmash.viewer5.handlers.ResourceHandler; public class DdsTexture extends RawOpenGLTextureResource { public DdsTexture(final ModelViewer viewer, final ResourceHandler handler, final String extension, final PathSolver pathSolver, final String fetchUrl) { super(viewer, extension, pathSolver, fetchUrl, handler); } @Override protected void lateLoad() { } @Override protected void load(final InputStream src, final Object options) { BufferedImage img; try { img = ImageIO.read(src); update(img, false); } catch (final IOException e) { throw new RuntimeException(e); } } }
967
Java
.java
29
30.965517
99
0.812903
Retera/WarsmashModEngine
224
39
25
AGPL-3.0
9/4/2024, 7:07:11 PM (Europe/Amsterdam)
false
false
false
true
true
false
true
true
967
1,318,914
A_test760.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/branch_in/A_test760.java
package branch_in; public class A_test760 { public void foo(int a) { /*[*/ do { if(a == 3) { continue; } System.out.println(); } while (a > 0); /*]*/ } }
180
Java
.java
13
10.846154
25
0.536585
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
180
4,534,601
TimeBarChart.java
vitelabs_vite-wallet-android/MPChartLib/src/main/java/com/github/mikephil/charting/stockChart/charts/TimeBarChart.java
package com.github.mikephil.charting.stockChart.charts; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.highlight.Highlight; import com.github.mikephil.charting.interfaces.datasets.IDataSet; import com.github.mikephil.charting.stockChart.dataManage.TimeDataManage; import com.github.mikephil.charting.stockChart.markerView.BarBottomMarkerView; import com.github.mikephil.charting.stockChart.renderer.TimeBarChartRenderer; import com.github.mikephil.charting.stockChart.renderer.TimeXAxisRenderer; import com.github.mikephil.charting.utils.DataTimeUtil; public class TimeBarChart extends BarChart { private BarBottomMarkerView markerBottom; private TimeDataManage kTimeData; public TimeBarChart(Context context) { super(context); } public TimeBarChart(Context context, AttributeSet attrs) { super(context, attrs); } public TimeBarChart(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } /** * @param markerBottom * @param kTimeData */ public void setMarker(BarBottomMarkerView markerBottom, TimeDataManage kTimeData) { this.markerBottom = markerBottom; this.kTimeData = kTimeData; } @Override public void initMyBarRenderer() {//调用自己的渲染器 mRenderer = new TimeBarChartRenderer(this, mAnimator, mViewPortHandler); } @Override protected void initXAxisRenderer() { mXAxisRenderer = new TimeXAxisRenderer(mViewPortHandler, (TimeXAxis) mXAxis, mLeftAxisTransformer, this); } @Override public void initXAxis() { mXAxis = new TimeXAxis(); } @Override protected void drawMarkers(Canvas canvas) { // if there is no marker view or drawing marker is disabled if (!isDrawMarkersEnabled() || !valuesToHighlight()) { return; } for (int i = 0; i < mIndicesToHighlight.length; i++) { Highlight highlight = mIndicesToHighlight[i]; IDataSet set = mData.getDataSetByIndex(highlight.getDataSetIndex()); Entry e = mData.getEntryForHighlight(mIndicesToHighlight[i]); int entryIndex = set.getEntryIndex(e); // make sure entry not null if (e == null || entryIndex > set.getEntryCount() * mAnimator.getPhaseX()) { continue; } float[] pos = getMarkerPosition(highlight); // check bounds if (!mViewPortHandler.isInBounds(pos[0], pos[1])) { continue; } String date = ""; date = DataTimeUtil.secToTime(kTimeData.getDatas().get((int) e.getX()).getTimeMills());//分时图显示的数据 markerBottom.setData(date); markerBottom.refreshContent(e, highlight); markerBottom.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); markerBottom.layout(0, 0, markerBottom.getMeasuredWidth(), markerBottom.getMeasuredHeight()); int width = markerBottom.getWidth() / 2; if (mViewPortHandler.contentRight() - pos[0] <= width) { markerBottom.draw(canvas, mViewPortHandler.contentRight() - markerBottom.getWidth() / 2, mViewPortHandler.contentBottom() + markerBottom.getHeight());//-markerBottom.getHeight() CommonUtil.dip2px(getContext(),65.8f) } else if (pos[0] - mViewPortHandler.contentLeft() <= width) { markerBottom.draw(canvas, mViewPortHandler.contentLeft() + markerBottom.getWidth() / 2, mViewPortHandler.contentBottom() + markerBottom.getHeight()); } else { markerBottom.draw(canvas, pos[0], mViewPortHandler.contentBottom() + markerBottom.getHeight()); } // callbacks to update the content // mMarker.refreshContent(e, highlight); // draw the marker // mMarker.draw(canvas, pos[0], pos[1]); } } /*返回转型后的左右轴*/ // public void setHighlightValue(Highlight h) { // if (mData == null) // mIndicesToHighlight = null; // else { // mIndicesToHighlight = new Highlight[]{h}; // } // invalidate(); // } // protected void drawMarkers(Canvas canvas) { // // if there is no marker view or drawing marker is disabled // if (!isDrawMarkersEnabled() || !valuesToHighlight()) // return; // // for (int i = 0; i < mIndicesToHighlight.length; i++) { // // Highlight highlight = mIndicesToHighlight[i]; // // IDataSet set = mData.getDataSetByIndex(highlight.getDataSetIndex()); // // Entry e = mData.getEntryForHighlight(mIndicesToHighlight[i]); // int entryIndex = set.getEntryIndex(e); // // // make sure entry not null // if (e == null || entryIndex > set.getEntryCount() * mAnimator.getPhaseX()) // continue; // // float[] pos = getMarkerPosition(highlight); // // // check bounds // if (!mViewPortHandler.isInBounds(pos[0], pos[1])) // continue; // // // callbacks to update the content // String date = ""; // if(kLineData == null){//区分应该显示什么数据 // date = DataTimeUtil.secToTime(minuteHelper.getDatas().get((int) e.getX()).m_nUpdateTime);//分时图显示的数据 // }else{ // if(this.type == 0){//0表示显示时间 // date = DataTimeUtil.secToTime(kLineData.getKLineDatas().get((int) e.getX()).m_nStartTime);//K线中显示的数据 // }else{//1表示显示日期 // date = kLineData.getKLineDatas().get((int) e.getX()).m_szDate;//K线中显示的数据 // } // } // markerBottom.setData(date); // markerBottom.refreshContent(e, highlight); // markerBottom.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); // markerBottom.layout(0, 0, markerBottom.getMeasuredWidth(), markerBottom.getMeasuredHeight()); // // int width = markerBottom.getWidth()/2; // if(mViewPortHandler.contentRight() - pos[0] <= width){ // markerBottom.draw(canvas, mViewPortHandler.contentRight() - markerBottom.getWidth(), mViewPortHandler.contentBottom());//-markerBottom.getHeight() CommonUtil.dip2px(getContext(),65.8f) // }else if(pos[0] - mViewPortHandler.contentLeft() <= width){ // markerBottom.draw(canvas, mViewPortHandler.contentLeft(), mViewPortHandler.contentBottom()); // }else{ // markerBottom.draw(canvas, pos[0] - width, mViewPortHandler.contentBottom()); // } // // // callbacks to update the content //// mMarker.refreshContent(e, highlight); // // // draw the marker //// mMarker.draw(canvas, pos[0], pos[1]); // } // } }
7,304
Java
.java
151
42.337748
233
0.641385
vitelabs/vite-wallet-android
2
0
0
GPL-3.0
9/5/2024, 12:16:26 AM (Europe/Amsterdam)
false
false
false
true
true
false
true
true
7,166
1,118,820
InputMeta.java
SemanticBeeng_jpdfbookmarks/iText-2.1.7-patched/src/core/com/lowagie/text/pdf/codec/wmf/InputMeta.java
/* * $Id: InputMeta.java 3373 2008-05-12 16:21:24Z xlv $ * * Copyright 2001, 2002 Paulo Soares * * The contents of this file are subject to the Mozilla Public License Version 1.1 * (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the License. * * The Original Code is 'iText, a free JAVA-PDF library'. * * The Initial Developer of the Original Code is Bruno Lowagie. Portions created by * the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie. * All Rights Reserved. * Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer * are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved. * * Contributor(s): all the names of the contributors are added in the source code * where applicable. * * Alternatively, the contents of this file may be used under the terms of the * LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the * provisions of LGPL are applicable instead of those above. If you wish to * allow use of your version of this file only under the terms of the LGPL * License and not to allow others to use your version of this file under * the MPL, indicate your decision by deleting the provisions above and * replace them with the notice and other provisions required by the LGPL. * If you do not delete the provisions above, a recipient may use your version * of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE. * * This library is free software; you can redistribute it and/or modify it * under the terms of the MPL as stated above or under the terms of the GNU * Library General Public License as published by the Free Software Foundation; * either version 2 of the License, or any later version. * * This library 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 Library general Public License for more * details. * * If you didn't download this code from the following link, you should check if * you aren't using an obsolete version: * http://www.lowagie.com/iText/ */ package com.lowagie.text.pdf.codec.wmf; import java.awt.Color; import java.io.IOException; import java.io.InputStream; import com.lowagie.text.Utilities; public class InputMeta { InputStream in; int length; public InputMeta(InputStream in) { this.in = in; } public int readWord() throws IOException{ length += 2; int k1 = in.read(); if (k1 < 0) return 0; return (k1 + (in.read() << 8)) & 0xffff; } public int readShort() throws IOException{ int k = readWord(); if (k > 0x7fff) k -= 0x10000; return k; } public int readInt() throws IOException{ length += 4; int k1 = in.read(); if (k1 < 0) return 0; int k2 = in.read() << 8; int k3 = in.read() << 16; return k1 + k2 + k3 + (in.read() << 24); } public int readByte() throws IOException{ ++length; return in.read() & 0xff; } public void skip(int len) throws IOException{ length += len; Utilities.skip(in, len); } public int getLength() { return length; } public Color readColor() throws IOException{ int red = readByte(); int green = readByte(); int blue = readByte(); readByte(); return new Color(red, green, blue); } }
3,905
Java
.java
100
34.21
84
0.692941
SemanticBeeng/jpdfbookmarks
41
5
2
GPL-3.0
9/4/2024, 7:11:02 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
3,905
116,094
BooleanInversionCheck.java
SonarSource_sonar-java/java-checks/src/test/files/checks/BooleanInversionCheck.java
class A { int a = 0; int i = 0; private void noncompliant() { if ( !(a == 2)) { } // Noncompliant {{Use the opposite operator ("!=") instead.}} // ^^^^^^^^^ boolean b = !(i < 10); // Noncompliant {{Use the opposite operator (">=") instead.}} b = !(i > 10); // Noncompliant {{Use the opposite operator ("<=") instead.}} b = !(i != 10); // Noncompliant {{Use the opposite operator ("==") instead.}} // ^^^^^^^^^^ b = !(i <= 10); // Noncompliant {{Use the opposite operator (">") instead.}} b = !(i >= 10); // Noncompliant {{Use the opposite operator ("<") instead.}} } private void compliant() { if (a != 2) { } boolean b = (i >= 10); b = !(a + i); } }
714
Java
.java
19
33.842105
88
0.512301
SonarSource/sonar-java
1,111
676
20
LGPL-3.0
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
false
false
true
true
false
true
false
true
714
3,848,559
FixedWidthPanel.java
Elvarg-Community_Elvarg-Client-Public/src/main/java/net/runelite/client/plugins/config/FixedWidthPanel.java
/* * Copyright (c) 2017, Adam <[email protected]> * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.client.plugins.config; import java.awt.Dimension; import javax.swing.JPanel; import net.runelite.client.ui.PluginPanel; class FixedWidthPanel extends JPanel { @Override public Dimension getPreferredSize() { return new Dimension(PluginPanel.PANEL_WIDTH, super.getPreferredSize().height); } }
1,701
Java
.java
36
45.361111
82
0.791817
Elvarg-Community/Elvarg-Client-Public
3
10
2
GPL-3.0
9/4/2024, 11:45:14 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
1,701
1,319,050
A_test552.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/locals_in/A_test552.java
package locals_in; public class A_test552 { public void foo() { int i= 0; for (;true;) { /*[*/i++;/*]*/ } } }
124
Java
.java
9
11.222222
24
0.535714
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
124
4,058,479
GeoUtils.java
RoProducts_rastertheque/MapboxLibrary/src/com/mapbox/mapboxsdk/util/GeoUtils.java
package com.mapbox.mapboxsdk.util; import com.mapbox.mapboxsdk.geometry.BoundingBox; import com.mapbox.mapboxsdk.geometry.LatLng; import java.util.List; public class GeoUtils { /** * Build a BoundingBox for a List of LatLng * @param coordinates List of coordinates * @param padding Option padding. Recommended 0.01. Send in null to have no padding applied * @return BoundingBox containing the given List of LatLng */ public static BoundingBox findBoundingBoxForGivenLocations(List<LatLng> coordinates, Double padding) { double west = 0.0; double east = 0.0; double north = 0.0; double south = 0.0; for (int lc = 0; lc < coordinates.size(); lc++) { LatLng loc = coordinates.get(lc); if (lc == 0) { north = loc.getLatitude(); south = loc.getLatitude(); west = loc.getLongitude(); east = loc.getLongitude(); } else { if (loc.getLatitude() > north) { north = loc.getLatitude(); } else if (loc.getLatitude() < south) { south = loc.getLatitude(); } if (loc.getLongitude() < west) { west = loc.getLongitude(); } else if (loc.getLongitude() > east) { east = loc.getLongitude(); } } } // OPTIONAL - Add some extra "padding" for better map display if (padding != null) { north = north + padding; south = south - padding; west = west - padding; east = east + padding; } return new BoundingBox(north, east, south, west); } }
1,775
Java
.java
46
27.586957
106
0.544135
RoProducts/rastertheque
2
4
0
GPL-2.0
9/5/2024, 12:01:24 AM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
1,775
3,183,338
JournalTransactionMarshaller.java
DiamondLightSource_daq-eclipse/uk.ac.diamond.org.apache.activemq/org/apache/activemq/openwire/v4/JournalTransactionMarshaller.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.openwire.v4; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Marshalling code for Open Wire Format for JournalTransactionMarshaller * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class JournalTransactionMarshaller extends BaseDataStreamMarshaller { /** * Return the type of Data Structure we marshal * @return short representation of the type data structure */ public byte getDataStructureType() { return JournalTransaction.DATA_STRUCTURE_TYPE; } /** * @return a new object instance */ public DataStructure createObject() { return new JournalTransaction(); } /** * Un-marshal an object instance from the data input stream * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); JournalTransaction info = (JournalTransaction)o; info.setTransactionId((org.apache.activemq.command.TransactionId) tightUnmarsalNestedObject(wireFormat, dataIn, bs)); info.setType(dataIn.readByte()); info.setWasPrepared(bs.readBoolean()); } /** * Write the booleans that this object uses to a BooleanStream */ public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException { JournalTransaction info = (JournalTransaction)o; int rc = super.tightMarshal1(wireFormat, o, bs); rc += tightMarshalNestedObject1(wireFormat, (DataStructure)info.getTransactionId(), bs); bs.writeBoolean(info.getWasPrepared()); return rc + 1; } /** * Write a object instance to data output stream * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); JournalTransaction info = (JournalTransaction)o; tightMarshalNestedObject2(wireFormat, (DataStructure)info.getTransactionId(), dataOut, bs); dataOut.writeByte(info.getType()); bs.readBoolean(); } /** * Un-marshal an object instance from the data input stream * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ public void looseUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn) throws IOException { super.looseUnmarshal(wireFormat, o, dataIn); JournalTransaction info = (JournalTransaction)o; info.setTransactionId((org.apache.activemq.command.TransactionId) looseUnmarsalNestedObject(wireFormat, dataIn)); info.setType(dataIn.readByte()); info.setWasPrepared(dataIn.readBoolean()); } /** * Write the booleans that this object uses to a BooleanStream */ public void looseMarshal(OpenWireFormat wireFormat, Object o, DataOutput dataOut) throws IOException { JournalTransaction info = (JournalTransaction)o; super.looseMarshal(wireFormat, o, dataOut); looseMarshalNestedObject(wireFormat, (DataStructure)info.getTransactionId(), dataOut); dataOut.writeByte(info.getType()); dataOut.writeBoolean(info.getWasPrepared()); } }
4,772
Java
.java
111
37.540541
125
0.723758
DiamondLightSource/daq-eclipse
4
9
3
EPL-1.0
9/4/2024, 11:03:38 PM (Europe/Amsterdam)
false
true
true
true
true
true
true
true
4,772
660,726
TenantController.java
LoveMyOrange_ding-flowable-vue2-enhance/YuDao/Camunda/ruoyi-vue-pro/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/tenant/TenantController.java
package cn.iocoder.yudao.module.system.controller.admin.tenant; import cn.iocoder.yudao.framework.common.pojo.CommonResult; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils; import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog; import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.*; import cn.iocoder.yudao.module.system.convert.tenant.TenantConvert; import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantDO; import cn.iocoder.yudao.module.system.service.tenant.TenantService; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Operation; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.annotation.security.PermitAll; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.io.IOException; import java.util.List; import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success; import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT; @Tag(name = "管理后台 - 租户") @RestController @RequestMapping("/system/tenant") public class TenantController { @Resource private TenantService tenantService; @GetMapping("/get-id-by-name") @PermitAll @Operation(summary = "使用租户名,获得租户编号", description = "登录界面,根据用户的租户名,获得租户编号") @Parameter(name = "name", description = "租户名", required = true, example = "1024") public CommonResult<Long> getTenantIdByName(@RequestParam("name") String name) { TenantDO tenantDO = tenantService.getTenantByName(name); return success(tenantDO != null ? tenantDO.getId() : null); } @PostMapping("/create") @Operation(summary = "创建租户") @PreAuthorize("@ss.hasPermission('system:tenant:create')") public CommonResult<Long> createTenant(@Valid @RequestBody TenantCreateReqVO createReqVO) { return success(tenantService.createTenant(createReqVO)); } @PutMapping("/update") @Operation(summary = "更新租户") @PreAuthorize("@ss.hasPermission('system:tenant:update')") public CommonResult<Boolean> updateTenant(@Valid @RequestBody TenantUpdateReqVO updateReqVO) { tenantService.updateTenant(updateReqVO); return success(true); } @DeleteMapping("/delete") @Operation(summary = "删除租户") @Parameter(name = "id", description = "编号", required = true, example = "1024") @PreAuthorize("@ss.hasPermission('system:tenant:delete')") public CommonResult<Boolean> deleteTenant(@RequestParam("id") Long id) { tenantService.deleteTenant(id); return success(true); } @GetMapping("/get") @Operation(summary = "获得租户") @Parameter(name = "id", description = "编号", required = true, example = "1024") @PreAuthorize("@ss.hasPermission('system:tenant:query')") public CommonResult<TenantRespVO> getTenant(@RequestParam("id") Long id) { TenantDO tenant = tenantService.getTenant(id); return success(TenantConvert.INSTANCE.convert(tenant)); } @GetMapping("/page") @Operation(summary = "获得租户分页") @PreAuthorize("@ss.hasPermission('system:tenant:query')") public CommonResult<PageResult<TenantRespVO>> getTenantPage(@Valid TenantPageReqVO pageVO) { PageResult<TenantDO> pageResult = tenantService.getTenantPage(pageVO); return success(TenantConvert.INSTANCE.convertPage(pageResult)); } @GetMapping("/export-excel") @Operation(summary = "导出租户 Excel") @PreAuthorize("@ss.hasPermission('system:tenant:export')") @OperateLog(type = EXPORT) public void exportTenantExcel(@Valid TenantExportReqVO exportReqVO, HttpServletResponse response) throws IOException { List<TenantDO> list = tenantService.getTenantList(exportReqVO); // 导出 Excel List<TenantExcelVO> datas = TenantConvert.INSTANCE.convertList02(list); ExcelUtils.write(response, "租户.xls", "数据", TenantExcelVO.class, datas); } }
4,320
Java
.java
84
44.642857
98
0.748771
LoveMyOrange/ding-flowable-vue2-enhance
114
11
1
GPL-3.0
9/4/2024, 7:08:18 PM (Europe/Amsterdam)
false
false
false
true
false
false
true
true
4,166
4,530,661
EqualityHelper.java
RL4MT_RL4MT/plugins/at.ac.tuwien.big.momot.lang/src-gen/at/ac/tuwien/big/momot/lang/momot/EqualityHelper.java
/** */ package at.ac.tuwien.big.momot.lang.momot; import org.eclipse.emf.ecore.EObject; import org.eclipse.xtext.xbase.XExpression; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Equality Helper</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link at.ac.tuwien.big.momot.lang.momot.EqualityHelper#getCall <em>Call</em>}</li> * <li>{@link at.ac.tuwien.big.momot.lang.momot.EqualityHelper#getMethod <em>Method</em>}</li> * </ul> * * @see at.ac.tuwien.big.momot.lang.momot.MomotPackage#getEqualityHelper() * @model * @generated */ public interface EqualityHelper extends EObject { /** * Returns the value of the '<em><b>Call</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Call</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Call</em>' containment reference. * @see #setCall(XExpression) * @see at.ac.tuwien.big.momot.lang.momot.MomotPackage#getEqualityHelper_Call() * @model containment="true" * @generated */ XExpression getCall(); /** * Sets the value of the '{@link at.ac.tuwien.big.momot.lang.momot.EqualityHelper#getCall <em>Call</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Call</em>' containment reference. * @see #getCall() * @generated */ void setCall(XExpression value); /** * Returns the value of the '<em><b>Method</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Method</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Method</em>' containment reference. * @see #setMethod(XExpression) * @see at.ac.tuwien.big.momot.lang.momot.MomotPackage#getEqualityHelper_Method() * @model containment="true" * @generated */ XExpression getMethod(); /** * Sets the value of the '{@link at.ac.tuwien.big.momot.lang.momot.EqualityHelper#getMethod <em>Method</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Method</em>' containment reference. * @see #getMethod() * @generated */ void setMethod(XExpression value); } // EqualityHelper
2,541
Java
.java
73
31.616438
134
0.661926
RL4MT/RL4MT
2
0
0
EPL-2.0
9/5/2024, 12:16:15 AM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
2,541
119,466
MissingNewLineAtEndOfFile.java
SonarSource_sonar-java/java-checks-test-sources/default/src/main/java/checks/MissingNewLineAtEndOfFile.java
package checks; class MissingNewlineAtEndOfFile { } // Noncompliant@0 {{Add a new line at the end of this file.}}
114
Java
.java
4
27.5
61
0.772727
SonarSource/sonar-java
1,111
676
20
LGPL-3.0
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
114
1,319,159
A_test982.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/duplicates_in/A_test982.java
package duplicates_in; public class A_test982 { A_test982 c; int x; int f(){ return /*[*/x/*]*/; } void g() { c.x= 1; } }
133
Java
.java
11
10.090909
24
0.578512
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
133
1,320,339
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/PullUp/test32/out/A.java
package p; abstract class A{ public abstract int m(); } class B extends A{ @Override public int m() { return 2 +3; } } class C extends A{ @Override public int m() { // TODO Auto-generated method stub return 0; } }
228
Java
.java
17
11.588235
36
0.695238
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
false
true
true
true
true
true
228
2,417,981
ShaderOptionVariable.java
dotexe1337_bdsm-client-1_16/src/main/java/net/optifine/shaders/config/ShaderOptionVariable.java
package net.optifine.shaders.config; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.optifine.Config; import net.optifine.shaders.Shaders; import net.optifine.util.StrUtils; public class ShaderOptionVariable extends ShaderOption { private static final Pattern PATTERN_VARIABLE = Pattern.compile("^\\s*#define\\s+(\\w+)\\s+(-?[0-9\\.Ff]+|\\w+)\\s*(//.*)?$"); public ShaderOptionVariable(String name, String description, String value, String[] values, String path) { super(name, description, value, values, value, path); this.setVisible(this.getValues().length > 1); } public String getSourceLine() { return "#define " + this.getName() + " " + this.getValue() + " // Shader option " + this.getValue(); } public String getValueText(String val) { String s = Shaders.translate("prefix." + this.getName(), ""); String s1 = super.getValueText(val); String s2 = Shaders.translate("suffix." + this.getName(), ""); return s + s1 + s2; } public String getValueColor(String val) { String s = val.toLowerCase(); return !s.equals("false") && !s.equals("off") ? "\u00a7a" : "\u00a7c"; } public boolean matchesLine(String line) { Matcher matcher = PATTERN_VARIABLE.matcher(line); if (!matcher.matches()) { return false; } else { String s = matcher.group(1); return s.matches(this.getName()); } } public static ShaderOption parseOption(String line, String path) { Matcher matcher = PATTERN_VARIABLE.matcher(line); if (!matcher.matches()) { return null; } else { String s = matcher.group(1); String s1 = matcher.group(2); String s2 = matcher.group(3); String s3 = StrUtils.getSegment(s2, "[", "]"); if (s3 != null && s3.length() > 0) { s2 = s2.replace(s3, "").trim(); } String[] astring = parseValues(s1, s3); if (s != null && s.length() > 0) { path = StrUtils.removePrefix(path, "/shaders/"); ShaderOption shaderoption = new ShaderOptionVariable(s, s2, s1, astring, path); return shaderoption; } else { return null; } } } public static String[] parseValues(String value, String valuesStr) { String[] astring = new String[] {value}; if (valuesStr == null) { return astring; } else { valuesStr = valuesStr.trim(); valuesStr = StrUtils.removePrefix(valuesStr, "["); valuesStr = StrUtils.removeSuffix(valuesStr, "]"); valuesStr = valuesStr.trim(); if (valuesStr.length() <= 0) { return astring; } else { String[] astring1 = Config.tokenize(valuesStr, " "); if (astring1.length <= 0) { return astring; } else { if (!Arrays.asList(astring1).contains(value)) { astring1 = (String[])Config.addObjectToArray(astring1, value, 0); } return astring1; } } } } }
3,610
Java
.java
110
22.490909
130
0.519529
dotexe1337/bdsm-client-1.16
8
1
1
GPL-2.0
9/4/2024, 9:22:36 PM (Europe/Amsterdam)
false
false
false
true
true
true
true
true
3,610
4,796,699
SwitchInstruction.java
millecker_soot-rb/src/soot/dexpler/instructions/SwitchInstruction.java
/* Soot - a Java Optimization Framework * Copyright (C) 2012 Michael Markert, Frank Hartmann * * (c) 2012 University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * Alexandre Bartel * * * This library 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 library 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 library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ package soot.dexpler.instructions; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.OffsetInstruction; import org.jf.dexlib.Code.SingleRegisterInstruction; import soot.Local; import soot.Unit; import soot.dexpler.DexBody; import soot.jimple.Jimple; import soot.jimple.Stmt; public abstract class SwitchInstruction extends PseudoInstruction implements DeferableInstruction { protected Unit markerUnit; public SwitchInstruction (Instruction instruction, int codeAdress) { super(instruction, codeAdress); } /** * Return a switch statement based on given target data on the given key. * */ protected abstract Stmt switchStatement(DexBody body, Instruction targetData, Local key); public void jimplify(DexBody body) { markerUnit = Jimple.v().newNopStmt(); unit = markerUnit; body.add(markerUnit); body.addDeferredJimplification(this); } public void deferredJimplify(DexBody body) { int keyRegister = ((SingleRegisterInstruction) instruction).getRegisterA(); int offset = ((OffsetInstruction) instruction).getTargetAddressOffset(); Local key = body.getRegisterLocal(keyRegister); int targetAddress = codeAddress + offset; Instruction targetData = body.instructionAtAddress(targetAddress).instruction; Stmt stmt = switchStatement(body, targetData, key); body.getBody().getUnits().insertAfter(stmt, markerUnit); } }
2,487
Java
.java
58
38.637931
99
0.753317
millecker/soot-rb
1
5
0
LGPL-2.1
9/5/2024, 12:32:12 AM (Europe/Amsterdam)
false
false
false
true
false
true
true
true
2,487
1,755,655
IntStream.java
wittawatj_jtcc/src/org/antlr/runtime/IntStream.java
/* [The "BSD licence"] Copyright (c) 2005-2008 Terence Parr 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. */ package org.antlr.runtime; /** A simple stream of integers used when all I care about is the char * or token type sequence (such as interpretation). */ public interface IntStream { void consume(); /** Get int at current input pointer + i ahead where i=1 is next int. * Negative indexes are allowed. LA(-1) is previous token (token * just matched). LA(-i) where i is before first token should * yield -1, invalid char / EOF. */ int LA(int i); /** Tell the stream to start buffering if it hasn't already. Return * current input position, index(), or some other marker so that * when passed to rewind() you get back to the same spot. * rewind(mark()) should not affect the input cursor. The Lexer * track line/col info as well as input index so its markers are * not pure input indexes. Same for tree node streams. */ int mark(); /** Return the current input symbol index 0..n where n indicates the * last symbol has been read. The index is the symbol about to be * read not the most recently read symbol. */ int index(); /** Reset the stream so that next call to index would return marker. * The marker will usually be index() but it doesn't have to be. It's * just a marker to indicate what state the stream was in. This is * essentially calling release() and seek(). If there are markers * created after this marker argument, this routine must unroll them * like a stack. Assume the state the stream was in when this marker * was created. */ void rewind(int marker); /** Rewind to the input position of the last marker. * Used currently only after a cyclic DFA and just * before starting a sem/syn predicate to get the * input position back to the start of the decision. * Do not "pop" the marker off the state. mark(i) * and rewind(i) should balance still. It is * like invoking rewind(last marker) but it should not "pop" * the marker off. It's like seek(last marker's input position). */ void rewind(); /** You may want to commit to a backtrack but don't want to force the * stream to keep bookkeeping objects around for a marker that is * no longer necessary. This will have the same behavior as * rewind() except it releases resources without the backward seek. * This must throw away resources for all markers back to the marker * argument. So if you're nested 5 levels of mark(), and then release(2) * you have to release resources for depths 2..5. */ void release(int marker); /** Set the input cursor to the position indicated by index. This is * normally used to seek ahead in the input stream. No buffering is * required to do this unless you know your stream will use seek to * move backwards such as when backtracking. * * This is different from rewind in its multi-directional * requirement and in that its argument is strictly an input cursor (index). * * For char streams, seeking forward must update the stream state such * as line number. For seeking backwards, you will be presumably * backtracking using the mark/rewind mechanism that restores state and * so this method does not need to update state when seeking backwards. * * Currently, this method is only used for efficient backtracking using * memoization, but in the future it may be used for incremental parsing. * * The index is 0..n-1. A seek to position i means that LA(1) will * return the ith symbol. So, seeking to 0 means LA(1) will return the * first element in the stream. */ void seek(int index); /** Only makes sense for streams that buffer everything up probably, but * might be useful to display the entire stream or for testing. This * value includes a single EOF. */ int size(); /** Where are you getting symbols from? Normally, implementations will * pass the buck all the way to the lexer who can ask its input stream * for the file name or whatever. */ public String getSourceName(); }
5,460
Java
.java
110
46.809091
78
0.743912
wittawatj/jtcc
17
8
2
GPL-3.0
9/4/2024, 8:17:41 PM (Europe/Amsterdam)
true
true
true
true
true
true
true
true
5,460
4,519,910
WxOpenConfig.java
mizhousoft_weixin-sdk/weixin-open/src/main/java/com/mizhousoft/weixin/open/config/WxOpenConfig.java
package com.mizhousoft.weixin.open.config; import com.mizhousoft.weixin.common.WxConfig; /** * 微信开放平台配置 * */ public class WxOpenConfig extends WxConfig { }
190
Java
.java
9
16.333333
46
0.761006
mizhousoft/weixin-sdk
2
2
0
EPL-2.0
9/5/2024, 12:15:50 AM (Europe/Amsterdam)
false
false
false
true
true
false
true
true
174
1,317,011
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/PushDown/testGenerics11/in/A.java
package p; class A<T>{ /** * comment */ public void m() {} } class B<T> extends A<T>{ }
93
Java
.java
9
8.777778
24
0.576471
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
93
3,208,325
AbstractJAMWikiLexer.java
node_jamwiki/jamwiki-core/src/main/java/org/jamwiki/parser/jflex/AbstractJAMWikiLexer.java
/** * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999. * * This program is free software; you can redistribute it and/or modify * it under the terms of the latest version of the GNU Lesser General * Public License as published by the Free Software Foundation; * * 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 (LICENSE.txt); if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.jamwiki.parser.jflex; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Stack; import org.apache.commons.lang3.StringUtils; import org.jamwiki.parser.ParserException; import org.jamwiki.parser.ParserInput; import org.jamwiki.parser.ParserOutput; import org.jamwiki.utils.Utilities; import org.jamwiki.utils.WikiLogger; /** * Abstract class that is extended by the main JFlex lexer. */ public abstract class AbstractJAMWikiLexer extends JFlexLexer { protected static final WikiLogger logger = WikiLogger.getLogger(AbstractJAMWikiLexer.class.getName()); /** * Automatically insert a paragraph tag after all block-level tags EXCEPT * for paragraph tags (since that is handled by the parser). This is * a hack-ish workaround for the fact that Mediawiki syntax makes it very * difficult to determine when a new paragraph is needed, so this code * is overzealous with paragraph insertion and empty paragraph tags are * resolved to empty text by the JFlexTagItem.toHtml() method. */ private static final Map<String, String> PARAGRAPH_OPEN_LOCATION_LIST = Utilities.initializeLookupMap("blockquote", "center", "div", "dl", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "ol", "pre", "table", "ul"); /** Stack of currently parsed tag content. */ private final Stack<JFlexTagItem> tagStack = new Stack<JFlexTagItem>(); /** * Append content to the current tag in the tag stack. */ protected void append(String content) { this.peekTag().getTagContent().append(content); } /** * Convert a wiki list character to an HTML list item type. For example, * "#" corresponds to "li" while ":" corresponds to "dd". */ private String calculateListItemType(char wikiSyntax) { if (wikiSyntax == '*' || wikiSyntax == '#') { return "li"; } if (wikiSyntax == ';') { return "dt"; } if (wikiSyntax == ':') { return "dd"; } throw new IllegalArgumentException("Unrecognized wiki syntax: " + wikiSyntax); } /** * Convert a wiki list character to an HTML list type. For example, * "#" corresponds to "ol". */ private String calculateListType(char wikiSyntax) { if (wikiSyntax == ';' || wikiSyntax == ':') { return "dl"; } if (wikiSyntax == '#') { return "ol"; } if (wikiSyntax == '*') { return "ul"; } throw new IllegalArgumentException("Unrecognized wiki syntax: " + wikiSyntax); } /** * Utility method used when parsing list tags to determine the current * list nesting level. */ private int currentListDepth() { int depth = 0; int i = 0; // traverse backwards through the tag stack looking for list tags while (this.peekTag(++i) != null) { if (this.peekTag(i).isEmptyParagraphTag()) { // ignore paragraphs continue; } if (!this.peekTag(i).isListTag()) { break; } depth++; } // divide by two since lists always have a list and a list item tag return (depth / 2); } /** * Override the parent method to allow tag stack initialization. */ protected void init(ParserInput parserInput, ParserOutput parserOutput, int mode) { super.init(parserInput, parserOutput, mode); this.tagStack.push(new JFlexTagItem(JFlexTagItem.ROOT_TAG)); } /** * Utility method to walk the current tag stack to determine if the top of the stack * contains list tags followed by a tag of a specific type. */ private boolean isNextAfterListTags(String tagType) { int i = 0; while (this.peekTag(++i) != null) { if (this.peekTag(i).getTagType().equals(tagType)) { return true; } if (!this.peekTag(i).isListTag()) { return false; } } return false; } /** * Utility method to determine if the parser is at the start of the file. */ protected boolean isStartOfFile() { if (this.peekTag().getTagContent().length() != 0) { // if there is content already then this is not the start of the file return false; } if (this.peekTag().isRootTag()) { // if this is the root tag and it's empty, this is the start of the file return true; } if (this.tagStack.size() == 2 && this.tagStack.get(0).getTagContent().length() == 0 && this.peekTag().isEmptyParagraphTag()) { // if this is the paragraph tag that is pre-pended prior to parsing // and the root tag is empty, this is the start of the file return true; } return false; } /** * Execute the lexer, returning the parsed content. Override the parent * method to use the tag stack. */ protected String lex() throws Exception { String line; if (this.mode == JFlexParser.MODE_LAYOUT) { // push a paragraph at start of lexing - if it turns out that an // opening paragraph is not needed then it will resolve to empty // text via JFlexTagItem.toHtml(). this.pushTag("p", null); } // parse all text while ((line = this.yylex()) != null) { this.append(line); } // parse for any paragraph tags that might need closing at EOF if (this.paragraphIsOpen()) { this.parse(TAG_TYPE_PARAGRAPH, "\n"); } return this.popAllTags(); } /** * Utility method to determine if a paragraph is currently open. */ protected boolean paragraphIsOpen() { // traverse backwards through the tag stack looking for an open paragraph tag int i = 0; while (this.peekTag(++i) != null) { if (this.peekTag(i).getTagType().equals("p")) { return true; } if (!this.peekTag(i).isInlineTag()) { // if a block tag is encountered there should be no // need to check further break; } } return false; } /** * Take Wiki text of the form "|" or "| style='foo' |" and convert to * and HTML <td> or <th> tag. * * @param text The text to be parsed. * @param tagType The HTML tag type, either "td" or "th". * @param markup The Wiki markup for the tag, either "|", "|+" or "!" */ protected void parseTableCell(String text, String tagType, String markup) throws ParserException { if (text == null) { throw new IllegalArgumentException("No text specified while parsing table cell"); } text = text.trim(); String openTagRaw = null; int pos = StringUtils.indexOfAnyBut(text, markup); if (pos != -1) { text = text.substring(pos); pos = text.indexOf('|'); if (pos != -1) { text = text.substring(0, pos); } openTagRaw = "<" + tagType + " " + text.trim() + ">"; } this.pushTag(tagType, openTagRaw); } /** * Peek at the current tag from the lexer stack and see if it matches * the given tag type. */ protected JFlexTagItem peekTag() { return this.tagStack.peek(); } /** * Peek at the current tag from the lexer stack and see if it matches * the given tag type. * * @param pos Depth of the tag stack to peek. If looking at the last tag * then specify one, the second-to-last-tag specify two, etc. * @return The tag as the specified position in the stack, or <code>null</code> * if the stack is smaller than the specified index. */ protected JFlexTagItem peekTag(int pos) { if (pos < 1) { throw new IllegalArgumentException("Cannot call peekTag with an index less than one"); } if (pos > this.tagStack.size()) { return null; } return this.tagStack.get(this.tagStack.size() - pos); } /** * Pop all list tags off of the current stack. */ protected void popAllListTags() throws ParserException { // before clearing a list, first make sure that any open inline tags or paragraph tags // have been closed (example: "<i><ul>" is invalid. close the <i> first). while (!this.peekTag().isRootTag() && (this.peekTag().getTagType().equals("p") || this.peekTag().isInlineTag())) { this.popTag(this.peekTag().getTagType()); } this.popListTags(this.currentListDepth()); } /** * Pop all tags off of the stack and return a string representation. */ private String popAllTags() throws ParserException { // pop the stack down to (but not including) the root tag while (this.tagStack.size() > 1) { this.popTag(this.peekTag().getTagType()); } // now pop the root tag if (this.mode >= JFlexParser.MODE_LAYOUT) { return this.tagStack.pop().toHtml().toString().trim(); } else { return this.tagStack.pop().toHtml().toString(); } } /** * Pop the next X number of list tags off of the current tag stack. */ private void popListTags(int depth) throws ParserException { if (depth < 0) { throw new IllegalArgumentException("Cannot pop a negative number: " + depth); } for (int i = 0; i < depth; i++) { // the open tag stack will be of the form <ol><li><p>, so pop all of them if (this.peekTag().getTagType().equals("p")) { this.popTag(this.peekTag().getTagType()); } this.popTag(this.peekTag().getTagType()); this.popTag(this.peekTag().getTagType()); } } /** * Handle popping a tag that is not the current tag on the stack. */ private void popMismatchedTag(String tagType) throws ParserException { // check to see if a close tag override was previously set, which happens // from the inner tag of unbalanced HTML. Example: "<u><strong>text</u></strong>" // would set a close tag override when the "</u>" is parsed to indicate that // the "</strong>" should actually be parsed as a "</u>". if (StringUtils.equals(this.peekTag().getTagType(), this.peekTag().getCloseTagOverride())) { this.popTag(this.peekTag().getCloseTagOverride()); return; } // if the open tag is a paragraph then close it - paragraph tags are added in // many places where they might not need to be since the parser is trying to // guess what a newline is supposed to mean. if (this.peekTag().getTagType().equals("p")) { this.popTag("p"); this.popTag(tagType); return; } // check to see if the parent tag is a list and the current tag is in the tag // stack. if so close the list and pop the current tag. if (!JFlexTagItem.isListTag(tagType) && this.peekTag().isListItemTag() && this.isNextAfterListTags(tagType)) { this.popAllListTags(); this.popTag(tagType); return; } // check to see if the parent tag matches the current close tag. if so then // this is unbalanced HTML of the form "<u><strong>text</u></strong>" and // it should be parsed as "<u><strong>text</strong></u>". JFlexTagItem parent = this.peekTag(2); if (parent != null && parent.getTagType().equals(tagType)) { parent.setCloseTagOverride(tagType); this.popTag(this.peekTag().getTagType()); return; } // if the above checks fail then this is an attempt to pop a tag that is not // currently open, so append the escaped close tag to the current tag // content without modifying the tag stack. this.peekTag().getTagContent().append("&lt;/" + tagType + "&gt;"); } /** * Pop the most recent HTML tag from the lexer stack. */ protected void popTag(String tagType) throws ParserException { if (this.tagStack.size() <= 1) { logger.warn("popTag called on an empty tag stack or on the root stack element. Please report this error on jamwiki.org, and provide the wiki syntax for the topic being parsed."); } if (!this.peekTag().getTagType().equals(tagType)) { // handle the case where the tag being popped is not the current tag on // the stack. this can happen with mis-matched HTML // ("<u><strong>text</u></strong>"), tags that aren't automatically // closed, and other more random scenarios. this.popMismatchedTag(tagType); return; } JFlexTagItem currentTag = this.peekTag(); if (this.tagStack.size() > 1) { // only pop if not the root tag currentTag = this.tagStack.pop(); } CharSequence html = currentTag.toHtml(); if (StringUtils.isBlank(html)) { // if the tag results in no content being generated then there is // nothing more to do. return; } JFlexTagItem previousTag = this.peekTag(); if (!currentTag.isInlineTag() || currentTag.getTagType().equals("pre")) { // if the current tag is not an inline tag, make sure it is on its own lines if (previousTag.getTagContent().length() > 0 && Character.isWhitespace(previousTag.getTagContent().charAt(previousTag.getTagContent().length() - 1))) { String trimmedContent = StringUtils.stripEnd(previousTag.getTagContent().toString(), null); previousTag.getTagContent().delete(trimmedContent.length(), previousTag.getTagContent().length()); } previousTag.getTagContent().append('\n'); previousTag.getTagContent().append(html); previousTag.getTagContent().append('\n'); } else { previousTag.getTagContent().append(html); } if (PARAGRAPH_OPEN_LOCATION_LIST.containsKey(tagType)) { // force a paragraph open after block tags. this tag may not actually // end up in the final output if there aren't any newlines in the // wikitext after the block tag. make sure that PARAGRAPH_OPEN_LOCATION_LIST // does not contain "p", otherwise we loop infinitely. this.pushTag("p", null); } } /** * Wiki lists are of the form ":#;" and depend on the previous list entries, * so given the current tag stack and the wiki syntax for the current list * syntax, update the tag stack accordingly. */ protected void processListStack(String wikiSyntax) throws ParserException { // before adding to a list, first make sure that any open inline tags or paragraph tags // have been closed (example: "<i><ul>" is invalid. close the <i> first). while (!this.peekTag().isRootTag() && (this.peekTag().getTagType().equals("p") || this.peekTag().isInlineTag())) { this.popTag(this.peekTag().getTagType()); } int previousDepth = this.currentListDepth(); int currentDepth = wikiSyntax.length(); // if list was previously open to a greater depth, close the old list down to the // current depth. int tagsToPop = (previousDepth - currentDepth); if (tagsToPop > 0) { this.popListTags(tagsToPop); previousDepth -= tagsToPop; } // now look for differences in the current list stacks. for example, if // the previous list was "::;" and the current list is "###" then there are // three lists that must be closed. first, walk back the current stack // to find the list open tags. List<String> listTagTypes = null; int j = 0; while (this.peekTag(++j) != null) { if (this.peekTag(j).isListTag() && !this.peekTag(j).isListItemTag()) { if (listTagTypes == null) { listTagTypes = new ArrayList<String>(); } listTagTypes.add(this.peekTag(j).getTagType()); } } // now verify whether the list open tags match the current syntax, ie // whether "::;" matches whatever tags are already open String tagType; for (int i = 1; i <= previousDepth; i++) { if (listTagTypes != null && (listTagTypes.size() - i) < 0) { logger.warn("processListStack has encountered an invalid list stack. Please report this error on jamwiki.org, and provide the wiki syntax for the topic being parsed."); break; } tagType = listTagTypes.get(listTagTypes.size() - i); if (tagType.equals(this.calculateListType(wikiSyntax.charAt(i - 1)))) { continue; } // if the above test did not match, then the stack needs to be popped // to this point. tagsToPop = (previousDepth - (i - 1)); this.popListTags(tagsToPop); previousDepth -= tagsToPop; break; } if (previousDepth == 0) { // if no list is open, open one this.pushTag(this.calculateListType(wikiSyntax.charAt(0)), null); // add the new list item to the stack this.pushTag(this.calculateListItemType(wikiSyntax.charAt(0)), null); } else if (previousDepth == currentDepth) { // pop the previous list item tagType = this.peekTag().getTagType(); this.popTag(tagType); // add the new list item to the stack this.pushTag(this.calculateListItemType(wikiSyntax.charAt(previousDepth - 1)), null); } // if the new list has additional elements, push them onto the stack int counterStart = (previousDepth > 1) ? previousDepth : 1; String previousTagType; for (int i = counterStart; i < wikiSyntax.length(); i++) { // handle a weird corner case. if a "dt" is open and there are // sub-lists, close the dt and open a "dd" for the sub-list previousTagType = this.peekTag().getTagType(); if (previousTagType.equals("p") && this.tagStack.size() > 2) { // ignore paragraph tags previousTagType = this.peekTag(2).getTagType(); } if (previousTagType.equals("dt")) { this.popTag("dt"); if (!this.calculateListType(wikiSyntax.charAt(i)).equals("dl")) { this.popTag("dl"); this.pushTag("dl", null); } this.pushTag("dd", null); } // push the new list tag, and its tag item, onto the stack this.pushTag(this.calculateListType(wikiSyntax.charAt(i)), null); this.pushTag(this.calculateListItemType(wikiSyntax.charAt(i)), null); } } /** * Make sure any open table tags that need to be closed are closed. */ protected void processTableStack() throws ParserException { // before updating the table make sure that any open inline tags or paragraph tags // have been closed (example: "<td><b></td>" won't work. while (!this.peekTag().isRootTag() && (this.peekTag().getTagType().equals("p") || this.peekTag().isInlineTag())) { this.popTag(this.peekTag().getTagType()); } String previousTagType = this.peekTag().getTagType(); if (!previousTagType.equals("caption") && !previousTagType.equals("th") && !previousTagType.equals("td")) { // no table cell was open, so nothing to close return; } // pop the previous tag this.popTag(previousTagType); } /** * Push a new HTML tag onto the lexer stack. */ protected void pushTag(String tagType, String openTagRaw) throws ParserException { this.pushTag(new JFlexTagItem(tagType, openTagRaw)); } /** * Push a new HTML tag onto the lexer stack. */ protected void pushTag(JFlexTagItem tag) throws ParserException { if (!tag.isInlineTag() && this.peekTag().getTagType().equals("p")) { // make sure any open paragraph is closed before opening a block tag this.popTag("p"); } // many HTML tags cannot nest (ie "<li><li></li></li>" is invalid), so if a non-nesting // tag is being added and the previous tag is of the same type, close the previous tag // note the special case for dt && dd tags if (tag.isNonNestingTag() && (this.peekTag().getTagType().equals(tag.getTagType()) || (tag.isListItemTag() && this.peekTag().isListItemTag()))) { this.popTag(this.peekTag().getTagType()); } this.tagStack.push(tag); } }
19,163
Java
.java
493
35.679513
210
0.699507
node/jamwiki
4
5
0
LGPL-3.0
9/4/2024, 11:05:15 PM (Europe/Amsterdam)
true
true
true
true
true
true
true
true
19,163
4,534,542
BubbleData.java
vitelabs_vite-wallet-android/MPChartLib/src/main/java/com/github/mikephil/charting/data/BubbleData.java
package com.github.mikephil.charting.data; import com.github.mikephil.charting.interfaces.datasets.IBubbleDataSet; import java.util.List; public class BubbleData extends BarLineScatterCandleBubbleData<IBubbleDataSet> { public BubbleData() { super(); } public BubbleData(IBubbleDataSet... dataSets) { super(dataSets); } public BubbleData(List<IBubbleDataSet> dataSets) { super(dataSets); } /** * Sets the width of the circle that surrounds the bubble when highlighted * for all DataSet objects this data object contains, in dp. * * @param width */ public void setHighlightCircleWidth(float width) { for (IBubbleDataSet set : mDataSets) { set.setHighlightCircleWidth(width); } } }
801
Java
.java
25
26.16
80
0.697523
vitelabs/vite-wallet-android
2
0
0
GPL-3.0
9/5/2024, 12:16:26 AM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
801
401,374
InAppPurchaseFragment.java
treasure-lau_Linphone4Android/app/src/main/java/org/linphone/purchase/InAppPurchaseFragment.java
package org.linphone.purchase; /* InAppPurchaseFragment.java Copyright (C) 2016 Belledonne Communications, Grenoble, France 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import java.util.Locale; import org.linphone.LinphoneManager; import org.linphone.LinphonePreferences; import org.linphone.R; import org.linphone.core.LinphoneProxyConfig; import android.app.Fragment; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; public class InAppPurchaseFragment extends Fragment implements View.OnClickListener { private LinearLayout usernameLayout; private EditText username, email; private TextView errorMessage; private boolean usernameOk = false, emailOk = false; private String defaultUsername, defaultEmail; private Button buyItemButton, recoverAccountButton; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); View view = inflater.inflate(R.layout.in_app_store, container, false); String id = getArguments().getString("item_id"); Purchasable item = InAppPurchaseActivity.instance().getPurchasedItem(id); buyItemButton = (Button) view.findViewById(R.id.inapp_button); displayBuySubscriptionButton(item); defaultEmail = InAppPurchaseActivity.instance().getGmailAccount(); defaultUsername = LinphonePreferences.instance().getAccountUsername(LinphonePreferences.instance().getDefaultAccountIndex()); usernameLayout = (LinearLayout) view.findViewById(R.id.username_layout); username = (EditText) view.findViewById(R.id.username); if(!getResources().getBoolean(R.bool.hide_username_in_inapp)){ usernameLayout.setVisibility(View.VISIBLE); username.setText(LinphonePreferences.instance().getAccountUsername(LinphonePreferences.instance().getDefaultAccountIndex())); addUsernameHandler(username, errorMessage); } else { if(defaultUsername != null){ usernameLayout.setVisibility(View.GONE); usernameOk = true; } } email = (EditText) view.findViewById(R.id.email); if(defaultEmail != null){ email.setText(defaultEmail); emailOk = true; } buyItemButton.setEnabled(emailOk && usernameOk); errorMessage = (TextView) view.findViewById(R.id.username_error); return view; } private void addUsernameHandler(final EditText field, final TextView errorMessage) { field.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int count, int after) { usernameOk = false; String username = s.toString(); if (isUsernameCorrect(username)) { usernameOk = true; errorMessage.setText(""); } else { errorMessage.setText(R.string.wizard_username_incorrect); } if (buyItemButton != null) buyItemButton.setEnabled(usernameOk); if (recoverAccountButton != null) recoverAccountButton.setEnabled(usernameOk); } }); } private boolean isUsernameCorrect(String username) { LinphoneProxyConfig lpc = LinphoneManager.getLc().createProxyConfig(); return lpc.isPhoneNumber(username); } private void displayBuySubscriptionButton(Purchasable item) { buyItemButton.setText("Buy account (" + item.getPrice() + ")"); buyItemButton.setTag(item); buyItemButton.setOnClickListener(this); buyItemButton.setEnabled(usernameOk && emailOk); } @Override public void onClick(View v) { Purchasable item = (Purchasable) v.getTag(); if (v.equals(recoverAccountButton)) { //TODO } else { InAppPurchaseActivity.instance().buyInapp(getUsername(), item); } } private String getUsername() { String username = this.username.getText().toString(); LinphoneProxyConfig lpc = LinphoneManager.getLc().createProxyConfig(); username = lpc.normalizePhoneNumber(username); return username.toLowerCase(Locale.getDefault()); } }
4,839
Java
.java
117
38.452991
128
0.792199
treasure-lau/Linphone4Android
246
102
19
GPL-3.0
9/4/2024, 7:07:11 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
4,839
1,317,295
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameType/test13/in/A.java
package p; class A{ void m(){ boolean b = (new A()) instanceof A; }; }
78
Java
.java
6
10.833333
39
0.575342
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
78
4,762,127
MultiMap.java
cismet_cismet-commons/src/main/java/de/cismet/tools/collections/MultiMap.java
/*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ package de.cismet.tools.collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; /** * //key=idnetifier;value=LinkedList. * * @version $Revision$, $Date$ * @deprecated error-prone */ public class MultiMap extends LinkedHashMap { //~ Constructors ----------------------------------------------------------- /** * ////////////////////////////////////////////// */ public MultiMap() { this(10); } /** * ////////////////////////////////////////////// * * @param size size */ public MultiMap(final int size) { super(size); } //~ Methods ---------------------------------------------------------------- ///////////////////////////////////////////////// @Override public Object put(final Object key, final Object value) { SyncLinkedList list = null; if (containsKey(key)) // anh\u00E4ngen an bestehende liste { list = (SyncLinkedList)get(key); list.add(value); } else // keine existierende liste { list = new SyncLinkedList(); list.add(value); super.put(key, list); } // no item is replaced return null; } // end add ////////////////////////////////////////////////////////////// @Override public void putAll(final Map t) { final Iterator i = t.entrySet().iterator(); while (i.hasNext()) { final Map.Entry e = (Map.Entry)i.next(); final Object val = e.getValue(); final Object key = e.getKey(); // wenn mehrere Eintr\u00E4ge zu einem key if (val instanceof SyncLinkedList) { final Iterator iter = ((SyncLinkedList)val).iterator(); while (iter.hasNext()) { put(key, iter.next()); } } else { put(key, val); } } } /** * HELL. * * @param key key for he given value * @param value value for the given key * * @return true if the specified key with the specified mapping does exist */ public boolean contains(final Object key, final Object value) { return containsKey(key) && ((SyncLinkedList)get(key)).contains(value); } /** * HELL. * * @param key DOCUMENT ME! * * @return DOCUMENT ME! */ public Iterator iterator(final String key) { if (containsKey(key)) { return ((SyncLinkedList)get(key)).iterator(); } else { return null; } } //////////////////////////////////////////////////////// /** * DOCUMENT ME! * * @param key DOCUMENT ME! * @param value DOCUMENT ME! * * @return DOCUMENT ME! */ //J- public boolean remove(final Object key, final Object value) { SyncLinkedList list = null; if (containsKey(key)) { list = (SyncLinkedList)get(key); final boolean listElementRemoved = list.remove(value); if (list.isEmpty()) { this.remove(key); } // Iterator iter = list.iterator(); // // while(iter.hasNext()) // if(value.equals(iter.next()) ) // return list.remove(value); return listElementRemoved; } else { return false; } } //J+ } // end class //////////////////////////////////////////////////////////////////////////
3,810
Java
.java
128
22.109375
80
0.4449
cismet/cismet-commons
1
1
10
LGPL-3.0
9/5/2024, 12:30:20 AM (Europe/Amsterdam)
false
false
true
true
false
true
false
true
3,810
1,701,329
FolderNotFoundException.java
stacksync_android/src/main/java/com/stacksync/android/exceptions/FolderNotFoundException.java
package com.stacksync.android.exceptions; public class FolderNotFoundException extends APIException { private static final long serialVersionUID = -4659557598238750176L; public FolderNotFoundException() { super(); } public FolderNotFoundException(String message) { super(message); } public FolderNotFoundException(String message, int statusCode){ super(message, statusCode); } }
399
Java
.java
13
28.153846
68
0.823219
stacksync/android
13
5
9
GPL-3.0
9/4/2024, 8:15:17 PM (Europe/Amsterdam)
false
false
true
true
false
true
false
true
399
1,319,464
A_test612.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/expression_in/A_test612.java
package expression_in; public class A_test612 { class Inner { } public void foo() { Inner[] inner= /*[*/new Inner[10]/*]*/; } }
135
Java
.java
8
15
41
0.642857
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
135
4,947,655
LaborJournalVoucherPositionCodeExistenceCheckValidation.java
ua-eas_ua-kfs-5_3/work/src/org/kuali/kfs/module/ld/document/validation/impl/LaborJournalVoucherPositionCodeExistenceCheckValidation.java
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.module.ld.document.validation.impl; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.kuali.kfs.module.ld.LaborConstants; import org.kuali.kfs.module.ld.businessobject.LaborJournalVoucherDetail; import org.kuali.kfs.module.ld.businessobject.PositionData; import org.kuali.kfs.sys.KFSKeyConstants; import org.kuali.kfs.sys.KFSPropertyConstants; import org.kuali.kfs.sys.businessobject.AccountingLine; import org.kuali.kfs.sys.context.SpringContext; import org.kuali.kfs.sys.document.validation.GenericValidation; import org.kuali.kfs.sys.document.validation.event.AttributedDocumentEvent; import org.kuali.rice.kns.service.DataDictionaryService; import org.kuali.rice.krad.service.BusinessObjectService; import org.kuali.rice.krad.util.GlobalVariables; /** * Validates that a labor journal voucher document's accounting lines have valid Position Code */ public class LaborJournalVoucherPositionCodeExistenceCheckValidation extends GenericValidation { private AccountingLine accountingLineForValidation; /** * Validates that the accounting line in the labor journal voucher document for valid position code * * @see org.kuali.kfs.validation.Validation#validate(java.lang.Object[]) */ public boolean validate(AttributedDocumentEvent event) { boolean result = true; LaborJournalVoucherDetail laborJournalVoucherDetail = (LaborJournalVoucherDetail) getAccountingLineForValidation(); String positionNumber = laborJournalVoucherDetail.getPositionNumber(); if (StringUtils.isBlank(positionNumber) || LaborConstants.getDashPositionNumber().equals(positionNumber)) { return true; } if (!positionCodeExistenceCheck(positionNumber)) { result = false; } return result; } /** * Checks whether employee id exists * * @param positionNumber positionNumber is checked against the collection of position number matches * @return True if the given position number exists, false otherwise. */ protected boolean positionCodeExistenceCheck(String positionNumber) { boolean positionNumberExists = true; Map<String, Object> criteria = new HashMap<String, Object>(); criteria.put(KFSPropertyConstants.POSITION_NUMBER, positionNumber); Collection<PositionData> positionNumberMatches = SpringContext.getBean(BusinessObjectService.class).findMatching(PositionData.class, criteria); if (positionNumberMatches == null || positionNumberMatches.isEmpty()) { String label = SpringContext.getBean(DataDictionaryService.class).getDataDictionary().getBusinessObjectEntry(PositionData.class.getName()).getAttributeDefinition(KFSPropertyConstants.POSITION_NUMBER).getLabel(); GlobalVariables.getMessageMap().putError(KFSPropertyConstants.POSITION_NUMBER, KFSKeyConstants.ERROR_EXISTENCE, label); positionNumberExists = false; } return positionNumberExists; } /** * Gets the accountingLineForValidation attribute. * * @return Returns the accountingLineForValidation. */ public AccountingLine getAccountingLineForValidation() { return accountingLineForValidation; } /** * Sets the accountingLineForValidation attribute value. * * @param accountingLineForValidation The accountingLineForValidation to set. */ public void setAccountingLineForValidation(AccountingLine accountingLineForValidation) { this.accountingLineForValidation = accountingLineForValidation; } }
4,612
Java
.java
92
43.913043
224
0.757569
ua-eas/ua-kfs-5.3
1
0
0
AGPL-3.0
9/5/2024, 12:36:54 AM (Europe/Amsterdam)
true
true
true
true
false
true
false
true
4,612
4,217,552
WorkbenchEntrySet.java
iskoda_Bubing-crawler-BUT/src/it/unimi/di/law/bubing/frontier/WorkbenchEntrySet.java
package it.unimi.di.law.bubing.frontier; /* * Copyright (C) 2012-2013 Sebastiano Vigna * * 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/>. * */ import static it.unimi.dsi.fastutil.HashCommon.arraySize; import it.unimi.dsi.fastutil.Hash; import java.util.Arrays; //RELEASE-STATUS: DIST /** A data structure representing the set of {@linkplain WorkbenchEntry workbench entries} created so far. * It is a lightweight implementation of a map from IP addresses to workbench entries. */ public class WorkbenchEntrySet implements java.io.Serializable, Hash { private static final long serialVersionUID = 0L; /** The array of keys. */ protected transient WorkbenchEntry[] workbenchEntry; /** The current table size. */ protected transient int n; /** The mask for wrapping a position counter. */ protected transient int mask; /** Number of entries in the set. */ protected int size; /** The maximum number of entries that can be filled before rehashing. */ protected int maxFill; /** Creates a set of workbench entries. */ public WorkbenchEntrySet() { n = 1024; mask = n - 1; maxFill = 3 * ( n / 4 ); workbenchEntry = new WorkbenchEntry[ n ]; } /** Returns the array of workbench entries; the order is arbitrary. The array may contain {@code null} elements. * * @return the array of workbench entries; it may contain {@code null} entries. */ public WorkbenchEntry[] workbenchEntries() { return workbenchEntry; } /** Ensures that the set has a given capacity. * * @param capacity the desired capacity. */ public void ensureCapacity( final int capacity ) { rehash( arraySize( capacity, (float)(3./4) ) ); } // TODO: change with something better private final static int hashCode( final byte[] a ) { return it.unimi.dsi.fastutil.HashCommon.murmurHash3( Arrays.hashCode( a ) ); } /** Adds a workbench entry to the set, if necessary. * * @param e the entry to be added. * @return true if the state set changed as a result of this operation. */ public boolean add( final WorkbenchEntry e ) { // The starting point. int pos = hashCode( e.ipAddress ) & mask; // There's always an unused entry. while ( workbenchEntry[ pos ] != null ) { if ( Arrays.equals( workbenchEntry[ pos ].ipAddress, e.ipAddress ) ) return false; pos = ( pos + 1 ) & mask; } workbenchEntry[ pos ] = e; if ( ++size >= maxFill && n < ( 1 << 30 ) ) rehash( 2 * n ); return true; } /** Shifts left entries with the specified hash code, starting at the specified position, and * empties the resulting free entry. * * @param pos a starting position. * @return the position cleared by the shifting process. */ protected final int shiftKeys( int pos ) { // Shift entries with the same hash. int last, slot; for ( ;; ) { pos = ( ( last = pos ) + 1 ) & mask; while ( workbenchEntry[ pos ] != null ) { slot = hashCode( workbenchEntry[ pos ].ipAddress ) & mask; if ( last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos ) break; pos = ( pos + 1 ) & mask; } if ( workbenchEntry[ pos ] == null ) break; workbenchEntry[ last ] = workbenchEntry[ pos ]; } workbenchEntry[ last ] = null; return last; } /** Removes a given workbench entry. * * @param e the workbench entry to be removed. * @return true if the state set changed as a result of this operation. */ public boolean remove( final WorkbenchEntry e ) { // The starting point. int pos = hashCode( e.ipAddress ) & mask; // There's always an unused entry. while ( workbenchEntry[ pos ] != null ) { if ( workbenchEntry[ pos ] == e ) { size--; shiftKeys( pos ); // TODO: implement resize return true; } pos = ( pos + 1 ) & mask; } return false; } /** Returns the entry for a given IP address. * * @param address the IP address. * @return the workbench entry corresponding to a given address, or {@code null}. */ public WorkbenchEntry get( final byte[] address ) { // The starting point. int pos = hashCode( address ) & mask; // There's always an unused entry. while ( workbenchEntry[ pos ] != null ) { if ( Arrays.equals( workbenchEntry[ pos ].ipAddress, address ) ) return workbenchEntry[ pos ]; pos = ( pos + 1 ) & mask; } return null; } /** Removes all elements from this set. * * <P>To increase object reuse, this method does not change the table size. */ public void clear() { if ( size == 0 ) return; size = 0; Arrays.fill( workbenchEntry, null ); } /** Returns the size (number of entries) in the workbench. * * @return the size (number of entries) in the workbench. */ public int size() { return size; } /** Returns whether the workbench is empty. * * @return whether the workbench is empty. */ public boolean isEmpty() { return size == 0; } /** Rehashes the set to a new size. * * @param newN the new size. */ protected void rehash( final int newN ) { int i = 0, pos; final WorkbenchEntry[] workbenchEntry = this.workbenchEntry; final int newMask = newN - 1; final WorkbenchEntry[] newWorkbenchEntry = new WorkbenchEntry[ newN ]; for ( int j = size; j-- != 0; ) { while ( workbenchEntry[ i ] == null ) i++; WorkbenchEntry e = workbenchEntry[ i ]; pos = hashCode( e.ipAddress ) & newMask; while ( newWorkbenchEntry[ pos ] != null ) pos = ( pos + 1 ) & newMask; newWorkbenchEntry[ pos ] = e; i++; } n = newN; mask = newMask; maxFill = 3 * ( n / 4 ); this.workbenchEntry = newWorkbenchEntry; } private void writeObject( java.io.ObjectOutputStream s ) throws java.io.IOException { s.defaultWriteObject(); for( int i = workbenchEntry.length; i-- != 0; ) if ( workbenchEntry[ i ] != null ) s.writeObject( workbenchEntry[ i ] ); } private void readObject( java.io.ObjectInputStream s ) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); n = arraySize( size, (float)(3./4) ); maxFill = 3 * ( n / 4 ); mask = n - 1; final WorkbenchEntry[] workbenchEntry = this.workbenchEntry = new WorkbenchEntry[ n ]; for ( int i = size, pos = 0; i-- != 0; ) { WorkbenchEntry e = (WorkbenchEntry)s.readObject(); pos = hashCode( e.ipAddress ) & mask; while ( workbenchEntry[ pos ] != null ) pos = ( pos + 1 ) & mask; } } }
6,923
Java
.java
197
32.172589
123
0.681893
iskoda/Bubing-crawler-BUT
2
1
0
LGPL-3.0
9/5/2024, 12:06:17 AM (Europe/Amsterdam)
true
true
true
true
true
true
true
true
6,923
4,861,185
WhoObject.java
Zenigata_jago/jagoclient/igs/who/WhoObject.java
package jagoclient.igs.who; import jagoclient.Global; import rene.util.parser.StringParser; import rene.util.sort.SortObject; /** This is needed for the Sorter class. @see rene.util.sort.Sorter */ public class WhoObject implements SortObject { String S,Name,Stat; public int V; boolean SortName; public WhoObject (String s, boolean sortname) { S=s; SortName=sortname; if (s.length()<=30) { V=-50; Name=""; Stat=""; return; } Stat=s.substring(0,5); StringParser p=new StringParser(s.substring(30)); String h=p.parseword(); p=new StringParser(h); if (p.isint()) { V=p.parseint(); if (p.skip("k")) V=100-V; else if (p.skip("d")) V=100+V; else if (p.skip("p")) V+=200; else if (p.skip("NR")) V=0; } else V=-50; if (s.length()<14) Name=""; else { p=new StringParser(s.substring(12)); Name=p.parseword(); } } String who () { return S; } public int compare (SortObject o) { WhoObject g=(WhoObject)o; if (SortName) { return Name.compareTo(g.Name); } else { if (V<g.V) return 1; else if (V>g.V) return -1; else return 0; } } public boolean looking () { return Stat.indexOf('!')>=0; } public boolean quiet () { return Stat.indexOf('Q')>=0; } public boolean silent () { return Stat.indexOf('X')>=0; } public boolean friend () { return Global.getParameter("friends","").indexOf(" "+Name)>=0; } public boolean marked () { return Global.getParameter("marked","").indexOf(" "+Name)>=0; } }
1,465
Java
.java
63
20.825397
65
0.665475
Zenigata/jago
1
0
0
GPL-2.0
9/5/2024, 12:33:57 AM (Europe/Amsterdam)
false
false
true
true
false
true
false
true
1,465
4,948,646
ProposalDao.java
ua-eas_ua-kfs-5_3/work/src/org/kuali/kfs/module/cg/dataaccess/ProposalDao.java
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.module.cg.dataaccess; import java.util.Collection; import org.kuali.kfs.module.cg.businessobject.Proposal; import org.kuali.kfs.module.cg.document.ProposalAwardCloseDocument; /** * Implementations of this interface provide access to persisted Proposal instances. */ public interface ProposalDao { /** * Gets a {@link Collection} of {@link Proposal} instances which have not yet been closed. * * @param c the {@link Close} instance which is used to determine which Proposals should be returned. * @return a {@link Collection} of appropriate {@link Proposals}. */ public Collection<Proposal> getProposalsToClose(ProposalAwardCloseDocument c); }
1,570
Java
.java
34
42.205882
106
0.749672
ua-eas/ua-kfs-5.3
1
0
0
AGPL-3.0
9/5/2024, 12:36:54 AM (Europe/Amsterdam)
true
true
true
true
false
true
true
true
1,570
1,318,582
B.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test1/out/B.java
package p; import java.util.ArrayList; import java.util.List; class B{ public static List m() { return new ArrayList(A.set); } }
135
Java
.java
8
15.125
30
0.752
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
135
1,534,604
PlayerDisconnectedEvent.java
VenixPLL_LightProxynetty/src/main/java/pl/venixpll/events/PlayerDisconnectedEvent.java
/* * LightProxy * Copyright (C) 2021. VenixPLL * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.venixpll.events; import com.darkmagician6.eventapi.events.Event; import lombok.AllArgsConstructor; import lombok.Data; import pl.venixpll.mc.objects.Player; @AllArgsConstructor @Data public class PlayerDisconnectedEvent implements Event { private Player player; }
1,009
Java
.java
27
35.444444
75
0.78608
VenixPLL/LightProxynetty
23
6
1
AGPL-3.0
9/4/2024, 7:57:39 PM (Europe/Amsterdam)
false
false
false
true
true
false
true
true
1,009
1,317,567
A_test21_in.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/InlineTemp/canInline/A_test21_in.java
package p; class A { private static void foo(String[] parameters, int j) { int temp1 = parameters.length + j; int temp = temp1; System.out.println(temp); } }
166
Java
.java
8
18.75
54
0.702532
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
166
4,296,146
FciDsepLegalPairsCfci.java
vineet1992_tetrad-vineet/tetrad-lib/src/main/java/edu/cmu/tetrad/search/FciDsepLegalPairsCfci.java
/////////////////////////////////////////////////////////////////////////////// // For information as to what this class does, see the Javadoc, below. // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, // // 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph // // Ramsey, and Clark Glymour. // // // // 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 // /////////////////////////////////////////////////////////////////////////////// package edu.cmu.tetrad.search; import edu.cmu.tetrad.graph.Graph; import edu.cmu.tetrad.graph.Node; import edu.cmu.tetrad.graph.Triple; import java.util.List; import java.util.Set; /** * Specifies what coefs as a legal pair of edges X---Y---Z for purposes of calculating possible d-separation sets for * the FCI algorithm. In this case, legal initial edges are those adjacent to initial nodes, and legal pairs of edges * are those for which either X-->Y<--Z or X is adjacent to Z--i.e. X, Y, and Z form a triangle. (It is assumed (and * checked) that is adjacent to Y and Y is adjacent to Z.) * * @author Joseph Ramsey */ class FciDsepLegalPairsCfci implements LegalPairs { /** * Graph with respect to which graph properties are tested. */ private Graph graph; private Set<Triple> ambiguousTriples; /** * Constructs a new legal pairs object. See class level doc. * * @param graph The graph with respect to which legal pairs will be tested. */ public FciDsepLegalPairsCfci(Graph graph, Set<Triple> unfaithfulTriples) { if (graph == null) { throw new NullPointerException(); } this.graph = graph; this.ambiguousTriples = unfaithfulTriples; } /** * @return true iff x is adjacent to y. */ public boolean isLegalFirstEdge(Node x, Node y) { return this.graph.isAdjacentTo(x, y); } /** * @return true iff x-->y<--z or else x is adjacent to z. * @throws IllegalArgumentException if x is not adjacent to y or y is not adjacent to z. */ public boolean isLegalPair(Node x, Node y, Node z, List<Node> c, List<Node> d) { if (!(graph.isAdjacentTo(x, y)) || !(graph.isAdjacentTo(y, z))) { throw new IllegalArgumentException(); } if (graph.isDefCollider(x, y, z)) { return true; } // if (graph.getEndpoint(x, y) == Endpoint.TAIL || graph.getEndpoint(z, y) == Endpoint.TAIL) { // return false; // } if (ambiguousTriples.contains(new Triple(x, y, z))) { return true; } return graph.isAdjacentTo(x, z); } }
3,821
Java
.java
79
43.556962
117
0.559313
vineet1992/tetrad-vineet
2
1
4
GPL-2.0
9/5/2024, 12:08:25 AM (Europe/Amsterdam)
false
false
true
true
false
true
false
true
3,821
3,158,476
SchemaEditorToolBar.java
ModelWriter_WP3/Source/eu.modelwriter.visualization.jgrapx/examples/com/mxgraph/examples/swing/editor/SchemaEditorToolBar.java
package com.mxgraph.examples.swing.editor; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JComboBox; import javax.swing.JOptionPane; import javax.swing.JToolBar; import javax.swing.TransferHandler; import com.mxgraph.examples.swing.editor.EditorActions.HistoryAction; import com.mxgraph.examples.swing.editor.EditorActions.NewAction; import com.mxgraph.examples.swing.editor.EditorActions.OpenAction; import com.mxgraph.examples.swing.editor.EditorActions.PrintAction; import com.mxgraph.examples.swing.editor.EditorActions.SaveAction; import com.mxgraph.swing.mxGraphComponent; import com.mxgraph.swing.util.mxGraphActions; import com.mxgraph.util.mxEvent; import com.mxgraph.util.mxEventObject; import com.mxgraph.util.mxResources; import com.mxgraph.util.mxEventSource.mxIEventListener; import com.mxgraph.view.mxGraphView; public class SchemaEditorToolBar extends JToolBar { /** * */ private static final long serialVersionUID = -3979320704834605323L; /** * * @param frame * @param orientation */ private boolean ignoreZoomChange = false; /** * */ public SchemaEditorToolBar(final BasicGraphEditor editor, int orientation) { super(orientation); setBorder(BorderFactory.createCompoundBorder(BorderFactory .createEmptyBorder(3, 3, 3, 3), getBorder())); setFloatable(false); add(editor.bind("New", new NewAction(), "/com/mxgraph/examples/swing/images/new.gif")); add(editor.bind("Open", new OpenAction(), "/com/mxgraph/examples/swing/images/open.gif")); add(editor.bind("Save", new SaveAction(false), "/com/mxgraph/examples/swing/images/save.gif")); addSeparator(); add(editor.bind("Print", new PrintAction(), "/com/mxgraph/examples/swing/images/print.gif")); addSeparator(); add(editor.bind("Cut", TransferHandler.getCutAction(), "/com/mxgraph/examples/swing/images/cut.gif")); add(editor.bind("Copy", TransferHandler.getCopyAction(), "/com/mxgraph/examples/swing/images/copy.gif")); add(editor.bind("Paste", TransferHandler.getPasteAction(), "/com/mxgraph/examples/swing/images/paste.gif")); addSeparator(); add(editor.bind("Delete", mxGraphActions.getDeleteAction(), "/com/mxgraph/examples/swing/images/delete.gif")); addSeparator(); add(editor.bind("Undo", new HistoryAction(true), "/com/mxgraph/examples/swing/images/undo.gif")); add(editor.bind("Redo", new HistoryAction(false), "/com/mxgraph/examples/swing/images/redo.gif")); addSeparator(); final mxGraphView view = editor.getGraphComponent().getGraph() .getView(); final JComboBox zoomCombo = new JComboBox(new Object[] { "400%", "200%", "150%", "100%", "75%", "50%", mxResources.get("page"), mxResources.get("width"), mxResources.get("actualSize") }); zoomCombo.setEditable(true); zoomCombo.setMinimumSize(new Dimension(75, 0)); zoomCombo.setPreferredSize(new Dimension(75, 0)); zoomCombo.setMaximumSize(new Dimension(75, 100)); zoomCombo.setMaximumRowCount(9); add(zoomCombo); // Sets the zoom in the zoom combo the current value mxIEventListener scaleTracker = new mxIEventListener() { /** * */ public void invoke(Object sender, mxEventObject evt) { ignoreZoomChange = true; try { zoomCombo.setSelectedItem((int) Math.round(100 * view .getScale()) + "%"); } finally { ignoreZoomChange = false; } } }; // Installs the scale tracker to update the value in the combo box // if the zoom is changed from outside the combo box view.getGraph().getView().addListener(mxEvent.SCALE, scaleTracker); view.getGraph().getView().addListener(mxEvent.SCALE_AND_TRANSLATE, scaleTracker); // Invokes once to sync with the actual zoom value scaleTracker.invoke(null, null); zoomCombo.addActionListener(new ActionListener() { /** * */ public void actionPerformed(ActionEvent e) { mxGraphComponent graphComponent = editor.getGraphComponent(); // Zoomcombo is changed when the scale is changed in the diagram // but the change is ignored here if (!ignoreZoomChange) { String zoom = zoomCombo.getSelectedItem().toString(); if (zoom.equals(mxResources.get("page"))) { graphComponent.setPageVisible(true); graphComponent .setZoomPolicy(mxGraphComponent.ZOOM_POLICY_PAGE); } else if (zoom.equals(mxResources.get("width"))) { graphComponent.setPageVisible(true); graphComponent .setZoomPolicy(mxGraphComponent.ZOOM_POLICY_WIDTH); } else if (zoom.equals(mxResources.get("actualSize"))) { graphComponent.zoomActual(); } else { try { zoom = zoom.replace("%", ""); double scale = Math.min(16, Math.max(0.01, Double.parseDouble(zoom) / 100)); graphComponent.zoomTo(scale, graphComponent .isCenterZoom()); } catch (Exception ex) { JOptionPane.showMessageDialog(editor, ex .getMessage()); } } } } }); } }
5,151
Java
.java
156
28.75
75
0.721328
ModelWriter/WP3
4
1
55
EPL-1.0
9/4/2024, 11:01:53 PM (Europe/Amsterdam)
false
true
true
true
true
true
true
true
5,151
1,317,116
B.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameType/test48/out/B.java
//renaming A to B package p; class B{ B ( ){}; }; class C{ void s(){ new p . B ( ); } };
92
Java
.java
10
7.9
17
0.518072
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
92
745,350
PropertyListBuilder.java
LawnchairLauncher_Lawnchair-V1/app/src/main/java/ch/deletescape/lawnchair/anim/PropertyListBuilder.java
package ch.deletescape.lawnchair.anim; import android.animation.PropertyValuesHolder; import android.view.View; import java.util.ArrayList; public class PropertyListBuilder { private final ArrayList<PropertyValuesHolder> mProperties = new ArrayList<>(); public PropertyListBuilder translationX(float f) { mProperties.add(PropertyValuesHolder.ofFloat(View.TRANSLATION_X, f)); return this; } public PropertyListBuilder translationY(float f) { mProperties.add(PropertyValuesHolder.ofFloat(View.TRANSLATION_Y, f)); return this; } public PropertyListBuilder scaleX(float f) { mProperties.add(PropertyValuesHolder.ofFloat(View.SCALE_X, f)); return this; } public PropertyListBuilder scaleY(float f) { mProperties.add(PropertyValuesHolder.ofFloat(View.SCALE_Y, f)); return this; } public PropertyListBuilder scale(float f) { return scaleX(f).scaleY(f); } public PropertyValuesHolder[] build() { return mProperties.toArray(new PropertyValuesHolder[mProperties.size()]); } }
1,106
Java
.java
29
32.310345
82
0.731525
LawnchairLauncher/Lawnchair-V1
93
43
0
GPL-3.0
9/4/2024, 7:08:37 PM (Europe/Amsterdam)
false
false
false
true
true
false
true
true
1,106
2,488,520
BreakpointType.java
Spacecraft-Code_SPELL/src/spel-gui/com.astra.ses.spell.gui.core/src/com/astra/ses/spell/gui/core/model/types/BreakpointType.java
/////////////////////////////////////////////////////////////////////////////// // // PACKAGE : com.astra.ses.spell.gui.core.model.types // // FILE : BreakpointType.java // // DATE : 2010-08-24 // // Copyright (C) 2008, 2015 SES ENGINEERING, Luxembourg S.A.R.L. // // By using this software in any way, you are agreeing to be bound by // the terms of this license. // // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // which accompanies this distribution, and is available at // http://www.eclipse.org/legal/epl-v10.html // // NO WARRANTY // EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED // ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER // EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR // CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A // PARTICULAR PURPOSE. Each Recipient is solely responsible for determining // the appropriateness of using and distributing the Program and assumes all // risks associated with its exercise of rights under this Agreement , // including but not limited to the risks and costs of program errors, // compliance with applicable laws, damage to or loss of data, programs or // equipment, and unavailability or interruption of operations. // // DISCLAIMER OF LIABILITY // EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY // CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION // LOST PROFITS), 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 OR DISTRIBUTION OF THE PROGRAM OR THE // EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGES. // // Contributors: // SES ENGINEERING - initial API and implementation and/or initial documentation // // PROJECT : SPELL // // SUBPROJECT: SPELL GUI Client // /////////////////////////////////////////////////////////////////////////////// package com.astra.ses.spell.gui.core.model.types; /****************************************************************************** * * Breakpoint type to distinguish between different breakpoints *****************************************************************************/ public enum BreakpointType { // PERMANENT BREAKPOINTS PERSIST ALONG THE PROCEDURE EXECUTION PERMANENT, // TEMPORARY BREAKPOINTS ARE REMOEVD ONCE THEY ARE REACHED THE FIRST TIME TEMPORARY, // UNKNOWN STATUS MEANS NO BREAKPOINT IS CONSIDERED FOR A LINE UNKNOWN; }
2,764
Java
.java
62
43.354839
83
0.688033
Spacecraft-Code/SPELL
7
3
1
GPL-3.0
9/4/2024, 9:40:21 PM (Europe/Amsterdam)
false
false
true
true
false
true
false
true
2,764
2,916,323
UNCONNECTED_PING.java
BlockServerProject_JRakLib/src/main/java/net/beaconpe/jraklib/protocol/UNCONNECTED_PING.java
/** * JRakLib is not affiliated with Jenkins Software LLC or RakNet. * This software is a port of RakLib https://github.com/PocketMine/RakLib. * This file is part of JRakLib. * * JRakLib 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 3 of the License, or * (at your option) any later version. * * JRakLib 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 JRakLib. If not, see <http://www.gnu.org/licenses/>. */ package net.beaconpe.jraklib.protocol; import net.beaconpe.jraklib.JRakLib; /** * UNCONNECTED_PING (Not encapsulated, 0x01) */ public class UNCONNECTED_PING extends Packet{ public static byte ID = 0x01; public long pingId; public byte getID() { return 0x01; } @Override protected void _encode() { putLong(pingId); put(JRakLib.MAGIC); } @Override protected void _decode() { pingId = getLong(); //magic } }
1,331
Java
.java
40
29.625
78
0.719626
BlockServerProject/JRakLib
5
5
2
LGPL-3.0
9/4/2024, 10:34:54 PM (Europe/Amsterdam)
false
false
true
true
false
true
false
true
1,331
1,315,071
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameNonPrivateField/testFail14/in/A.java
package p; class A{ int f; } class B extends A{ A a; int m(){ int g; return f; } }
90
Java
.java
11
6.545455
18
0.6125
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
90
4,341,903
ThirteensSimulation.java
jvonk_CompSci/03-28/ElevensLab/Activity Starter Code/Activity11 Starter Code/ThirteensSimulation.java
/** * This is a class that simulates games of Thirteens. * See accompanying documents for a description of how Thirteens is played. */ public class ThirteensSimulation { /** * The number of games of Thirteens to play. */ private static final int GAMES_TO_PLAY = 1000; /** * Flag used to control debugging print statements. */ private static final boolean I_AM_DEBUGGING = false; /** * @param args is not used. */ public static void main(String[] args) { ThirteensBoard board = new ThirteensBoard(); int wins = 0; for (int k = 0; k < GAMES_TO_PLAY; k++) { if (I_AM_DEBUGGING) { System.out.println(board); } while (board.playIfPossible()) { if (I_AM_DEBUGGING) { System.out.println(board); } } if (board.gameIsWon()) { wins++; } board.newGame(); } double percentWon = (int) (1000.0 * wins / GAMES_TO_PLAY + 0.5) / 10.0; System.out.println("Games won: " + wins); System.out.println("Games played: " + GAMES_TO_PLAY); System.out.println("Percent won: " + percentWon + "%"); } }
1,064
Java
.java
39
24.076923
75
0.656526
jvonk/CompSci
2
0
0
GPL-3.0
9/5/2024, 12:09:51 AM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
1,064
5,136,286
SimpleSkeletonEmbodiment.java
ArticulatedSocialAgentsPlatform_AsapEnvironment/HmiAnimationEmbodiments/src/hmi/animationembodiments/SimpleSkeletonEmbodiment.java
/******************************************************************************* * Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands * * This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer). * * ASAPRealizer is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License (LGPL) as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ASAPRealizer 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 Lesser General Public License * along with ASAPRealizer. If not, see http://www.gnu.org/licenses/. ******************************************************************************/ package hmi.animationembodiments; import hmi.animation.VJoint; /** * Simple implementation of a SkeletonEmbodiment with a VJoint. * @author Herwin * */ public class SimpleSkeletonEmbodiment implements SkeletonEmbodiment { private final String id; private final VJoint animationJoint; public SimpleSkeletonEmbodiment(String id, VJoint vj) { this.id = id; this.animationJoint = vj; } @Override public void copy() { animationJoint.calculateMatrices(); } @Override public String getId() { return id; } @Override public VJoint getAnimationVJoint() { return animationJoint; } }
1,706
Java
.java
50
30.4
91
0.667071
ArticulatedSocialAgentsPlatform/AsapEnvironment
1
2
0
LGPL-3.0
9/5/2024, 12:42:05 AM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
1,706
4,951,884
AsyncHttpRequest.java
lookwhatlook_WeiboWeiBaTong/libs/LoginBeebo-android-async-http/src/com/loopj/android/http/AsyncHttpRequest.java
/* Android Asynchronous Http Client Copyright (c) 2011 James Smith <[email protected]> http://loopj.com 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.loopj.android.http; import android.util.Log; import org.apache.http.HttpResponse; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.AbstractHttpClient; import org.apache.http.protocol.HttpContext; import java.io.IOException; import java.net.MalformedURLException; import java.net.UnknownHostException; import java.util.concurrent.atomic.AtomicBoolean; /** * Internal class, representing the HttpRequest, done in asynchronous manner */ public class AsyncHttpRequest implements Runnable { private final AbstractHttpClient client; private final HttpContext context; private final HttpUriRequest request; private final ResponseHandlerInterface responseHandler; private int executionCount; private final AtomicBoolean isCancelled = new AtomicBoolean(); private boolean cancelIsNotified; private volatile boolean isFinished; private boolean isRequestPreProcessed; public AsyncHttpRequest(AbstractHttpClient client, HttpContext context, HttpUriRequest request, ResponseHandlerInterface responseHandler) { this.client = Utils.notNull(client, "client"); this.context = Utils.notNull(context, "context"); this.request = Utils.notNull(request, "request"); this.responseHandler = Utils.notNull(responseHandler, "responseHandler"); } /** * This method is called once by the system when the request is about to be * processed by the system. The library makes sure that a single request * is pre-processed only once. * * Please note: pre-processing does NOT run on the main thread, and thus * any UI activities that you must perform should be properly dispatched to * the app's UI thread. * * @param request The request to pre-process */ public void onPreProcessRequest(AsyncHttpRequest request) { // default action is to do nothing... } /** * This method is called once by the system when the request has been fully * sent, handled and finished. The library makes sure that a single request * is post-processed only once. * * Please note: post-processing does NOT run on the main thread, and thus * any UI activities that you must perform should be properly dispatched to * the app's UI thread. * * @param request The request to post-process */ public void onPostProcessRequest(AsyncHttpRequest request) { // default action is to do nothing... } @Override public void run() { if (isCancelled()) { return; } // Carry out pre-processing for this request only once. if (!isRequestPreProcessed) { isRequestPreProcessed = true; onPreProcessRequest(this); } if (isCancelled()) { return; } responseHandler.sendStartMessage(); if (isCancelled()) { return; } try { makeRequestWithRetries(); } catch (IOException e) { if (!isCancelled()) { responseHandler.sendFailureMessage(0, null, null, e); } else { Log.e("AsyncHttpRequest", "makeRequestWithRetries returned error", e); } } if (isCancelled()) { return; } responseHandler.sendFinishMessage(); if (isCancelled()) { return; } // Carry out post-processing for this request. onPostProcessRequest(this); isFinished = true; } private void makeRequest() throws IOException { if (isCancelled()) { return; } // Fixes #115 if (request.getURI().getScheme() == null) { // subclass of IOException so processed in the caller throw new MalformedURLException("No valid URI scheme was provided"); } if (responseHandler instanceof RangeFileAsyncHttpResponseHandler) { ((RangeFileAsyncHttpResponseHandler) responseHandler).updateRequestHeaders(request); } HttpResponse response = client.execute(request, context); if (isCancelled()) { return; } // Carry out pre-processing for this response. responseHandler.onPreProcessResponse(responseHandler, response); if (isCancelled()) { return; } // The response is ready, handle it. responseHandler.sendResponseMessage(response); if (isCancelled()) { return; } // Carry out post-processing for this response. responseHandler.onPostProcessResponse(responseHandler, response); } private void makeRequestWithRetries() throws IOException { boolean retry = true; IOException cause = null; HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler(); try { while (retry) { try { makeRequest(); return; } catch (UnknownHostException e) { // switching between WI-FI and mobile data networks can cause a retry which then results in an UnknownHostException // while the WI-FI is initialising. The retry logic will be invoked here, if this is NOT the first retry // (to assist in genuine cases of unknown host) which seems better than outright failure cause = new IOException("UnknownHostException exception: " + e.getMessage()); retry = (executionCount > 0) && retryHandler.retryRequest(cause, ++executionCount, context); } catch (NullPointerException e) { // there's a bug in HttpClient 4.0.x that on some occasions causes // DefaultRequestExecutor to throw an NPE, see // http://code.google.com/p/android/issues/detail?id=5255 cause = new IOException("NPE in HttpClient: " + e.getMessage()); retry = retryHandler.retryRequest(cause, ++executionCount, context); } catch (IOException e) { if (isCancelled()) { // Eating exception, as the request was cancelled return; } cause = e; retry = retryHandler.retryRequest(cause, ++executionCount, context); } if (retry) { responseHandler.sendRetryMessage(executionCount); } } } catch (Exception e) { // catch anything else to ensure failure message is propagated Log.e("AsyncHttpRequest", "Unhandled exception origin cause", e); cause = new IOException("Unhandled exception: " + e.getMessage()); } // cleaned up to throw IOException throw (cause); } public boolean isCancelled() { boolean cancelled = isCancelled.get(); if (cancelled) { sendCancelNotification(); } return cancelled; } private synchronized void sendCancelNotification() { if (!isFinished && isCancelled.get() && !cancelIsNotified) { cancelIsNotified = true; responseHandler.sendCancelMessage(); } } public boolean isDone() { return isCancelled() || isFinished; } public boolean cancel(boolean mayInterruptIfRunning) { isCancelled.set(true); request.abort(); return isCancelled(); } }
8,363
Java
.java
201
32.228856
143
0.640202
lookwhatlook/WeiboWeiBaTong
1
1
0
GPL-3.0
9/5/2024, 12:37:05 AM (Europe/Amsterdam)
false
true
true
true
true
true
true
true
8,363
55,924
TerminalSession.java
subhra74_snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/ui/TerminalSession.java
package com.jediterm.terminal.ui; import com.jediterm.terminal.Terminal; import com.jediterm.terminal.TtyConnector; import com.jediterm.terminal.debug.DebugBufferType; import com.jediterm.terminal.model.TerminalTextBuffer; /** * @author traff */ public interface TerminalSession { void start(); String getBufferText(DebugBufferType type); TerminalTextBuffer getTerminalTextBuffer(); Terminal getTerminal(); TtyConnector getTtyConnector(); String getSessionName(); void close(); }
504
Java
.java
17
27.235294
54
0.820459
subhra74/snowflake
2,148
231
174
GPL-3.0
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
504
4,832,769
DispenserBehaviorFire.java
herpingdo_Hakkit/net/minecraft/src/DispenserBehaviorFire.java
package net.minecraft.src; final class DispenserBehaviorFire extends BehaviorDefaultDispenseItem { private boolean field_96466_b = true; /** * Dispense the specified stack, play the dispense sound and spawn particles. */ protected ItemStack dispenseStack(IBlockSource par1IBlockSource, ItemStack par2ItemStack) { EnumFacing var3 = BlockDispenser.getFacing(par1IBlockSource.getBlockMetadata()); World var4 = par1IBlockSource.getWorld(); int var5 = par1IBlockSource.getXInt() + var3.getFrontOffsetX(); int var6 = par1IBlockSource.getYInt() + var3.getFrontOffsetY(); int var7 = par1IBlockSource.getZInt() + var3.getFrontOffsetZ(); if (var4.isAirBlock(var5, var6, var7)) { var4.setBlock(var5, var6, var7, Block.fire.blockID); if (par2ItemStack.attemptDamageItem(1, var4.rand)) { par2ItemStack.stackSize = 0; } } else if (var4.getBlockId(var5, var6, var7) == Block.tnt.blockID) { Block.tnt.onBlockDestroyedByPlayer(var4, var5, var6, var7, 1); var4.setBlockToAir(var5, var6, var7); } else { this.field_96466_b = false; } return par2ItemStack; } /** * Play the dispense sound from the specified block. */ protected void playDispenseSound(IBlockSource par1IBlockSource) { if (this.field_96466_b) { par1IBlockSource.getWorld().playAuxSFX(1000, par1IBlockSource.getXInt(), par1IBlockSource.getYInt(), par1IBlockSource.getZInt(), 0); } else { par1IBlockSource.getWorld().playAuxSFX(1001, par1IBlockSource.getXInt(), par1IBlockSource.getYInt(), par1IBlockSource.getZInt(), 0); } } }
1,825
Java
.java
48
29.645833
144
0.645963
herpingdo/Hakkit
1
0
0
GPL-3.0
9/5/2024, 12:33:06 AM (Europe/Amsterdam)
false
false
true
true
false
true
false
true
1,825
3,414,986
ConstantDoubleInfo.java
lrytz_sclasslib/src/org/gjt/jclasslib/structures/constants/ConstantDoubleInfo.java
/* This library 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. */ package org.gjt.jclasslib.structures.constants; import org.gjt.jclasslib.structures.InvalidByteCodeException; import java.io.*; /** Describes a <tt>CONSTANT_Double_info</tt> constant pool data structure. @author <a href="mailto:[email protected]">Ingo Kegel</a> @version $Revision: 1.4 $ $Date: 2003/08/20 17:14:37 $ */ public class ConstantDoubleInfo extends ConstantLargeNumeric { public byte getTag() { return CONSTANT_DOUBLE; } public String getTagVerbose() { return CONSTANT_DOUBLE_VERBOSE; } public String getVerbose() throws InvalidByteCodeException { return String.valueOf(getDouble()); } /** Get the double value of this constant pool entry. @return the value */ public double getDouble() { long longBits = (long)highBytes << 32 | (long)lowBytes & 0xFFFFFFFFL; return Double.longBitsToDouble(longBits); } /** Set the double value of this constant pool entry. @param number the value */ public void setDouble(double number) { long longBits = Double.doubleToLongBits(number); highBytes = (int)(longBits >>> 32 & 0xFFFFFFFFL); lowBytes = (int)(longBits & 0xFFFFFFFFL); } public void read(DataInput in) throws InvalidByteCodeException, IOException { super.read(in); if (debug) debug("read "); } public void write(DataOutput out) throws InvalidByteCodeException, IOException { out.writeByte(CONSTANT_DOUBLE); super.write(out); if (debug) debug("wrote "); } protected void debug(String message) { super.debug(message + getTagVerbose() + " with high_bytes " + highBytes + " and low_bytes " + lowBytes); } }
2,092
Java
.java
57
30
82
0.673183
lrytz/sclasslib
3
1
0
GPL-2.0
9/4/2024, 11:24:01 PM (Europe/Amsterdam)
true
true
true
true
true
true
true
true
2,092
1,695,826
Class68_Sub6.java
moparisthebest_MoparScape/clients/client508/src/main/java/Class68_Sub6.java
/* Class68_Sub6 - Decompiled by JODE * Visit http://jode.sourceforge.net/ */ public class Class68_Sub6 extends Class68 { public static int anInt2836; public static int anInt2837; public static boolean aBoolean2838 = true; public int anInt2839; public static int anInt2840; public static int anInt2841; public static int anInt2842; public static Class21_Sub1 aClass21_Sub1_2843; public static Login aLogin_2844 = new Login(64); public int anInt2845; public static int anInt2846; public static Class68_Sub20_Sub1 aClass68_Sub20_Sub1_2847; public static void method664(byte i) { aClass21_Sub1_2843 = null; aLogin_2844 = null; aClass68_Sub20_Sub1_2847 = null; int i_0_ = -79 % (-i / 46); } public Class68_Sub6(int i, int i_1_) { anInt2845 = i_1_; anInt2839 = i; } }
909
Java
.java
27
27.222222
63
0.657534
moparisthebest/MoparScape
19
8
0
AGPL-3.0
9/4/2024, 8:15:08 PM (Europe/Amsterdam)
false
false
true
true
false
true
false
true
909
3,674,292
ExecutorBizImpl.java
SaberSola_xxl-job/xxl-job-core/src/main/java/com/xxl/job/core/biz/impl/ExecutorBizImpl.java
package com.xxl.job.core.biz.impl; import com.xxl.job.core.biz.ExecutorBiz; import com.xxl.job.core.biz.model.LogResult; import com.xxl.job.core.biz.model.ReturnT; import com.xxl.job.core.biz.model.TriggerParam; import com.xxl.job.core.enums.ExecutorBlockStrategyEnum; import com.xxl.job.core.executor.XxlJobExecutor; import com.xxl.job.core.glue.GlueFactory; import com.xxl.job.core.glue.GlueTypeEnum; import com.xxl.job.core.handler.IJobHandler; import com.xxl.job.core.handler.impl.GlueJobHandler; import com.xxl.job.core.handler.impl.ScriptJobHandler; import com.xxl.job.core.log.XxlJobFileAppender; import com.xxl.job.core.thread.JobThread; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; /** * Created by xuxueli on 17/3/1. */ public class ExecutorBizImpl implements ExecutorBiz { private static Logger logger = LoggerFactory.getLogger(ExecutorBizImpl.class); @Override public ReturnT<String> beat() { return ReturnT.SUCCESS; } @Override public ReturnT<String> idleBeat(int jobId) { // isRunningOrHasQueue boolean isRunningOrHasQueue = false; JobThread jobThread = XxlJobExecutor.loadJobThread(jobId); if (jobThread != null && jobThread.isRunningOrHasQueue()) { isRunningOrHasQueue = true; } if (isRunningOrHasQueue) { return new ReturnT<String>(ReturnT.FAIL_CODE, "job thread is running or has trigger queue."); } return ReturnT.SUCCESS; } @Override public ReturnT<String> kill(int jobId) { // kill handlerThread, and create new one JobThread jobThread = XxlJobExecutor.loadJobThread(jobId); if (jobThread != null) { XxlJobExecutor.removeJobThread(jobId, "scheduling center kill job."); return ReturnT.SUCCESS; } return new ReturnT<String>(ReturnT.SUCCESS_CODE, "job thread aleady killed."); } @Override public ReturnT<LogResult> log(long logDateTim, int logId, int fromLineNum) { // log filename: logPath/yyyy-MM-dd/9999.log String logFileName = XxlJobFileAppender.makeLogFileName(new Date(logDateTim), logId); LogResult logResult = XxlJobFileAppender.readLog(logFileName, fromLineNum); return new ReturnT<LogResult>(logResult); } @Override public ReturnT<String> run(TriggerParam triggerParam) { // load old:jobHandler + jobThread JobThread jobThread = XxlJobExecutor.loadJobThread(triggerParam.getJobId()); IJobHandler jobHandler = jobThread!=null?jobThread.getHandler():null; String removeOldReason = null; // valid:jobHandler + jobThread GlueTypeEnum glueTypeEnum = GlueTypeEnum.match(triggerParam.getGlueType()); if (GlueTypeEnum.BEAN == glueTypeEnum) { // new jobhandler IJobHandler newJobHandler = XxlJobExecutor.loadJobHandler(triggerParam.getExecutorHandler()); // valid old jobThread if (jobThread!=null && jobHandler != newJobHandler) { // change handler, need kill old thread removeOldReason = "change jobhandler or glue type, and terminate the old job thread."; jobThread = null; jobHandler = null; } // valid handler if (jobHandler == null) { jobHandler = newJobHandler; if (jobHandler == null) { return new ReturnT<String>(ReturnT.FAIL_CODE, "job handler [" + triggerParam.getExecutorHandler() + "] not found."); } } } else if (GlueTypeEnum.GLUE_GROOVY == glueTypeEnum) { // valid old jobThread if (jobThread != null && !(jobThread.getHandler() instanceof GlueJobHandler && ((GlueJobHandler) jobThread.getHandler()).getGlueUpdatetime()==triggerParam.getGlueUpdatetime() )) { // change handler or gluesource updated, need kill old thread removeOldReason = "change job source or glue type, and terminate the old job thread."; jobThread = null; jobHandler = null; } // valid handler if (jobHandler == null) { try { IJobHandler originJobHandler = GlueFactory.getInstance().loadNewInstance(triggerParam.getGlueSource()); jobHandler = new GlueJobHandler(originJobHandler, triggerParam.getGlueUpdatetime()); } catch (Exception e) { logger.error(e.getMessage(), e); return new ReturnT<String>(ReturnT.FAIL_CODE, e.getMessage()); } } } else if (glueTypeEnum!=null && glueTypeEnum.isScript()) { // valid old jobThread if (jobThread != null && !(jobThread.getHandler() instanceof ScriptJobHandler && ((ScriptJobHandler) jobThread.getHandler()).getGlueUpdatetime()==triggerParam.getGlueUpdatetime() )) { // change script or gluesource updated, need kill old thread removeOldReason = "change job source or glue type, and terminate the old job thread."; jobThread = null; jobHandler = null; } // valid handler if (jobHandler == null) { jobHandler = new ScriptJobHandler(triggerParam.getJobId(), triggerParam.getGlueUpdatetime(), triggerParam.getGlueSource(), GlueTypeEnum.match(triggerParam.getGlueType())); } } else { return new ReturnT<String>(ReturnT.FAIL_CODE, "glueType[" + triggerParam.getGlueType() + "] is not valid."); } // executor block strategy if (jobThread != null) { ExecutorBlockStrategyEnum blockStrategy = ExecutorBlockStrategyEnum.match(triggerParam.getExecutorBlockStrategy(), null); if (ExecutorBlockStrategyEnum.DISCARD_LATER == blockStrategy) { // discard when running if (jobThread.isRunningOrHasQueue()) { return new ReturnT<String>(ReturnT.FAIL_CODE, "block strategy effect:"+ExecutorBlockStrategyEnum.DISCARD_LATER.getTitle()); } } else if (ExecutorBlockStrategyEnum.COVER_EARLY == blockStrategy) { // kill running jobThread if (jobThread.isRunningOrHasQueue()) { removeOldReason = "block strategy effect:" + ExecutorBlockStrategyEnum.COVER_EARLY.getTitle(); jobThread = null; } } else { // just queue trigger } } // replace thread (new or exists invalid) if (jobThread == null) { jobThread = XxlJobExecutor.registJobThread(triggerParam.getJobId(), jobHandler, removeOldReason); } // push data to queue ReturnT<String> pushResult = jobThread.pushTriggerQueue(triggerParam); return pushResult; } }
7,112
Java
.java
145
38.068966
187
0.636508
SaberSola/xxl-job
3
1
0
GPL-3.0
9/4/2024, 11:38:03 PM (Europe/Amsterdam)
false
true
false
true
true
true
true
true
7,104
1,501,573
Application.java
WDAqua_Frankenstein/Qanary/qa.qanary_component-DiambiguationProperty-OKBQA/src/main/java/eu/wdaqua/qanary/diambiguationproperty/Application.java
package eu.wdaqua.qanary.diambiguationproperty; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import eu.wdaqua.qanary.component.QanaryComponent; @SpringBootApplication @EnableAutoConfiguration @ComponentScan("eu.wdaqua.qanary.component") /** * basic class for wrapping functionality to a Qanary component * note: there is no need to change something here */ public class Application { /** * this method is needed to make the QanaryComponent in this project known * to the QanaryServiceController in the qanary_component-template * * @return */ @Bean public QanaryComponent qanaryComponent() { return new DiambiguationProperty(); } public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
1,021
Java
.java
29
32.862069
74
0.823171
WDAqua/Frankenstein
26
10
64
GPL-3.0
9/4/2024, 7:54:27 PM (Europe/Amsterdam)
false
false
false
true
true
false
true
true
1,021
1,477,815
EntityAmbientCreature.java
LeafHacker_xdolf/minecraft/net/minecraft/entity/passive/EntityAmbientCreature.java
package net.minecraft.entity.passive; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; public abstract class EntityAmbientCreature extends EntityLiving implements IAnimals { public EntityAmbientCreature(World worldIn) { super(worldIn); } public boolean canBeLeashedTo(EntityPlayer player) { return false; } }
428
Java
.java
15
24.666667
84
0.785366
LeafHacker/xdolf
20
4
0
GPL-3.0
9/4/2024, 7:53:12 PM (Europe/Amsterdam)
false
true
true
true
true
true
true
true
428
1,317,611
A_test0_in.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/InlineTemp/canInline18/A_test0_in.java
package p; class TestInlineLambda0 { private FI fun1() { final FI fi = x -> x++; FI fi1 = fi; // [1] FI fi2; fi2 = fi; // [2] FI[] a = new FI[] {fi, fi}; // [3] FI[][] b = new FI[][] {{fi, fi}, {fi}}; // [4] FI[] c = {fi, fi}; // [5] FI[][] d = {{fi}, {fi}}; // [6] int x1 = fun2(fi); // [7] TestInlineLambda0 c1 = new TestInlineLambda0(fi); // [8] F f1 = (fi_p) -> fi; // [9] F f2 = (fi_p) -> { return fi; // [10] }; f1.bar(fi); // [11] FI fi4 = true ? fi : fi; // [12] return fi; // [13] } private int fun2(FI fi) {return 0;} public TestInlineLambda0(FI fi) { } } @FunctionalInterface interface FI { int foo(int x); } @FunctionalInterface interface F { FI bar(FI fi); }
731
Java
.java
32
20.09375
58
0.525547
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
731
4,321,103
MethodNameFilter.java
manbaum_maple-ir/org.mapleir.topdank-services/src/main/java/org/topdank/banalysis/filter/method/MethodNameFilter.java
package org.topdank.banalysis.filter.method; import org.objectweb.asm.tree.MethodNode; import org.topdank.banalysis.filter.MethodFilter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author sc4re */ public class MethodNameFilter implements MethodFilter { protected final List<String> names; public MethodNameFilter(String...names) { this.names = new ArrayList<>(); this.names.addAll(Arrays.asList(names)); } @Override public boolean accept(MethodNode methodNode) { return names.contains(methodNode.name); } }
601
Java
.java
20
26.3
55
0.751304
manbaum/maple-ir
2
7
0
GPL-3.0
9/5/2024, 12:09:08 AM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
601
1,320,155
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/InferTypeArguments/testCuArrays02/out/A.java
package p; import java.util.Arrays; import java.util.List; class A { void addAll(String[] ss) { List<String> l= Arrays.asList(ss); } }
141
Java
.java
8
15.875
36
0.725191
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
141
4,248,551
ReferenceCounting.java
rockleeprc_sourcecode/ThinkInJava4/polymorphism/ReferenceCounting.java
//: polymorphism/ReferenceCounting.java // Cleaning up shared member objects. import static net.mindview.util.Print.*; class Shared { private int refcount = 0; private static long counter = 0; private final long id = counter++; public Shared() { print("Creating " + this); } public void addRef() { refcount++; } protected void dispose() { if(--refcount == 0) print("Disposing " + this); } public String toString() { return "Shared " + id; } } class Composing { private Shared shared; private static long counter = 0; private final long id = counter++; public Composing(Shared shared) { print("Creating " + this); this.shared = shared; this.shared.addRef(); } protected void dispose() { print("disposing " + this); shared.dispose(); } public String toString() { return "Composing " + id; } } public class ReferenceCounting { public static void main(String[] args) { Shared shared = new Shared(); Composing[] composing = { new Composing(shared), new Composing(shared), new Composing(shared), new Composing(shared), new Composing(shared) }; for(Composing c : composing) c.dispose(); } } /* Output: Creating Shared 0 Creating Composing 0 Creating Composing 1 Creating Composing 2 Creating Composing 3 Creating Composing 4 disposing Composing 0 disposing Composing 1 disposing Composing 2 disposing Composing 3 disposing Composing 4 Disposing Shared 0 *///:~
1,459
Java
.java
55
23.618182
56
0.710921
rockleeprc/sourcecode
2
2
0
GPL-3.0
9/5/2024, 12:07:03 AM (Europe/Amsterdam)
true
true
true
true
true
true
true
true
1,459
3,345,190
CancellableEvent.java
LimeIncOfficial_Stealth-Craft/src/main/java/net/minestom/server/event/trait/CancellableEvent.java
package net.minestom.server.event.trait; import net.minestom.server.event.Event; import net.minestom.server.event.EventDispatcher; /** * Represents an {@link Event} which can be cancelled. * Called using {@link EventDispatcher#callCancellable(CancellableEvent, Runnable)}. */ public interface CancellableEvent extends Event { /** * Gets if the {@link Event} should be cancelled or not. * * @return true if the event should be cancelled */ boolean isCancelled(); /** * Marks the {@link Event} as cancelled or not. * * @param cancel true if the event should be cancelled, false otherwise */ void setCancelled(boolean cancel); }
689
Java
.java
21
28.809524
84
0.715361
LimeIncOfficial/Stealth-Craft
4
0
0
GPL-3.0
9/4/2024, 11:14:21 PM (Europe/Amsterdam)
false
false
false
true
true
false
true
true
689
3,158,534
mxLine.java
ModelWriter_WP3/Source/eu.modelwriter.visualization.jgrapx/src/com/mxgraph/util/mxLine.java
/** * Copyright (c) 2007-2010, Gaudenz Alder, David Benson */ package com.mxgraph.util; import java.awt.geom.Line2D; /** * Implements a line with double precision coordinates. */ public class mxLine extends mxPoint { /** * */ private static final long serialVersionUID = -4730972599169158546L; /** * The end point of the line */ protected mxPoint endPoint; /** * Creates a new line */ public mxLine(mxPoint startPt, mxPoint endPt) { this.setX(startPt.getX()); this.setY(startPt.getY()); this.endPoint = endPt; } /** * Creates a new line */ public mxLine(double startPtX, double startPtY, mxPoint endPt) { x = startPtX; y = startPtY; this.endPoint = endPt; } /** * Returns the end point of the line. * * @return Returns the end point of the line. */ public mxPoint getEndPoint() { return this.endPoint; } /** * Sets the end point of the rectangle. * * @param value The new end point of the line */ public void setEndPoint(mxPoint value) { this.endPoint = value; } /** * Sets the start and end points. */ public void setPoints(mxPoint startPt, mxPoint endPt) { this.setX(startPt.getX()); this.setY(startPt.getY()); this.endPoint = endPt; } /** * Returns the square of the shortest distance from a point to this line. The line is considered * extrapolated infinitely in both directions for the purposes of the calculation. * * @param pt the point whose distance is being measured * @return the square of the distance from the specified point to this line. */ public double ptLineDistSq(mxPoint pt) { return new Line2D.Double(getX(), getY(), endPoint.getX(), endPoint.getY()) .ptLineDistSq(pt.getX(), pt.getY()); } /** * Returns the square of the shortest distance from a point to this line segment. * * @param pt the point whose distance is being measured * @return the square of the distance from the specified point to this segment. */ public double ptSegDistSq(mxPoint pt) { return new Line2D.Double(getX(), getY(), endPoint.getX(), endPoint.getY()) .ptSegDistSq(pt.getX(), pt.getY()); } }
2,213
Java
.java
79
24.189873
98
0.68017
ModelWriter/WP3
4
1
55
EPL-1.0
9/4/2024, 11:01:53 PM (Europe/Amsterdam)
true
true
true
true
true
true
true
true
2,213
1,662
ContentProviderHolder.java
LSPosed_LSPosed/hiddenapi/stubs/src/main/java/android/app/ContentProviderHolder.java
package android.app; import android.content.IContentProvider; public class ContentProviderHolder { public IContentProvider provider; }
141
Java
.java
5
26
40
0.858209
LSPosed/LSPosed
17,042
2,560
4
GPL-3.0
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
141
1,316,189
As.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface/test72/in/As.java
package p; public class As { void r(A foo) { A local= null; foo.m(local); } }
102
Java
.java
7
10.142857
22
0.515789
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
102
1,534,504
ServerStatusInfo.java
VenixPLL_LightProxynetty/src/main/java/pl/venixpll/mc/data/status/ServerStatusInfo.java
/* * LightProxy * Copyright (C) 2021. VenixPLL * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.venixpll.mc.data.status; import lombok.Data; import pl.venixpll.mc.data.chat.Message; @Data public class ServerStatusInfo { private VersionInfo version; private PlayerInfo players; private Message description; private String icon; public ServerStatusInfo(final VersionInfo version, final PlayerInfo players, final Message description, final String icon) { this.version = version; this.players = players; this.description = description; this.icon = icon; } }
1,254
Java
.java
33
34.69697
128
0.752671
VenixPLL/LightProxynetty
23
6
1
AGPL-3.0
9/4/2024, 7:57:39 PM (Europe/Amsterdam)
false
false
false
true
true
false
true
true
1,254
61,684
Slime.java
Luohuayu_CatServer/src/main/java/org/bukkit/entity/Slime.java
package org.bukkit.entity; /** * Represents a Slime. */ public interface Slime extends Mob { /** * @return The size of the slime */ public int getSize(); /** * @param sz The new size of the slime. */ public void setSize(int sz); }
272
Java
.java
14
15.5
43
0.611765
Luohuayu/CatServer
1,967
211
97
LGPL-3.0
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
false
false
false
true
true
true
true
true
272
1,319,634
A_test540.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/locals_out/A_test540.java
package locals_out; public class A_test540 { public void foo() { int i= 0; int[] array= new int[10]; int[] index= new int[1]; extracted(array, index); } protected void extracted(int[] array, int[] index) { /*[*/array[0]= index[0];/*]*/ } }
259
Java
.java
12
19
53
0.632231
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
259
867,764
StaticArray12.java
bing-chou_etherscan-explorer/web3j-app/abi/src/main/java/org/web3j/abi/datatypes/generated/StaticArray12.java
package org.web3j.abi.datatypes.generated; import java.util.List; import org.web3j.abi.datatypes.StaticArray; import org.web3j.abi.datatypes.Type; /** * Auto generated code. * <p><strong>Do not modifiy!</strong> * <p>Please use org.web3j.codegen.AbiTypesGenerator in the * <a href="https://github.com/web3j/web3j/tree/master/codegen">codegen module</a> to update. */ public class StaticArray12<T extends Type> extends StaticArray<T> { public StaticArray12(List<T> values) { super(12, values); } @SafeVarargs public StaticArray12(T... values) { super(12, values); } }
612
Java
.java
19
28.842105
93
0.722034
bing-chou/etherscan-explorer
70
53
5
GPL-3.0
9/4/2024, 7:09:22 PM (Europe/Amsterdam)
false
false
false
true
true
true
true
true
612
1,312,388
ExceptionAttribute.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/views/ExceptionAttribute.java
/******************************************************************************* * Copyright (c) 2000, 2007 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.astview.views; public abstract class ExceptionAttribute extends ASTAttribute { protected Throwable fException= null; public Throwable getException() { return fException; } }
766
Java
.java
20
36.2
81
0.611336
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
true
true
true
true
true
true
true
766
1,317,100
B.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameType/test42/out/B.java
package p; class B { B(B A){} B A(B A){ A= new B(new B(A)); return A; } }
80
Java
.java
8
8.25
21
0.520548
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
80
3,903,566
PropertyInteger.java
IzumiiKonata_mcp-1_8_9-maven/src/main/java/net/minecraft/block/properties/PropertyInteger.java
package net.minecraft.block.properties; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import java.util.Collection; import java.util.Set; public class PropertyInteger extends PropertyHelper<Integer> { private final ImmutableSet<Integer> allowedValues; protected PropertyInteger(String name, int min, int max) { super(name, Integer.class); if (min < 0) { throw new IllegalArgumentException("Min value of " + name + " must be 0 or greater"); } else if (max <= min) { throw new IllegalArgumentException("Max value of " + name + " must be greater than min (" + min + ")"); } else { Set<Integer> set = Sets.newHashSet(); for (int i = min; i <= max; ++i) { set.add(Integer.valueOf(i)); } this.allowedValues = ImmutableSet.copyOf(set); } } public Collection<Integer> getAllowedValues() { return this.allowedValues; } public boolean equals(Object p_equals_1_) { if (this == p_equals_1_) { return true; } else if (p_equals_1_ != null && this.getClass() == p_equals_1_.getClass()) { if (!super.equals(p_equals_1_)) { return false; } else { PropertyInteger propertyinteger = (PropertyInteger) p_equals_1_; return this.allowedValues.equals(propertyinteger.allowedValues); } } else { return false; } } public int hashCode() { int i = super.hashCode(); i = 31 * i + this.allowedValues.hashCode(); return i; } public static PropertyInteger create(String name, int min, int max) { return new PropertyInteger(name, min, max); } /** * Get the name for the given value. */ public String getName(Integer value) { return value.toString(); } }
1,955
Java
.java
53
28.45283
115
0.596296
IzumiiKonata/mcp-1.8.9-maven
3
0
0
GPL-3.0
9/4/2024, 11:47:52 PM (Europe/Amsterdam)
false
true
false
true
false
true
true
true
1,955
1,314,915
Foo.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceIndirection/test16/in/Foo.java
package p; public class Foo { public void foo() { } { foo(); } }
80
Java
.java
8
7.125
20
0.603175
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
80
1,365,596
StubCyPayloadListener.java
cytoscape_cytoscape-api/event-api/src/test/java/org/cytoscape/event/StubCyPayloadListener.java
package org.cytoscape.event; /* * #%L * Cytoscape Event API (event-api) * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2008 - 2021 The Cytoscape Consortium * %% * 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 General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * DOCUMENT ME! */ public interface StubCyPayloadListener extends CyListener { /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ public void handleEvent(StubCyPayloadEvent e); /** * A special method for testing which returns the number of times * that the handleEvent() method had been called. In general, * extensions of the CyListener interface should NOT define other * methods. */ public int getNumCalls(); void setEventHelper(CyEventHelper eh); }
1,351
Java
.java
43
29.046512
72
0.733691
cytoscape/cytoscape-api
21
34
0
LGPL-2.1
9/4/2024, 7:46:06 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
1,351
3,347,638
SplashActivity.java
ArjunKheni_salonspot/app/src/main/java/com/scet/saloonspot/SplashActivity.java
package com.scet.saloonspot; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.Window; import android.view.WindowManager; import androidx.appcompat.app.AppCompatActivity; public class SplashActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_splash); new Handler().postDelayed(new Runnable() { @Override public void run() { Intent intent=new Intent(SplashActivity.this, LoginActivity.class); startActivity(intent); finish(); } },3000); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); getSupportActionBar().hide(); } }
1,105
Java
.java
28
31.428571
83
0.698694
ArjunKheni/salonspot
4
4
1
GPL-2.0
9/4/2024, 11:14:30 PM (Europe/Amsterdam)
false
false
false
true
false
true
true
true
1,105
3,054,984
ActionClickAction.java
mizhousoft_push-sdk/push-sdk-common/src/main/java/com/mizhousoft/push/action/ActionClickAction.java
package com.mizhousoft.push.action; /** * ClickAction * * @version */ public class ActionClickAction extends ClickAction { // 设置通过action打开应用自定义页面时,本字段填写要打开的页面activity对应的action。 private String action; /** * 构造函数 * * @param action */ public ActionClickAction(String action) { super(); this.action = action; } /** * 获取action * * @return */ public String getAction() { return action; } /** * 设置action * * @param action */ public void setAction(String action) { this.action = action; } }
615
Java
.java
39
11.384615
54
0.695565
mizhousoft/push-sdk
5
2
0
EPL-2.0
9/4/2024, 10:44:59 PM (Europe/Amsterdam)
false
false
false
true
true
false
true
true
539
2,726,607
SpreadsheetsClient.java
nogago_nogago/Tracks/MyTracks/src/com/google/android/apps/mytracks/io/gdata/docs/SpreadsheetsClient.java
/* * Copyright 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.gdata.docs; import com.google.wireless.gdata.client.GDataClient; import com.google.wireless.gdata.client.GDataParserFactory; import com.google.wireless.gdata.client.GDataServiceClient; import com.google.wireless.gdata.client.HttpException; import com.google.wireless.gdata.data.Entry; import com.google.wireless.gdata.data.StringUtils; import com.google.wireless.gdata.parser.GDataParser; import com.google.wireless.gdata.parser.ParseException; import com.google.wireless.gdata.serializer.GDataSerializer; import com.google.wireless.gdata2.client.AuthenticationException; import java.io.IOException; import java.io.InputStream; /** * GDataServiceClient for accessing Google Spreadsheets. This client can access * and parse all of the Spreadsheets feed types: Spreadsheets feed, Worksheets * feed, List feed, and Cells feed. Read operations are supported on all feed * types, but only the List and Cells feeds support write operations. (This is a * limitation of the protocol, not this API. Such write access may be added to * the protocol in the future, requiring changes to this implementation.) * * Only 'private' visibility and 'full' projections are currently supported. */ public class SpreadsheetsClient extends GDataServiceClient { /** The name of the service, dictated to be 'wise' by the protocol. */ public static final String SERVICE = "wise"; /** Standard base feed url for spreadsheets. */ public static final String SPREADSHEETS_BASE_FEED_URL = "http://spreadsheets.google.com/feeds/spreadsheets/private/full"; /** * Represents an entry in a GData Spreadsheets meta-feed. */ public static class SpreadsheetEntry extends Entry { } /** * Represents an entry in a GData Worksheets meta-feed. */ public static class WorksheetEntry extends Entry { } /** * Creates a new SpreadsheetsClient. Uses the standard base URL for * spreadsheets feeds. * * @param client The GDataClient that should be used to authenticate requests, * retrieve feeds, etc */ public SpreadsheetsClient(GDataClient client, GDataParserFactory spreadsheetFactory) { super(client, spreadsheetFactory); } @Override public String getServiceName() { return SERVICE; } /** * Returns a parser for the specified feed type. * * @param feedEntryClass the Class of entry type that will be parsed, which * lets this method figure out which parser to create * @param feedUri the URI of the feed to be fetched and parsed * @param authToken the current authToken to use for the request * @return a parser for the indicated feed * @throws AuthenticationException if the authToken is not valid * @throws ParseException if the response from the server could not be parsed */ private GDataParser getParserForTypedFeed( Class<? extends Entry> feedEntryClass, String feedUri, String authToken) throws AuthenticationException, ParseException, IOException { GDataClient gDataClient = getGDataClient(); GDataParserFactory gDataParserFactory = getGDataParserFactory(); try { InputStream is = gDataClient.getFeedAsStream(feedUri, authToken); return gDataParserFactory.createParser(feedEntryClass, is); } catch (HttpException e) { convertHttpExceptionForReads("Could not fetch parser feed.", e); return null; // never reached } } /** * Converts an HTTP exception that happened while reading into the equivalent * local exception. */ public void convertHttpExceptionForReads(String message, HttpException cause) throws AuthenticationException, IOException { switch (cause.getStatusCode()) { case HttpException.SC_FORBIDDEN: case HttpException.SC_UNAUTHORIZED: throw new AuthenticationException(message, cause); case HttpException.SC_GONE: default: throw new IOException(message + ": " + cause.getMessage()); } } @Override public Entry createEntry(String feedUri, String authToken, Entry entry) throws ParseException, IOException { GDataParserFactory factory = getGDataParserFactory(); GDataSerializer serializer = factory.createSerializer(entry); InputStream is; try { is = getGDataClient().createEntry(feedUri, authToken, serializer); } catch (HttpException e) { convertHttpExceptionForWrites(entry.getClass(), "Could not update entry.", e); return null; // never reached. } GDataParser parser = factory.createParser(entry.getClass(), is); try { return parser.parseStandaloneEntry(); } finally { parser.close(); } } /** * Fetches a GDataParser for the indicated feed. The parser can be used to * access the contents of URI. WARNING: because we cannot reliably infer the * feed type from the URI alone, this method assumes the default feed type! * This is probably NOT what you want. Please use the getParserFor[Type]Feed * methods. * * @param feedEntryClass * @param feedUri the URI of the feed to be fetched and parsed * @param authToken the current authToken to use for the request * @return a parser for the indicated feed * @throws ParseException if the response from the server could not be parsed */ @SuppressWarnings("rawtypes") @Override public GDataParser getParserForFeed( Class feedEntryClass, String feedUri, String authToken) throws ParseException, IOException { try { return getParserForTypedFeed(SpreadsheetEntry.class, feedUri, authToken); } catch (AuthenticationException e) { throw new IOException("Authentication Failure: " + e.getMessage()); } } /** * Returns a parser for a Worksheets meta-feed. * * @param feedUri the URI of the feed to be fetched and parsed * @param authToken the current authToken to use for the request * @return a parser for the indicated feed * @throws AuthenticationException if the authToken is not valid * @throws ParseException if the response from the server could not be parsed */ public GDataParser getParserForWorksheetsFeed( String feedUri, String authToken) throws AuthenticationException, ParseException, IOException { return getParserForTypedFeed(WorksheetEntry.class, feedUri, authToken); } /** * Updates an entry. The URI to be updated is taken from <code>entry</code>. * Note that only entries in List and Cells feeds can be updated, so * <code>entry</code> must be of the corresponding type; other types will * result in an exception. * * @param entry the entry to be updated; must include its URI * @param authToken the current authToken to be used for the operation * @return An Entry containing the re-parsed version of the entry returned by * the server in response to the update * @throws ParseException if the server returned an error, if the server's * response was unparseable (unlikely), or if <code>entry</code> is of * a read-only type * @throws IOException on network error */ @Override public Entry updateEntry(Entry entry, String authToken) throws ParseException, IOException { GDataParserFactory factory = getGDataParserFactory(); GDataSerializer serializer = factory.createSerializer(entry); String editUri = entry.getEditUri(); if (StringUtils.isEmpty(editUri)) { throw new ParseException("No edit URI -- cannot update."); } InputStream is; try { is = getGDataClient().updateEntry(editUri, authToken, serializer); } catch (HttpException e) { convertHttpExceptionForWrites(entry.getClass(), "Could not update entry.", e); return null; // never reached } GDataParser parser = factory.createParser(entry.getClass(), is); try { return parser.parseStandaloneEntry(); } finally { parser.close(); } } /** * Converts an HTTP exception which happened while writing to the equivalent * local exception. */ @SuppressWarnings("rawtypes") private void convertHttpExceptionForWrites( Class entryClass, String message, HttpException cause) throws ParseException, IOException { switch (cause.getStatusCode()) { case HttpException.SC_CONFLICT: if (entryClass != null) { InputStream is = cause.getResponseStream(); if (is != null) { parseEntry(entryClass, cause.getResponseStream()); } } throw new IOException(message); case HttpException.SC_BAD_REQUEST: throw new ParseException(message + ": " + cause); case HttpException.SC_FORBIDDEN: case HttpException.SC_UNAUTHORIZED: throw new IOException(message); default: throw new IOException(message + ": " + cause.getMessage()); } } /** * Parses one entry from the input stream. */ @SuppressWarnings("rawtypes") private Entry parseEntry(Class entryClass, InputStream is) throws ParseException, IOException { GDataParser parser = null; try { parser = getGDataParserFactory().createParser(entryClass, is); return parser.parseStandaloneEntry(); } finally { if (parser != null) { parser.close(); } } } }
9,909
Java
.java
246
35.650407
80
0.730187
nogago/nogago
6
0
8
GPL-3.0
9/4/2024, 10:10:16 PM (Europe/Amsterdam)
false
false
false
true
true
false
true
true
9,909
2,238,480
BitSieve.java
shchiu_openjdk/jdk/src/share/classes/java/math/BitSieve.java
/* * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.math; /** * A simple bit sieve used for finding prime number candidates. Allows setting * and clearing of bits in a storage array. The size of the sieve is assumed to * be constant to reduce overhead. All the bits of a new bitSieve are zero, and * bits are removed from it by setting them. * * To reduce storage space and increase efficiency, no even numbers are * represented in the sieve (each bit in the sieve represents an odd number). * The relationship between the index of a bit and the number it represents is * given by * N = offset + (2*index + 1); * Where N is the integer represented by a bit in the sieve, offset is some * even integer offset indicating where the sieve begins, and index is the * index of a bit in the sieve array. * * @see BigInteger * @author Michael McCloskey * @since 1.3 */ class BitSieve { /** * Stores the bits in this bitSieve. */ private long bits[]; /** * Length is how many bits this sieve holds. */ private int length; /** * A small sieve used to filter out multiples of small primes in a search * sieve. */ private static BitSieve smallSieve = new BitSieve(); /** * Construct a "small sieve" with a base of 0. This constructor is * used internally to generate the set of "small primes" whose multiples * are excluded from sieves generated by the main (package private) * constructor, BitSieve(BigInteger base, int searchLen). The length * of the sieve generated by this constructor was chosen for performance; * it controls a tradeoff between how much time is spent constructing * other sieves, and how much time is wasted testing composite candidates * for primality. The length was chosen experimentally to yield good * performance. */ private BitSieve() { length = 150 * 64; bits = new long[(unitIndex(length - 1) + 1)]; // Mark 1 as composite set(0); int nextIndex = 1; int nextPrime = 3; // Find primes and remove their multiples from sieve do { sieveSingle(length, nextIndex + nextPrime, nextPrime); nextIndex = sieveSearch(length, nextIndex + 1); nextPrime = 2*nextIndex + 1; } while((nextIndex > 0) && (nextPrime < length)); } /** * Construct a bit sieve of searchLen bits used for finding prime number * candidates. The new sieve begins at the specified base, which must * be even. */ BitSieve(BigInteger base, int searchLen) { /* * Candidates are indicated by clear bits in the sieve. As a candidates * nonprimality is calculated, a bit is set in the sieve to eliminate * it. To reduce storage space and increase efficiency, no even numbers * are represented in the sieve (each bit in the sieve represents an * odd number). */ bits = new long[(unitIndex(searchLen-1) + 1)]; length = searchLen; int start = 0; int step = smallSieve.sieveSearch(smallSieve.length, start); int convertedStep = (step *2) + 1; // Construct the large sieve at an even offset specified by base MutableBigInteger r = new MutableBigInteger(); MutableBigInteger q = new MutableBigInteger(); do { // Calculate base mod convertedStep r.copyValue(base.mag); r.divideOneWord(convertedStep, q); start = r.value[r.offset]; // Take each multiple of step out of sieve start = convertedStep - start; if (start%2 == 0) start += convertedStep; sieveSingle(searchLen, (start-1)/2, convertedStep); // Find next prime from small sieve step = smallSieve.sieveSearch(smallSieve.length, step+1); convertedStep = (step *2) + 1; } while (step > 0); } /** * Given a bit index return unit index containing it. */ private static int unitIndex(int bitIndex) { return bitIndex >>> 6; } /** * Return a unit that masks the specified bit in its unit. */ private static long bit(int bitIndex) { return 1L << (bitIndex & ((1<<6) - 1)); } /** * Get the value of the bit at the specified index. */ private boolean get(int bitIndex) { int unitIndex = unitIndex(bitIndex); return ((bits[unitIndex] & bit(bitIndex)) != 0); } /** * Set the bit at the specified index. */ private void set(int bitIndex) { int unitIndex = unitIndex(bitIndex); bits[unitIndex] |= bit(bitIndex); } /** * This method returns the index of the first clear bit in the search * array that occurs at or after start. It will not search past the * specified limit. It returns -1 if there is no such clear bit. */ private int sieveSearch(int limit, int start) { if (start >= limit) return -1; int index = start; do { if (!get(index)) return index; index++; } while(index < limit-1); return -1; } /** * Sieve a single set of multiples out of the sieve. Begin to remove * multiples of the specified step starting at the specified start index, * up to the specified limit. */ private void sieveSingle(int limit, int start, int step) { while(start < limit) { set(start); start += step; } } /** * Test probable primes in the sieve and return successful candidates. */ BigInteger retrieve(BigInteger initValue, int certainty, java.util.Random random) { // Examine the sieve one long at a time to find possible primes int offset = 1; for (int i=0; i<bits.length; i++) { long nextLong = ~bits[i]; for (int j=0; j<64; j++) { if ((nextLong & 1) == 1) { BigInteger candidate = initValue.add( BigInteger.valueOf(offset)); if (candidate.primeToCertainty(certainty, random)) return candidate; } nextLong >>>= 1; offset+=2; } } return null; } }
7,617
Java
.java
194
32.010309
87
0.634337
shchiu/openjdk
9
12
0
GPL-2.0
9/4/2024, 8:38:47 PM (Europe/Amsterdam)
false
true
true
true
true
true
true
true
7,617
1,319,044
A_test1250.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/fieldInitializer_out/A_test1250.java
package fieldInitializer_out; public class A_test1250 { private double fRand= extracted(); protected double extracted() { return /*[*/Math.random()/*]*/; } }
165
Java
.java
7
21.571429
35
0.724359
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
165
3,583,712
Matrix4.java
godstale_VR-Defense-Game/rajawali/src/main/java/org/rajawali3d/math/Matrix4.java
/** * Copyright 2013 Dennis Ippel * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.rajawali3d.math; import org.rajawali3d.math.vector.Vector3; import org.rajawali3d.math.vector.Vector3.Axis; import org.rajawali3d.util.ArrayUtils; /** * Encapsulates a column major 4x4 Matrix. * * This class is not thread safe and must be confined to a single thread or protected by * some external locking mechanism if necessary. All static methods are thread safe. * * Rewritten August 8, 2013 by Jared Woolston ([email protected]) with heavy influence from libGDX * @see <a href="https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/math/Matrix4.java"> * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/math/Matrix4.java</a> * * @author dennis.ippel * @author Jared Woolston ([email protected]) * */ public final class Matrix4 { //Matrix indices as column major notation (Row x Column) public static final int M00 = 0; // 0; public static final int M01 = 4; // 1; public static final int M02 = 8; // 2; public static final int M03 = 12; // 3; public static final int M10 = 1; // 4; public static final int M11 = 5; // 5; public static final int M12 = 9; // 6; public static final int M13 = 13; // 7; public static final int M20 = 2; // 8; public static final int M21 = 6; // 9; public static final int M22 = 10; // 10; public static final int M23 = 14; // 11; public static final int M30 = 3; // 12; public static final int M31 = 7; // 13; public static final int M32 = 11; // 14; public static final int M33 = 15; // 15; private double[] m = new double[16]; //The matrix values //The following scratch variables are intentionally left as members //and not static to ensure that this class can be utilized by multiple threads //in a safe manner without the overhead of synchronization. This is a tradeoff of //speed for memory and it is considered a small enough memory increase to be acceptable. private double[] mTmp = new double[16]; //A scratch matrix private float[] mFloat = new float[16]; //A float copy of the values, used for sending to GL. private final Quaternion mQuat = new Quaternion(); //A scratch quaternion. private final Vector3 mVec1 = new Vector3(); //A scratch Vector3 private final Vector3 mVec2 = new Vector3(); //A scratch Vector3 private final Vector3 mVec3 = new Vector3(); //A scratch Vector3 private Matrix4 mMatrix; //A scratch Matrix4 //-------------------------------------------------- // Constructors //-------------------------------------------------- /** * Constructs a default identity {@link Matrix4}. */ public Matrix4() { identity(); } /** * Constructs a new {@link Matrix4} based on the given matrix. * * @param matrix {@link Matrix4} The matrix to clone. */ public Matrix4(final Matrix4 matrix) { setAll(matrix); } /** * Constructs a new {@link Matrix4} based on the provided double array. The array length * must be greater than or equal to 16 and the array will be copied from the 0 index. * * @param matrix double array containing the values for the matrix in column major order. * The array is not modified or referenced after this constructor completes. */ public Matrix4(double[] matrix) { setAll(matrix); } /** * Constructs a new {@link Matrix4} based on the provided float array. The array length * must be greater than or equal to 16 and the array will be copied from the 0 index. * * @param matrix float array containing the values for the matrix in column major order. * The array is not modified or referenced after this constructor completes. */ public Matrix4(float[] matrix) { this(ArrayUtils.convertFloatsToDoubles(matrix)); } /** * Constructs a {@link Matrix4} based on the rotation represented by the provided {@link Quaternion}. * * @param quat {@link Quaternion} The {@link Quaternion} to be copied. */ public Matrix4(final Quaternion quat) { setAll(quat); } //-------------------------------------------------- // Modification methods //-------------------------------------------------- /** * Sets the elements of this {@link Matrix4} based on the elements of the provided {@link Matrix4}. * * @param matrix {@link Matrix4} to copy. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setAll(final Matrix4 matrix) { matrix.toArray(m); return this; } /** * Sets the elements of this {@link Matrix4} based on the provided double array. * The array length must be greater than or equal to 16 and the array will be copied * from the 0 index. * * @param matrix double array containing the values for the matrix in column major order. * The array is not modified or referenced after this constructor completes. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setAll(double[] matrix) { System.arraycopy(matrix, 0, m, 0, 16); return this; } public Matrix4 setAll(float[] matrix) { m[0] = matrix[0]; m[1] = matrix[1]; m[2] = matrix[2]; m[3] = matrix[3]; m[4] = matrix[4]; m[5] = matrix[5]; m[6] = matrix[6]; m[7] = matrix[7]; m[8] = matrix[8]; m[9] = matrix[9]; m[10] = matrix[10]; m[11] = matrix[11]; m[12] = matrix[12]; m[13] = matrix[13]; m[14] = matrix[14]; m[15] = matrix[15]; return this; } /** * Sets the elements of this {@link Matrix4} based on the rotation represented by * the provided {@link Quaternion}. * * @param quat {@link Quaternion} The {@link Quaternion} to represent. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setAll(final Quaternion quat) { quat.toRotationMatrix(m); return this; } /** * Sets the elements of this {@link Matrix4} based on the rotation represented by * the provided quaternion elements. * * @param w double The w component of the quaternion. * @param x double The x component of the quaternion. * @param y double The y component of the quaternion. * @param z double The z component of the quaternion. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setAll(double w, double x, double y, double z) { return setAll(mQuat.setAll(w, x, y, z)); } /** * Sets the four columns of this {@link Matrix4} which correspond to the x-, y-, and z- * axis of the vector space this {@link Matrix4} creates as well as the 4th column representing * the translation of any point that is multiplied by this {@link Matrix4}. * * @param xAxis {@link Vector3} The x axis. * @param yAxis {@link Vector3} The y axis. * @param zAxis {@link Vector3} The z axis. * @param pos {@link Vector3} The translation vector. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setAll(final Vector3 xAxis, final Vector3 yAxis, final Vector3 zAxis, final Vector3 pos) { m[M00] = xAxis.x; m[M01] = yAxis.x; m[M02] = zAxis.x; m[M03] = pos.x; m[M10] = xAxis.y; m[M11] = yAxis.y; m[M12] = zAxis.y; m[M13] = pos.y; m[M20] = xAxis.z; m[M21] = yAxis.z; m[M22] = zAxis.z; m[M23] = pos.z; m[M30] = 0; m[M31] = 0; m[M32] = 0; m[M33] = 1; return this; } /** * Sets the values of this {@link Matrix4} to the values corresponding to a Translation x Scale x Rotation. * This is useful for composing a model matrix as efficiently as possible, eliminating any extraneous calculations. * * @param position {@link Vector3} representing the translation. * @param scale {@link Vector3} representing the scaling. * @param rotation {@link Quaternion} representing the rotation. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setAll(final Vector3 position, final Vector3 scale, final Quaternion rotation) { // Precompute these factors for speed final double x2 = rotation.x * rotation.x; final double y2 = rotation.y * rotation.y; final double z2 = rotation.z * rotation.z; final double xy = rotation.x * rotation.y; final double xz = rotation.x * rotation.z; final double yz = rotation.y * rotation.z; final double wx = rotation.w * rotation.x; final double wy = rotation.w * rotation.y; final double wz = rotation.w * rotation.z; // Column 0 m[M00] = scale.x * (1.0 - 2.0 * (y2 + z2)); m[M10] = 2.0 * scale.y * (xy - wz); m[M20] = 2.0 * scale.z * (xz + wy); m[M30] = 0; // Column 1 m[M01] = 2.0 * scale.x * (xy + wz); m[M11] = scale.y * (1.0 - 2.0 * (x2 + z2)); m[M21] = 2.0 * scale.z * (yz - wx); m[M31] = 0; // Column 2 m[M02] = 2.0 * scale.x * (xz - wy); m[M12] = 2.0 * scale.y * (yz + wx); m[M22] = scale.z * (1.0 - 2.0 * (x2 + y2)); m[M32] = 0; // Column 3 m[M03] = position.x; m[M13] = position.y; m[M23] = position.z; m[M33] = 1.0; return this; } /** * Sets this {@link Matrix4} to an identity matrix. * * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 identity() { m[M00] = 1; m[M10] = 0; m[M20] = 0; m[M30] = 0; m[M01] = 0; m[M11] = 1; m[M21] = 0; m[M31] = 0; m[M02] = 0; m[M12] = 0; m[M22] = 1; m[M32] = 0; m[M03] = 0; m[M13] = 0; m[M23] = 0; m[M33] = 1; return this; } /** * Sets all elements of this {@link Matrix4} to zero. * * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 zero() { for (int i=0; i<16; ++i) { m[i] = 0; } return this; } /** * Calculate the determinant of this {@link Matrix4}. * * @return double The determinant. */ public double determinant() { return m[M30] * m[M21] * m[M12] * m[M03]- m[M20] * m[M31] * m[M12] * m[M03]- m[M30] * m[M11] * m[M22] * m[M03]+ m[M10] * m[M31] * m[M22] * m[M03]+ m[M20] * m[M11] * m[M32] * m[M03]- m[M10] * m[M21] * m[M32] * m[M03]- m[M30] * m[M21] * m[M02] * m[M13]+ m[M20] * m[M31] * m[M02] * m[M13]+ m[M30] * m[M01] * m[M22] * m[M13]- m[M00] * m[M31] * m[M22] * m[M13]- m[M20] * m[M01] * m[M32] * m[M13]+ m[M00] * m[M21] * m[M32] * m[M13]+ m[M30] * m[M11] * m[M02] * m[M23]- m[M10] * m[M31] * m[M02] * m[M23]- m[M30] * m[M01] * m[M12] * m[M23]+ m[M00] * m[M31] * m[M12] * m[M23]+ m[M10] * m[M01] * m[M32] * m[M23]- m[M00] * m[M11] * m[M32] * m[M23]- m[M20] * m[M11] * m[M02] * m[M33]+ m[M10] * m[M21] * m[M02] * m[M33]+ m[M20] * m[M01] * m[M12] * m[M33]- m[M00] * m[M21] * m[M12] * m[M33]- m[M10] * m[M01] * m[M22] * m[M33]+ m[M00] * m[M11] * m[M22] * m[M33]; } /** * Inverts this {@link Matrix4}. * * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 inverse() { boolean success = Matrix.invertM(mTmp, 0, m, 0); System.arraycopy(mTmp, 0, m, 0, 16); return this; } /** * Transposes this {@link Matrix4}. * * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 transpose() { Matrix.transposeM(mTmp, 0, m, 0); System.arraycopy(mTmp, 0, m, 0, 16); return this; } /** * Adds the given {@link Matrix4} to this one. * * @param matrix {@link Matrix4} The matrix to add. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 add(Matrix4 matrix) { matrix.toArray(mTmp); m[0] += mTmp[0]; m[1] += mTmp[1]; m[2] += mTmp[2]; m[3] += mTmp[3]; m[4] += mTmp[4]; m[5] += mTmp[5]; m[6] += mTmp[6]; m[7] += mTmp[7]; m[8] += mTmp[8]; m[9] += mTmp[9]; m[10] += mTmp[10]; m[11] += mTmp[11]; m[12] += mTmp[12]; m[13] += mTmp[13]; m[14] += mTmp[14]; m[15] += mTmp[15]; return this; } /** * Subtracts the given {@link Matrix4} to this one. * * @param matrix {@link Matrix4} The matrix to subtract. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 subtract(final Matrix4 matrix) { matrix.toArray(mTmp); m[0] -= mTmp[0]; m[1] -= mTmp[1]; m[2] -= mTmp[2]; m[3] -= mTmp[3]; m[4] -= mTmp[4]; m[5] -= mTmp[5]; m[6] -= mTmp[6]; m[7] -= mTmp[7]; m[8] -= mTmp[8]; m[9] -= mTmp[9]; m[10] -= mTmp[10]; m[11] -= mTmp[11]; m[12] -= mTmp[12]; m[13] -= mTmp[13]; m[14] -= mTmp[14]; m[15] -= mTmp[15]; return this; } /** * Multiplies this {@link Matrix4} with the given one, storing the result in this {@link Matrix}. * <pre> * A.multiply(B) results in A = AB. * </pre> * * @param matrix {@link Matrix4} The RHS {@link Matrix4}. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 multiply(final Matrix4 matrix) { System.arraycopy(m, 0, mTmp, 0, 16); Matrix.multiplyMM(m, 0, mTmp, 0, matrix.getDoubleValues(), 0); return this; } /** * Left multiplies this {@link Matrix4} with the given one, storing the result in this {@link Matrix}. * <pre> * A.leftMultiply(B) results in A = BA. * </pre> * * @param matrix {@link Matrix4} The LHS {@link Matrix4}. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 leftMultiply(final Matrix4 matrix) { System.arraycopy(m, 0, mTmp, 0, 16); Matrix.multiplyMM(m, 0, matrix.getDoubleValues(), 0, mTmp, 0); return this; } /** * Multiplies each element of this {@link Matrix4} by the provided factor. * * @param value double The multiplication factor. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 multiply(final double value) { for (int i = 0; i < m.length; ++i) m[i] *= value; return this; } /** * Adds a translation to this {@link Matrix4} based on the provided {@link Vector3}. * * @param vec {@link Vector3} describing the translation components. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 translate(final Vector3 vec) { m[M03] += vec.x; m[M13] += vec.y; m[M23] += vec.z; return this; } /** * Adds a translation to this {@link Matrix4} based on the provided components. * * @param x double The x component of the translation. * @param y double The y component of the translation. * @param z double The z component of the translation. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 translate(double x, double y, double z) { m[M03] += x; m[M13] += y; m[M23] += z; return this; } /** * Subtracts a translation to this {@link Matrix4} based on the provided {@link Vector3}. * * @param vec {@link Vector3} describing the translation components. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 negTranslate(final Vector3 vec) { return translate(-vec.x, -vec.y, -vec.z); } /** * Scales this {@link Matrix4} based on the provided components. * * @param vec {@link Vector3} describing the scaling on each axis. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 scale(final Vector3 vec) { return scale(vec.x, vec.y, vec.z); } /** * Scales this {@link Matrix4} based on the provided components. * * @param x double The x component of the scaling. * @param y double The y component of the scaling. * @param z double The z component of the scaling. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 scale(double x, double y, double z) { Matrix.scaleM(m, 0, x, y, z); return this; } /** * Scales this {@link Matrix4} along all three axis by the provided value. * * @param s double The scaling factor. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 scale(double s) { return scale(s, s, s); } /** * Post multiplies this {@link Matrix4} with the rotation specified by the provided {@link Quaternion}. * * @param quat {@link Quaternion} describing the rotation to apply. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 rotate(final Quaternion quat) { if (mMatrix == null) { mMatrix = quat.toRotationMatrix(); } else { quat.toRotationMatrix(mMatrix); } return multiply(mMatrix); } /** * Post multiplies this {@link Matrix4} with the rotation specified by the provided * axis and angle. * * @param axis {@link Vector3} The axis of rotation. * @param angle double The angle of rotation in degrees. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 rotate(final Vector3 axis, double angle) { return angle == 0 ? this : rotate(mQuat.fromAngleAxis(axis, angle)); } /** * Post multiplies this {@link Matrix4} with the rotation specified by the provided * cardinal axis and angle. * * @param axis {@link Axis} The cardinal axis of rotation. * @param angle double The angle of rotation in degrees. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 rotate(final Axis axis, double angle) { return angle == 0 ? this : rotate(mQuat.fromAngleAxis(axis, angle)); } /** * Post multiplies this {@link Matrix4} with the rotation specified by the provided * axis and angle. * * @param x double The x component of the axis of rotation. * @param y double The y component of the axis of rotation. * @param z double The z component of the axis of rotation. * @param angle double The angle of rotation in degrees. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 rotate(double x, double y, double z, double angle) { return angle == 0 ? this :rotate(mQuat.fromAngleAxis(x, y, z, angle)); } /** * Post multiplies this {@link Matrix4} with the rotation between the two provided * {@link Vector3}s. * * @param v1 {@link Vector3} The base vector. * @param v2 {@link Vector3} The target vector. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 rotate(final Vector3 v1, final Vector3 v2) { return rotate(mQuat.fromRotationBetween(v1, v2)); } /** * Sets the translation of this {@link Matrix4} based on the provided {@link Vector3}. * * @param vec {@link Vector3} describing the translation components. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setTranslation(final Vector3 vec) { m[M03] = vec.x; m[M13] = vec.y; m[M23] = vec.z; return this; } /** * Sets the homogenous scale of this {@link Matrix4}. * * @param zoom double The zoom value. 1 = no zoom. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setCoordinateZoom(double zoom) { m[M33] = zoom; return this; } /** * Rotates the given {@link Vector3} by the rotation specified by this {@link Matrix4}. * * @param vec {@link Vector3} The vector to rotate. */ public void rotateVector(final Vector3 vec) { double x = vec.x * m[M00] + vec.y * m[M01] + vec.z * m[M02]; double y = vec.x * m[M10] + vec.y * m[M11] + vec.z * m[M12]; double z = vec.x * m[M20] + vec.y * m[M21] + vec.z * m[M22]; vec.setAll(x, y, z); } /** * Projects a give {@link Vector3} with this {@link Matrix4} storing * the result in the given {@link Vector3}. * * @param vec {@link Vector3} The vector to multiply by. * @return {@link Vector3} The resulting vector. */ public Vector3 projectVector(final Vector3 vec) { double inv = 1.0 / (m[M03] * vec.x + m[M13] * vec.y + m[M23] * vec.z + m[M33]); double x = (m[M00] * vec.x + m[M01] * vec.y + m[M02] * vec.z + m[M03]) * inv; double y = (m[M10] * vec.x + m[M11] * vec.y + m[M12] * vec.z + m[M13]) * inv; double z = (m[M20] * vec.x + m[M21] * vec.y + m[M22] * vec.z + m[M23]) * inv; return vec.setAll(x, y, z); } /** * Projects a give {@link Vector3} with this {@link Matrix4} storing * the result in a new {@link Vector3}. * * @param vec {@link Vector3} The vector to multiply by. * @return {@link Vector3} The resulting vector. */ public Vector3 projectAndCreateVector(final Vector3 vec) { Vector3 r = new Vector3(); double inv = 1.0 / (m[M03] * vec.x + m[M13] * vec.y + m[M23] * vec.z + m[M33]); r.x = (m[M00] * vec.x + m[M01] * vec.y + m[M02] * vec.z + m[M03]) * inv; r.y = (m[M10] * vec.x + m[M11] * vec.y + m[M12] * vec.z + m[M13]) * inv; r.z = (m[M20] * vec.x + m[M21] * vec.y + m[M22] * vec.z + m[M23]) * inv; return r; } /** * Sets translation of this {@link Matrix4} based on the provided components. * * @param x double The x component of the translation. * @param y double The y component of the translation. * @param z double The z component of the translation. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setTranslation(double x, double y, double z) { m[M03] = x; m[M13] = y; m[M23] = z; return this; } /** * Linearly interpolates between this {@link Matrix4} and the given {@link Matrix4} by * the given factor. * * @param matrix {@link Matrix4} The other matrix. * @param t {@code double} The interpolation ratio. The result is weighted to this value on the {@link Matrix4}. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 lerp(Matrix4 matrix, double t) { matrix.toArray(mTmp); for (int i = 0; i < 16; ++i) m[i] = m[i] * (1.0 - t) + t * mTmp[i]; return this; } //-------------------------------------------------- // Set to methods //-------------------------------------------------- /** * Sets this {@link Matrix4} to a Normal matrix. * * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setToNormalMatrix() { m[M03] = 0; m[M13] = 0; m[M23] = 0; return inverse().transpose(); } /** * Sets this {@link Matrix4} to a perspective projection matrix. * * @param near double The near plane. * @param far double The far plane. * @param fov double The field of view in degrees. * @param aspect double The aspect ratio. Defined as width/height. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setToPerspective(double near, double far, double fov, double aspect) { identity(); Matrix.perspectiveM(m, 0, fov, aspect, near, far); return this; } /** * Sets this {@link Matrix4} to an orthographic projection matrix with the origin at (x,y) * extended to the specified width and height. The near plane is at 0 and the far plane is at 1. * * @param x double The x coordinate of the origin. * @param y double The y coordinate of the origin. * @param width double The width. * @param height double The height. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setToOrthographic2D(double x, double y, double width, double height) { return setToOrthographic(x, x + width, y, y + height, 0, 1); } /** * Sets this {@link Matrix4} to an orthographic projection matrix with the origin at (x,y) * extended to the specified width and height. * * @param x double The x coordinate of the origin. * @param y double The y coordinate of the origin. * @param width double The width. * @param height double The height. * @param near double The near plane. * @param far double The far plane. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setToOrthographic2D(double x, double y, double width, double height, double near, double far) { return setToOrthographic(x, x + width, y, y + height, near, far); } /** * * @param left double The left plane. * @param right double The right plane. * @param bottom double The bottom plane. * @param top double The top plane. * @param near double The near plane. * @param far double The far plane. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setToOrthographic(double left, double right, double bottom, double top, double near, double far) { Matrix.orthoM(m, 0, left, right, bottom, top, near, far); return this; } /** * Sets this {@link Matrix4} to a translation matrix based on the provided {@link Vector3}. * * @param vec {@link Vector3} describing the translation components. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setToTranslation(final Vector3 vec) { identity(); m[M03] = vec.x; m[M13] = vec.y; m[M23] = vec.z; return this; } /** * Sets this {@link Matrix4} to a translation matrix based on the provided components. * * @param x double The x component of the translation. * @param y double The y component of the translation. * @param z double The z component of the translation. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setToTranslation(double x, double y, double z) { identity(); m[M03] = x; m[M13] = y; m[M23] = z; return this; } /** * Sets this {@link Matrix4} to a scale matrix based on the provided {@link Vector3}. * * @param vec {@link Vector3} describing the scaling components. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setToScale(final Vector3 vec) { identity(); m[M00] = vec.x; m[M11] = vec.y; m[M22] = vec.z; return this; } /** * Sets this {@link Matrix4} to a scale matrix based on the provided components. * * @param x double The x component of the translation. * @param y double The y component of the translation. * @param z double The z component of the translation. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setToScale(double x, double y, double z) { identity(); m[M00] = x; m[M11] = y; m[M22] = z; return this; } /** * Sets this {@link Matrix4} to a translation and scaling matrix. * * @param translation {@link Vector3} specifying the translation components. * @param scaling {@link Vector3} specifying the scaling components. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setToTranslationAndScaling(final Vector3 translation, final Vector3 scaling) { identity(); m[M03] = translation.x; m[M13] = translation.y; m[M23] = translation.z; m[M00] = scaling.x; m[M11] = scaling.y; m[M22] = scaling.z; return this; } /** * Sets this {@link Matrix4} to a translation and scaling matrix. * * @param tx double The x component of the translation. * @param ty double The y component of the translation. * @param tz double The z component of the translation. * @param sx double The x component of the scaling. * @param sy double The y component of the scaling. * @param sz double The z component of the scaling. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setToTranslationAndScaling(double tx, double ty, double tz, double sx, double sy, double sz) { identity(); m[M03] = tx; m[M13] = ty; m[M23] = tz; m[M00] = sx; m[M11] = sy; m[M22] = sz; return this; } /** * Sets this {@link Matrix4} to the specified rotation around the specified axis. * * @param axis {@link Vector3} The axis of rotation. * @param angle double The rotation angle in degrees. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setToRotation(final Vector3 axis, double angle) { return angle == 0 ? identity() : setAll(mQuat.fromAngleAxis(axis, angle)); } /** * Sets this {@link Matrix4} to the specified rotation around the specified cardinal axis. * * @param axis {@link Axis} The axis of rotation. * @param angle double The rotation angle in degrees. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setToRotation(final Axis axis, double angle) { return angle == 0 ? identity() : setAll(mQuat.fromAngleAxis(axis, angle)); } /** * Sets this {@link Matrix4} to the specified rotation around the specified axis. * * @param x double The x component of the axis of rotation. * @param y double The y component of the axis of rotation. * @param z double The z component of the axis of rotation. * @param angle double The rotation angle. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setToRotation(double x, double y, double z, double angle) { return angle == 0 ? identity() : setAll(mQuat.fromAngleAxis(x, y, z, angle)); } /** * Sets this {@link Matrix4} to the rotation between two {@link Vector3} objects. * * @param v1 {@link Vector3} The base vector. Should be normalized. * @param v2 {@link Vector3} The target vector. Should be normalized. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setToRotation(final Vector3 v1, final Vector3 v2) { return setAll(mQuat.fromRotationBetween(v1, v2)); } /** * Sets this {@link Matrix4} to the rotation between two vectors. The * incoming vectors should be normalized. * * @param x1 double The x component of the base vector. * @param y1 double The y component of the base vector. * @param z1 double The z component of the base vector. * @param x2 double The x component of the target vector. * @param y2 double The y component of the target vector. * @param z2 double The z component of the target vector. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setToRotation(double x1, double y1, double z1, double x2, double y2, double z2) { return setAll(mQuat.fromRotationBetween(x1, y1, z1, x2, y2, z2)); } /** * Sets this {@link Matrix4} to the rotation specified by the provided Euler angles. * * @param yaw double The yaw angle in degrees. * @param pitch double The pitch angle in degrees. * @param roll double The roll angle in degrees. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setToRotation(double yaw, double pitch, double roll) { return setAll(mQuat.fromEuler(yaw, pitch, roll)); } /** * Sets this {@link Matrix4} to a look at matrix with a direction and up {@link Vector3}. * You can multiply this with a translation {@link Matrix4} to get a camera Model-View matrix. * * @param direction {@link Vector3} The look direction. * @param up {@link Vector3} The up axis. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setToLookAt(final Vector3 direction, final Vector3 up) { mVec3.setAll(direction).normalize(); mVec1.setAll(direction).normalize(); mVec1.cross(up).normalize(); mVec2.setAll(mVec1).cross(mVec3).normalize(); identity(); m[M00] = mVec1.x; m[M01] = mVec1.y; m[M02] = mVec1.z; m[M10] = mVec2.x; m[M11] = mVec2.y; m[M12] = mVec2.z; m[M20] = mVec3.x; m[M21] = mVec3.y; m[M22] = mVec3.z; return this; } /** * Sets this {@link Matrix4} to a look at matrix with the given position, target and up {@link Vector3}s. * * @param position {@link Vector3} The eye position. * @param target {@link Vector3} The target position. * @param up {@link Vector3} The up axis. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setToLookAt(final Vector3 position, final Vector3 target, final Vector3 up) { Matrix.setLookAtM(m, 0, position.x, position.y, position.z, target.x, target.y, target.z, up.x, up.y, up.z); return this; } /** * Sets this {@link Matrix4} to a world matrix with the specified cardinal axis and the origin at the * provided position. * * @param position {@link Vector3} The position to use as the origin of the world coordinates. * @param forward {@link Vector3} The direction of the forward (z) vector. * @param up {@link Vector3} The direction of the up (y) vector. * @return A reference to this {@link Matrix4} to facilitate chaining. */ public Matrix4 setToWorld(final Vector3 position, final Vector3 forward, final Vector3 up) { mVec1.setAll(forward).normalize(); mVec2.setAll(mVec1).cross(up).normalize(); mVec3.setAll(mVec2).cross(mVec1).normalize(); return setAll(mVec2, mVec3, mVec1, position); } //-------------------------------------------------- // Component fetch methods //-------------------------------------------------- /** * Creates a new {@link Vector3} representing the translation component * of this {@link Matrix4}. * * @return {@link Vector3} representing the translation. */ public Vector3 getTranslation() { return getTranslation(new Vector3()); } public Vector3 getTranslation(Vector3 vec) { return vec.setAll(m[M03], m[M13], m[M23]); } /** * Creates a new {@link Vector3} representing the scaling component * of this {@link Matrix4}. * * @return {@link Vector3} representing the scaling. */ public Vector3 getScaling() { final double x = Math.sqrt(m[M00]*m[M00] + m[M01]*m[M01] + m[M02]*m[M02]); final double y = Math.sqrt(m[M10]*m[M10] + m[M11]*m[M11] + m[M12]*m[M12]); final double z = Math.sqrt(m[M20]*m[M20] + m[M21]*m[M21] + m[M22]*m[M22]); return new Vector3(x, y, z); } /** * Sets the components of the provided {@link Vector3} representing the scaling component * of this {@link Matrix4}. * * @param vec {@link Vector3} to store the result in. * @return {@link Vector3} representing the scaling. */ public Vector3 getScaling(final Vector3 vec) { final double x = Math.sqrt(m[M00]*m[M00] + m[M01]*m[M01] + m[M02]*m[M02]); final double y = Math.sqrt(m[M10]*m[M10] + m[M11]*m[M11] + m[M12]*m[M12]); final double z = Math.sqrt(m[M20]*m[M20] + m[M21]*m[M21] + m[M22]*m[M22]); return vec.setAll(x, y, z); } //-------------------------------------------------- // Creation methods //-------------------------------------------------- /** * Creates a new {@link Matrix4} representing a rotation. * * @param quat {@link Quaternion} representing the rotation. * @return {@link Matrix4} The new matrix. */ public static Matrix4 createRotationMatrix(final Quaternion quat) { return new Matrix4(quat); } /** * Creates a new {@link Matrix4} representing a rotation. * * @param axis {@link Vector3} The axis of rotation. * @param angle double The rotation angle in degrees. * @return {@link Matrix4} The new matrix. */ public static Matrix4 createRotationMatrix(final Vector3 axis, double angle) { return new Matrix4().setToRotation(axis, angle); } /** * Creates a new {@link Matrix4} representing a rotation. * * @param axis {@link Axis} The axis of rotation. * @param angle double The rotation angle in degrees. * @return {@link Matrix4} The new matrix. */ public static Matrix4 createRotationMatrix(final Axis axis, double angle) { return new Matrix4().setToRotation(axis, angle); } /** * Creates a new {@link Matrix4} representing a rotation. * * @param x double The x component of the axis of rotation. * @param y double The y component of the axis of rotation. * @param z double The z component of the axis of rotation. * @param angle double The rotation angle in degrees. * @return {@link Matrix4} The new matrix. */ public static Matrix4 createRotationMatrix(double x, double y, double z, double angle) { return new Matrix4().setToRotation(x, y, z, angle); } /** * Creates a new {@link Matrix4} representing a rotation by Euler angles. * * @param yaw double The yaw Euler angle. * @param pitch double The pitch Euler angle. * @param roll double The roll Euler angle. * @return {@link Matrix4} The new matrix. */ public static Matrix4 createRotationMatrix(double yaw, double pitch, double roll) { return new Matrix4().setToRotation(yaw, pitch, roll); } /** * Creates a new {@link Matrix4} representing a translation. * * @param vec {@link Vector3} describing the translation components. * @return A new {@link Matrix4} representing the translation only. */ public static Matrix4 createTranslationMatrix(final Vector3 vec) { return new Matrix4().translate(vec); } /** * Creates a new {@link Matrix4} representing a translation. * * @param x double The x component of the translation. * @param y double The y component of the translation. * @param z double The z component of the translation. * @return A new {@link Matrix4} representing the translation only. */ public static Matrix4 createTranslationMatrix(double x, double y, double z) { return new Matrix4().translate(x, y, z); } /** * Creates a new {@link Matrix4} representing a scaling. * * @param vec {@link Vector3} describing the scaling components. * @return A new {@link Matrix4} representing the scaling only. */ public static Matrix4 createScaleMatrix(final Vector3 vec) { return new Matrix4().setToScale(vec); } /** * Creates a new {@link Matrix4} representing a scaling. * * @param x double The x component of the scaling. * @param y double The y component of the scaling. * @param z double The z component of the scaling. * @return A new {@link Matrix4} representing the scaling only. */ public static Matrix4 createScaleMatrix(double x, double y, double z) { return new Matrix4().setToScale(x, y, z); } //-------------------------------------------------- // Utility methods //-------------------------------------------------- /** * Copies the backing array of this {@link Matrix4} into a float array and returns it. * * @return float array containing a copy of the backing array. The returned array is owned * by this {@link Matrix4} and is subject to change as the implementation sees fit. */ public float[] getFloatValues() { ArrayUtils.convertDoublesToFloats(m, mFloat); return mFloat; } /** * Returns the backing array of this {@link Matrix4}. * * @return double array containing the backing array. The returned array is owned * by this {@link Matrix4} and is subject to change as the implementation sees fit. */ public double[] getDoubleValues() { return m; } /** * Create and return a copy of this {@link Matrix4}. * * @return {@link Matrix4} The copy. */ @Override public Matrix4 clone() { return new Matrix4(this); } /** * Copies the backing array of this {@link Matrix4} into the provided double array. * * @param doubleArray double array to store the copy in. Must be at least 16 elements long. * Entries will be placed starting at the 0 index. */ public void toArray(double[] doubleArray) { System.arraycopy(m, 0, doubleArray, 0, 16); } public void toFloatArray(float[] floatArray) { floatArray[0] = (float)m[0]; floatArray[1] = (float)m[1]; floatArray[2] = (float)m[2]; floatArray[3] = (float)m[3]; floatArray[4] = (float)m[4]; floatArray[5] = (float)m[5]; floatArray[6] = (float)m[6]; floatArray[7] = (float)m[7]; floatArray[8] = (float)m[8]; floatArray[9] = (float)m[9]; floatArray[10] = (float)m[10]; floatArray[11] = (float)m[11]; floatArray[12] = (float)m[12]; floatArray[13] = (float)m[13]; floatArray[14] = (float)m[14]; floatArray[15] = (float)m[15]; } /** * Determines if this {@link Matrix4} is equivalent to the provided {@link Matrix4}. For this * to be true each element must match exactly between the two. * * @param m2 {@link Matrix4} the other matrix. * @return boolean True if they are an exact match. */ public boolean equals(final Matrix4 m2) { m2.toArray(mTmp); if ( m[0] != mTmp[0] || m[1] != mTmp[1] || m[2] != mTmp[2] || m[3] != mTmp[3] || m[4] != mTmp[4] || m[5] != mTmp[5] || m[6] != mTmp[6] || m[7] != mTmp[7] || m[8] != mTmp[8] || m[9] != mTmp[9] || m[10] != mTmp[10] || m[11] != mTmp[11] || m[12] != mTmp[12] || m[13] != mTmp[13] || m[14] != mTmp[14] || m[15] != mTmp[15] ) return false; return true; } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "[" + m[M00] + "|" + m[M01] + "|" + m[M02] + "|" + m[M03] + "]\n[" + m[M10] + "|" + m[M11] + "|" + m[M12] + "|" + m[M13] + "]\n[" + m[M20] + "|" + m[M21] + "|" + m[M22] + "|" + m[M23] + "]\n[" + m[M30] + "|" + m[M31] + "|" + m[M32] + "|" + m[M33] + "]\n"; } }
41,677
Java
.java
1,064
35.279135
127
0.652487
godstale/VR-Defense-Game
3
1
0
LGPL-3.0
9/4/2024, 11:34:01 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
41,677
13,787
package-info.java
checkstyle_checkstyle/src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/missingjavadocpackage/nojavadoc/single/package-info.java
/* MissingJavadocPackage */ //* not javadoc package com.puppycrawl.tools.checkstyle.checks // violation .javadoc.missingjavadocpackage.nojavadoc.single;
164
Java
.java
6
24.5
59
0.8
checkstyle/checkstyle
8,277
3,649
906
LGPL-2.1
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
false
false
false
true
true
false
true
true
164
4,018,308
Persistable.java
akamai_BlazeDS/modules/core/test/java/macromedia/qa/metrics/Persistable.java
/************************************************************************* * * ADOBE CONFIDENTIAL * __________________ * * Copyright 2008 Adobe Systems Incorporated * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Adobe Systems Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Adobe Systems Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Adobe Systems Incorporated. **************************************************************************/ package macromedia.qa.metrics; import macromedia.util.UnitTrace; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Map; /** * A base type whose subclasses are expected to be backed * by a database table. * <p/> * A Persistable instance represents a row in that * table. All Persistable items are expected to have * a unique identifier field called simply, "id" of * SQL Type "bigint", or a Long in Java. * * @author Peter Farland */ public abstract class Persistable { protected long id = -1; /** * Determines whether a Persistable instance exists in a table * by counting the number of records returned by a SELECT statement. * If the count is greater than 0, it is assumed that the instance * exists. * * @param database * @return * @throws SQLException */ public boolean exists(MetricsDatabase database) throws SQLException { if (database != null) { PreparedStatement statement = null; ResultSet rs = null; try { int count = 0; statement = get(database); rs = statement.executeQuery(); count = MetricsDatabase.countRecords(rs); if (count > 0) { rs.first(); Object val = rs.getObject("id"); if (val != null) { id = MetricsDatabase.getId(val); return id >= 0; } } } catch (SQLException ex) { if (UnitTrace.errors) System.err.println("Error checking if " + getIdentity() + " exists." + ex == null ? "" : ex.getMessage()); throw ex; } finally { closeResultSet(rs); closeStatement(statement); } } return false; } protected PreparedStatement get(MetricsDatabase database) throws SQLException { PreparedStatement statement = null; statement = database.select(null, getTables(), getClauses(), null); return statement; } /** * Silently tries to close a ResultSet. This must be called before executing * another query on most drivers when sharing a common connection. * * @param rs */ protected void closeResultSet(ResultSet rs) { if (rs != null) { try { rs.close(); } catch (Exception ex) { } } } /** * Silently tries to close a Statement. This must be called before executing * another query on most drivers when sharing a common connection. * * @param stmt */ protected void closeStatement(Statement stmt) { if (stmt != null) { try { stmt.close(); } catch (Exception ex) { } } } /** * A utility method to save a Persistable instance to a given database. This method * first checkes whether the instance exists, in which case an update is performed, * otherwise an insert is performed. In the case of an insert, a load operation is * also called to populate the instance's id field. * * @param database * @throws SQLException */ public void save(MetricsDatabase database) throws SQLException { PreparedStatement statement = null; try { if (exists(database)) { statement = database.update(getTableName(), getUpdates(), getClauses(), null); statement.executeUpdate(); } else { statement = database.insert(getTableName(), getInserts(), null, null); statement.executeUpdate(); load(database); } } catch (SQLException ex) { if (UnitTrace.errors) System.err.println("Error saving " + getIdentity() + ". " + ex == null ? "" : ex.getMessage()); throw ex; } finally { closeStatement(statement); } } /** * A short-circuit utility method that forces a record to be inserted without first checking * that it exists (an hence usually would be processed as an update). * <p/> * As with save(), load() is called after an insert to populate a Persistable instance's * id field. * * @param database * @throws SQLException */ public void insert(MetricsDatabase database) throws SQLException { PreparedStatement statement = null; try { statement = database.insert(getTableName(), getInserts(), null, null); statement.executeUpdate(); load(database); } catch (SQLException ex) { if (UnitTrace.errors) System.err.println("Error saving " + getIdentity() + ". " + ex == null ? "" : ex.getMessage()); throw ex; } finally { closeStatement(statement); } } public abstract void load(MetricsDatabase database); public abstract String getTableName(); public abstract String getIdentity(); protected abstract String[] getTables(); /* * Note that Persistable entries in the following Maps * will be referenced by id in SQL statements. */ protected abstract Map getInserts(); protected abstract Map getUpdates(); protected abstract Map getClauses(); }
6,944
Java
.java
209
23.511962
127
0.551863
akamai/BlazeDS
2
1
0
LGPL-3.0
9/4/2024, 11:59:57 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
6,944
1,310,111
ZModifyMountpointEvent.java
zextras_carbonio-mailbox/client/src/main/java/com/zimbra/client/event/ZModifyMountpointEvent.java
// SPDX-FileCopyrightText: 2022 Synacor, Inc. // SPDX-FileCopyrightText: 2022 Zextras <https://www.zextras.com> // // SPDX-License-Identifier: GPL-2.0-only package com.zimbra.client.event; import com.zimbra.common.service.ServiceException; import com.zimbra.common.soap.Element; import com.zimbra.common.soap.MailConstants; import com.zimbra.client.ZJSONObject; import org.json.JSONException; public class ZModifyMountpointEvent extends ZModifyFolderEvent { public ZModifyMountpointEvent(Element e) throws ServiceException { super(e); } /** * @param defaultValue value to return if unchanged * @return new name or defaultValue if unchanged */ public String getOwnerDisplayName(String defaultValue) { return mFolderEl.getAttribute(MailConstants.A_OWNER_NAME, defaultValue); } /** * @param defaultValue value to return if unchanged * @return new name or defaultValue if unchanged */ public String getRemoteId(String defaultValue) { return mFolderEl.getAttribute(MailConstants.A_REMOTE_ID, defaultValue); } /** * @param defaultValue value to return if unchanged * @return new name or defaultValue if unchanged */ public String getOwnerId(String defaultValue) { return mFolderEl.getAttribute(MailConstants.A_ZIMBRA_ID, defaultValue); } public ZJSONObject toZJSONObject() throws JSONException { ZJSONObject zjo = super.toZJSONObject(); if (getOwnerId(null) != null) zjo.put("ownerId", getOwnerId(null)); if (getOwnerDisplayName(null) != null) zjo.put("ownerDisplayName", getOwnerDisplayName(null)); if (getRemoteId(null) != null) zjo.put("remoteId", getRemoteId(null)); return zjo; } }
1,759
Java
.java
43
35.767442
102
0.731107
zextras/carbonio-mailbox
32
6
6
GPL-2.0
9/4/2024, 7:33:43 PM (Europe/Amsterdam)
true
true
true
true
true
true
true
true
1,759
1,316,129
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface/test76/in/A.java
package p; public class A { public int amount(){ return 1;} public void add(){} }
85
Java
.java
5
15.4
32
0.696203
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
85
689,463
ShowActionDashboardAction.java
licheng_zoj/judge_server/src/main/cn/edu/zju/acm/onlinejudge/action/ShowActionDashboardAction.java
/* * Copyright (C) 2001 - 2005 ZJU Online Judge, All Rights Reserved. */ package cn.edu.zju.acm.onlinejudge.action; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessages; import cn.edu.zju.acm.onlinejudge.bean.request.LogCriteria; import cn.edu.zju.acm.onlinejudge.form.LogSearchForm; import cn.edu.zju.acm.onlinejudge.util.AccessLog; import cn.edu.zju.acm.onlinejudge.util.ActionLog; import cn.edu.zju.acm.onlinejudge.util.PerformanceManager; import cn.edu.zju.acm.onlinejudge.util.Utility; /** * <p> * ShowDashboardAction * </p> * * * @author ZOJDEV * @version 2.0 */ public class ShowActionDashboardAction extends BaseAction { /** * <p> * Default constructor. * </p> */ public ShowActionDashboardAction() { } /** * ShowRolesAction. * * @param mapping action mapping * @param form action form * @param request http servlet request * @param response http servlet response * * @return action forward instance * * @throws Exception any errors happened */ public ActionForward execute(ActionMapping mapping, ActionForm form, ContextAdapter context) throws Exception { ActionForward forward = checkAdmin(mapping, context); if (forward != null) { return forward; } LogSearchForm searchForm = (LogSearchForm) form; if (searchForm.getTimeStart() == null) { searchForm.setTimeStart(Utility.toTimestamp(new Date(System.currentTimeMillis() - 24 * 3600 * 1000))); } ActionMessages errors = searchForm.check(); if (errors.size() > 0) { context.setAttribute("logs", new ArrayList<AccessLog>()); return handleFailure(mapping, context, errors); } LogCriteria criteria = searchForm.toLogCriteria(); if (criteria.getTimeStart() == null) { criteria.setTimeStart(new Date(System.currentTimeMillis() - 24 * 3600 * 1000)); } List<ActionLog> logs = PerformanceManager.getInstance().getActionDashboard(criteria, searchForm.getOrderBy()); context.setAttribute("parameters", searchForm.toParameterMap()); context.setAttribute("logs", logs); return handleSuccess(mapping, context, "success"); } }
2,655
Java
.java
70
30.1
119
0.681837
licheng/zoj
109
44
0
GPL-3.0
9/4/2024, 7:08:19 PM (Europe/Amsterdam)
false
false
true
true
false
true
false
true
2,655