/** Extracts document and cluster lists before serialization. */ @Persist private void beforeSerialization() { /* * See http://issues.carrot2.org/browse/CARROT-693; this monitor does not save us * in multi-threaded environment anyway. A better solution would be to prepare * this eagerly in the constructor, but we try to balance overhead and full * correctness here. */ synchronized (this) { query = (String) attributes.get(AttributeNames.QUERY); if (getDocuments() != null) { documents = Lists.newArrayList(getDocuments()); } else { documents = null; } if (getClusters() != null) { clusters = Lists.newArrayList(getClusters()); } else { clusters = null; } otherAttributesForSerialization = MapUtils.asHashMap(SimpleXmlWrappers.wrap(attributes)); otherAttributesForSerialization.remove(AttributeNames.QUERY); otherAttributesForSerialization.remove(AttributeNames.CLUSTERS); otherAttributesForSerialization.remove(AttributeNames.DOCUMENTS); if (otherAttributesForSerialization.isEmpty()) { otherAttributesForSerialization = null; } } }
public static void unpath(World world, int i, int j, int k) { List<ChunkCoordinates> blocks = Lists.newLinkedList(); List<ChunkCoordinates> notify = Lists.newLinkedList(); blocks.add(new ChunkCoordinates(i, j, k)); while (blocks.size() > 0) { ChunkCoordinates coords = blocks.remove(0); depolarize(world, coords.posX + 1, coords.posY, coords.posZ, blocks); depolarize(world, coords.posX, coords.posY + 1, coords.posZ, blocks); depolarize(world, coords.posX, coords.posY, coords.posZ + 1, blocks); depolarize(world, coords.posX - 1, coords.posY, coords.posZ, blocks); depolarize(world, coords.posX, coords.posY - 1, coords.posZ, blocks); depolarize(world, coords.posX, coords.posY, coords.posZ - 1, blocks); notify.add(coords); } for (ChunkCoordinates coords : notify) { if (world.blockExists(coords.posX, coords.posY, coords.posZ)) { world.markBlockForUpdate(coords.posX, coords.posY, coords.posZ); world.notifyBlocksOfNeighborChange( coords.posX, coords.posY, coords.posZ, world.getBlock(coords.posX, coords.posY, coords.posZ)); } } }
public void checkMap(SessionState ss) { if (map.isEmpty()) { for (Lists mylist : EnumSet.range(Lists.MYLIST, Lists.MAYBELIST)) { for (Types typeval : Types.values()) { HashMap<String, Integer> own = new HashMap<String, Integer>(); listName = mylist.getListName(typeval.getName()); map.put(listName, own); } } } else return; }
private static void pathto(World world, int i, int j, int k) { List<ChunkCoordinates> blocks = Lists.newLinkedList(); List<ChunkCoordinates> portals = Lists.newLinkedList(); List<ChunkCoordinates> repath = Lists.newLinkedList(); List<ChunkCoordinates> redraw = Lists.newLinkedList(); blocks.add(new ChunkCoordinates(i, j, k)); while ((portals.size() > 0) || (blocks.size() > 0)) { while (blocks.size() > 0) { ChunkCoordinates coords = blocks.remove(0); directPortal(world, coords.posX + 1, coords.posY, coords.posZ, 5, blocks, portals); directPortal(world, coords.posX, coords.posY + 1, coords.posZ, 1, blocks, portals); directPortal(world, coords.posX, coords.posY, coords.posZ + 1, 3, blocks, portals); directPortal(world, coords.posX - 1, coords.posY, coords.posZ, 6, blocks, portals); directPortal(world, coords.posX, coords.posY - 1, coords.posZ, 2, blocks, portals); directPortal(world, coords.posX, coords.posY, coords.posZ - 1, 4, blocks, portals); redraw.add(coords); } if (portals.size() > 0) { ChunkCoordinates coords = portals.remove(0); directPortal(world, coords.posX + 1, coords.posY, coords.posZ, 5, blocks, portals); directPortal(world, coords.posX, coords.posY + 1, coords.posZ, 1, blocks, portals); directPortal(world, coords.posX, coords.posY, coords.posZ + 1, 3, blocks, portals); directPortal(world, coords.posX - 1, coords.posY, coords.posZ, 6, blocks, portals); directPortal(world, coords.posX, coords.posY - 1, coords.posZ, 2, blocks, portals); directPortal(world, coords.posX, coords.posY, coords.posZ - 1, 4, blocks, portals); if (world.getBlock(coords.posX, coords.posY, coords.posZ) == NailedBlocks.portal) { repath.add(coords); } } } while (repath.size() > 0) { ChunkCoordinates coords = repath.remove(0); if (world.getBlock(coords.posX, coords.posY, coords.posZ) == NailedBlocks.portal) { if (!BlockPortal.isValidPortal(world, coords.posX, coords.posY, coords.posZ)) { repathNeighbors(world, coords.posX, coords.posY, coords.posZ); world.setBlock(coords.posX, coords.posY, coords.posZ, Blocks.air, 0, 0); addSurrounding(repath, coords.posX, coords.posY, coords.posZ); } else { redraw.add(coords); } } } for (ChunkCoordinates coords : redraw) { if (world.blockExists(coords.posX, coords.posY, coords.posZ)) { world.markBlockForUpdate(coords.posX, coords.posY, coords.posZ); world.notifyBlocksOfNeighborChange( coords.posX, coords.posY, coords.posZ, world.getBlock(coords.posX, coords.posY, coords.posZ)); } } }
/** * Assigns sequential identifiers to the provided <code>clusters</code> (and their sub-clusters). * If a cluster already has an identifier, the identifier will not be changed. * * @param clusters Clusters to assign identifiers to. * @throws IllegalArgumentException if the provided clusters contain non-unique identifiers */ public static void assignClusterIds(Collection<Cluster> clusters) { final ArrayList<Cluster> flattened = Lists.newArrayListWithExpectedSize(clusters.size()); flatten(flattened, clusters); synchronized (clusters) { final HashSet<Integer> ids = Sets.newHashSet(); // First, find the start value for the id and check uniqueness of the ids // already provided. int maxId = Integer.MIN_VALUE; for (final Cluster cluster : flattened) { if (cluster.id != null) { if (!ids.add(cluster.id)) { throw new IllegalArgumentException("Non-unique cluster id found: " + cluster.id); } maxId = Math.max(maxId, cluster.id); } } // We'd rather start with 0 maxId = Math.max(maxId, -1); // Assign missing ids for (final Cluster c : flattened) { if (c.id == null) { c.id = ++maxId; } } } }
public void checkRedeclarationsInInnerClassNames(@NotNull TopDownAnalysisContext c) { for (ClassDescriptorWithResolutionScopes classDescriptor : c.getDeclaredClasses().values()) { if (classDescriptor.getKind() == ClassKind.CLASS_OBJECT) { // Class objects should be considered during analysing redeclarations in classes continue; } Collection<DeclarationDescriptor> allDescriptors = classDescriptor.getScopeForMemberLookup().getOwnDeclaredDescriptors(); ClassDescriptorWithResolutionScopes classObj = classDescriptor.getClassObjectDescriptor(); if (classObj != null) { Collection<DeclarationDescriptor> classObjDescriptors = classObj.getScopeForMemberLookup().getOwnDeclaredDescriptors(); if (!classObjDescriptors.isEmpty()) { allDescriptors = Lists.newArrayList(allDescriptors); allDescriptors.addAll(classObjDescriptors); } } Multimap<Name, DeclarationDescriptor> descriptorMap = HashMultimap.create(); for (DeclarationDescriptor desc : allDescriptors) { if (desc instanceof ClassDescriptor || desc instanceof PropertyDescriptor) { descriptorMap.put(desc.getName(), desc); } } reportRedeclarations(descriptorMap); } }
@Override public void readFields(DataInput input) throws IOException { byte[] tableNameBytes = Bytes.readByteArray(input); PName tableName = new PNameImpl(tableNameBytes); PTableType tableType = PTableType.values()[WritableUtils.readVInt(input)]; long sequenceNumber = WritableUtils.readVLong(input); long timeStamp = input.readLong(); byte[] pkNameBytes = Bytes.readByteArray(input); String pkName = pkNameBytes.length == 0 ? null : Bytes.toString(pkNameBytes); int nColumns = WritableUtils.readVInt(input); List<PColumn> columns = Lists.newArrayListWithExpectedSize(nColumns); for (int i = 0; i < nColumns; i++) { PColumn column = new PColumnImpl(); column.readFields(input); columns.add(column); } Map<String, byte[][]> guidePosts = new HashMap<String, byte[][]>(); int size = WritableUtils.readVInt(input); for (int i = 0; i < size; i++) { String key = WritableUtils.readString(input); int valueSize = WritableUtils.readVInt(input); byte[][] value = new byte[valueSize][]; for (int j = 0; j < valueSize; j++) { value[j] = Bytes.readByteArray(input); } guidePosts.put(key, value); } PTableStats stats = new PTableStatsImpl(guidePosts); init(tableName, tableType, timeStamp, sequenceNumber, pkName, columns, stats); }
/** * 将原始数据切割后装入ThreadInfo,并以Key=WaitID,Value= ThreadInfo实体放入到Multimap<String, ThreadInfo>集合中 * ps:Multimap 类似于Map<key,collection>, key:value-> 1:n * * @param rawDatas * @return */ public Multimap<String, ThreadInfo> getThreadInfo(List<String[]> rawDatas) { Multimap<String, ThreadInfo> w_IdMap = HashMultimap.create(); List<ThreadInfo> threadsList = Lists.newArrayList(); for (String[] rawData : rawDatas) { ThreadInfo threadInfo = new ThreadInfo(); Pattern t_id = Pattern.compile("tid=(0x[\\d\\w]+)"); Pattern t_name = Pattern.compile("\"([\\d\\D]*)\""); Pattern w_Id = Pattern.compile("\\[(0x[\\d\\w]+)\\]"); Matcher tIdMatcher = t_id.matcher(rawData[0]); Matcher nameMatcher = t_name.matcher(rawData[0]); Matcher w_IdMatcher = w_Id.matcher(rawData[0]); if (tIdMatcher.find()) { threadInfo.setThreadId(tIdMatcher.group(1)); } if (nameMatcher.find()) { threadInfo.setThreadName(nameMatcher.group(1)); } if (w_IdMatcher.find()) { threadInfo.setWaitThreadId(w_IdMatcher.group(1)); } threadInfo.setThreadCondition(rawData[1]); w_IdMap.put(threadInfo.getWaitThreadId(), threadInfo); } return w_IdMap; }
private static List<FunctionDescriptor> getSuperFunctionsForMethod( @NotNull PsiMethodWrapper method, @NotNull BindingTrace trace, @NotNull ClassDescriptor containingClass) { List<FunctionDescriptor> superFunctions = Lists.newArrayList(); Map<ClassDescriptor, JetType> superclassToSupertype = getSuperclassToSupertypeMap(containingClass); Multimap<FqName, Pair<FunctionDescriptor, PsiMethod>> superclassToFunctions = getSuperclassToFunctionsMultimap(method, trace.getBindingContext(), containingClass); for (HierarchicalMethodSignature superSignature : method.getPsiMethod().getHierarchicalMethodSignature().getSuperSignatures()) { PsiMethod superMethod = superSignature.getMethod(); PsiClass psiClass = superMethod.getContainingClass(); assert psiClass != null; String classFqNameString = psiClass.getQualifiedName(); assert classFqNameString != null; FqName classFqName = new FqName(classFqNameString); if (!JavaToKotlinClassMap.getInstance().mapPlatformClass(classFqName).isEmpty()) { for (FunctionDescriptor superFun : JavaToKotlinMethodMap.INSTANCE.getFunctions(superMethod, containingClass)) { superFunctions.add(substituteSuperFunction(superclassToSupertype, superFun)); } continue; } DeclarationDescriptor superFun = superMethod instanceof JetClsMethod ? trace.get( BindingContext.DECLARATION_TO_DESCRIPTOR, ((JetClsMethod) superMethod).getOrigin()) : findSuperFunction(superclassToFunctions.get(classFqName), superMethod); if (superFun == null) { reportCantFindSuperFunction(method); continue; } assert superFun instanceof FunctionDescriptor : superFun.getClass().getName(); superFunctions.add( substituteSuperFunction(superclassToSupertype, (FunctionDescriptor) superFun)); } // sorting for diagnostic stability Collections.sort( superFunctions, new Comparator<FunctionDescriptor>() { @Override public int compare(FunctionDescriptor fun1, FunctionDescriptor fun2) { FqNameUnsafe fqName1 = getFQName(fun1.getContainingDeclaration()); FqNameUnsafe fqName2 = getFQName(fun2.getContainingDeclaration()); return fqName1.getFqName().compareTo(fqName2.getFqName()); } }); return superFunctions; }
// Returns list with type arguments info from supertypes // Example: // - Foo<A, B> is a subtype of Bar<A, List<B>>, Baz<Boolean, A> // - input: klass = Foo, typesFromSuper = [Bar<String, List<Int>>, Baz<Boolean, CharSequence>] // - output[0] = [String, CharSequence], output[1] = [] private static List<List<TypeProjectionAndVariance>> calculateTypeArgumentsFromSuper( @NotNull ClassDescriptor klass, @NotNull Collection<TypeAndVariance> typesFromSuper) { // For each superclass of klass and its parameters, hold their mapping to klass' parameters // #0 of Bar -> A // #1 of Bar -> List<B> // #0 of Baz -> Boolean // #1 of Baz -> A // #0 of Foo -> A (mapped to itself) // #1 of Foo -> B (mapped to itself) Multimap<TypeConstructor, TypeProjection> substitution = SubstitutionUtils.buildDeepSubstitutionMultimap( TypeUtils.makeUnsubstitutedType(klass, JetScope.EMPTY)); // for each parameter of klass, hold arguments in corresponding supertypes List<List<TypeProjectionAndVariance>> parameterToArgumentsFromSuper = Lists.newArrayList(); for (TypeParameterDescriptor ignored : klass.getTypeConstructor().getParameters()) { parameterToArgumentsFromSuper.add(new ArrayList<TypeProjectionAndVariance>()); } // Enumerate all types from super and all its parameters for (TypeAndVariance typeFromSuper : typesFromSuper) { for (TypeParameterDescriptor parameter : typeFromSuper.type.getConstructor().getParameters()) { TypeProjection argument = typeFromSuper.type.getArguments().get(parameter.getIndex()); // for given example, this block is executed four times: // 1. typeFromSuper = Bar<String, List<Int>>, parameter = "#0 of Bar", argument = // String // 2. typeFromSuper = Bar<String, List<Int>>, parameter = "#1 of Bar", argument = // List<Int> // 3. typeFromSuper = Baz<Boolean, CharSequence>, parameter = "#0 of Baz", argument = // Boolean // 4. typeFromSuper = Baz<Boolean, CharSequence>, parameter = "#1 of Baz", argument = // CharSequence // if it is mapped to klass' parameter, then store it into map for (TypeProjection projection : substitution.get(parameter.getTypeConstructor())) { // 1. projection = A // 2. projection = List<B> // 3. projection = Boolean // 4. projection = A ClassifierDescriptor classifier = projection.getType().getConstructor().getDeclarationDescriptor(); // this condition is true for 1 and 4, false for 2 and 3 if (classifier instanceof TypeParameterDescriptor && classifier.getContainingDeclaration() == klass) { int parameterIndex = ((TypeParameterDescriptor) classifier).getIndex(); Variance effectiveVariance = parameter.getVariance().superpose(typeFromSuper.varianceOfPosition); parameterToArgumentsFromSuper .get(parameterIndex) .add(new TypeProjectionAndVariance(argument, effectiveVariance)); } } } } return parameterToArgumentsFromSuper; }
/** * @param sstables * @return */ public static List<Pair<SSTableReader, Long>> createSSTableAndMinTimestampPairs( Iterable<SSTableReader> sstables) { List<Pair<SSTableReader, Long>> sstableMinTimestampPairs = Lists.newArrayListWithCapacity(Iterables.size(sstables)); for (SSTableReader sstable : sstables) sstableMinTimestampPairs.add(Pair.create(sstable, sstable.getMinTimestamp())); return sstableMinTimestampPairs; }
/** * 清除掉没有处于waiting on condition状态的线程 * * @param rawDatas * @return */ public List<String[]> remove(List<String[]> rawDatas) { List<String[]> pickedData = Lists.newArrayList(); for (String[] temp : rawDatas) { if (temp[0].lastIndexOf("waiting on condition") > -1) pickedData.add(temp); } return pickedData; }
public static List<NameValuePair> convertAttributesToNameValuePair( Map<String, String> aAttributes) { List<NameValuePair> myNameValuePairs = Lists.newArrayList(); for (Map.Entry<String, String> myEntry : aAttributes.entrySet()) { myNameValuePairs.add(new BasicNameValuePair(myEntry.getKey(), myEntry.getValue())); } return myNameValuePairs; }
private JavaDescriptorResolver.ValueParameterDescriptors modifyValueParametersAccordingToSuperMethods( @NotNull JavaDescriptorResolver.ValueParameterDescriptors parameters // descriptors built by parameters resolver ) { // we are not processing receiver type specifically: // if this function comes from Kotlin, then we don't need to do it, if it doesn't, then it can't // have receiver List<ValueParameterDescriptor> resultParameters = Lists.newArrayList(); for (ValueParameterDescriptor originalParam : parameters.getDescriptors()) { final int index = originalParam.getIndex(); List<TypeAndVariance> typesFromSuperMethods = ContainerUtil.map( superFunctions, new Function<FunctionDescriptor, TypeAndVariance>() { @Override public TypeAndVariance fun(FunctionDescriptor superFunction) { return new TypeAndVariance( superFunction.getValueParameters().get(index).getType(), INVARIANT); } }); VarargCheckResult varargCheckResult = checkVarargInSuperFunctions(originalParam); JetType altType = modifyTypeAccordingToSuperMethods( varargCheckResult.parameterType, typesFromSuperMethods, MEMBER_SIGNATURE_CONTRAVARIANT); resultParameters.add( new ValueParameterDescriptorImpl( originalParam.getContainingDeclaration(), index, originalParam.getAnnotations(), originalParam.getName(), altType, originalParam.declaresDefaultValue(), varargCheckResult.isVararg ? KotlinBuiltIns.getInstance().getArrayElementType(altType) : null)); } JetType originalReceiverType = parameters.getReceiverType(); if (originalReceiverType != null) { JetType substituted = SignaturesUtil.createSubstitutorForFunctionTypeParameters(autoTypeParameterToModified) .substitute(originalReceiverType, INVARIANT); assert substituted != null; return new JavaDescriptorResolver.ValueParameterDescriptors(substituted, resultParameters); } else { return new JavaDescriptorResolver.ValueParameterDescriptors(null, resultParameters); } }
@NotNull @Override public List<Instruction> getReversedInstructions() { LinkedHashSet<Instruction> traversedInstructions = Sets.newLinkedHashSet(); PseudocodeTraverserKt.traverseFollowingInstructions( sinkInstruction, traversedInstructions, BACKWARD, null); if (traversedInstructions.size() < instructions.size()) { List<Instruction> simplyReversedInstructions = Lists.newArrayList(instructions); Collections.reverse(simplyReversedInstructions); for (Instruction instruction : simplyReversedInstructions) { if (!traversedInstructions.contains(instruction)) { PseudocodeTraverserKt.traverseFollowingInstructions( instruction, traversedInstructions, BACKWARD, null); } } } return Lists.newArrayList(traversedInstructions); }
@NotNull private static List<Label> copyLabels( Collection<Label> labels, Map<Label, Label> originalToCopy) { List<Label> newLabels = Lists.newArrayList(); for (Label label : labels) { Label newLabel = originalToCopy.get(label); newLabels.add(newLabel != null ? newLabel : label); } return newLabels; }
/** * Group files with similar min timestamp into buckets. Files with recent min timestamps are * grouped together into buckets designated to short timespans while files with older timestamps * are grouped into buckets representing longer timespans. * * @param files pairs consisting of a file and its min timestamp * @param timeUnit * @param base * @param now * @return a list of buckets of files. The list is ordered such that the files with newest * timestamps come first. Each bucket is also a list of files ordered from newest to oldest. */ @VisibleForTesting static <T> List<List<T>> getBuckets( Collection<Pair<T, Long>> files, long timeUnit, int base, long now) { // Sort files by age. Newest first. final List<Pair<T, Long>> sortedFiles = Lists.newArrayList(files); Collections.sort( sortedFiles, Collections.reverseOrder( new Comparator<Pair<T, Long>>() { public int compare(Pair<T, Long> p1, Pair<T, Long> p2) { return p1.right.compareTo(p2.right); } })); List<List<T>> buckets = Lists.newArrayList(); Target target = getInitialTarget(now, timeUnit); PeekingIterator<Pair<T, Long>> it = Iterators.peekingIterator(sortedFiles.iterator()); outerLoop: while (it.hasNext()) { while (!target.onTarget(it.peek().right)) { // If the file is too new for the target, skip it. if (target.compareToTimestamp(it.peek().right) < 0) { it.next(); if (!it.hasNext()) break outerLoop; } else // If the file is too old for the target, switch targets. target = target.nextTarget(base); } List<T> bucket = Lists.newArrayList(); while (target.onTarget(it.peek().right)) { bucket.add(it.next().left); if (!it.hasNext()) break; } buckets.add(bucket); } return buckets; }
@Override public Iterable<DataKey> getSubKeys() { final Tag tag = this.findLastTag(this.path, false); if (!(tag instanceof CompoundTag)) { return (Iterable<DataKey>) Collections.emptyList(); } final List<DataKey> subKeys = (List<DataKey>) Lists.newArrayList(); for (final String name : ((CompoundTag) tag).getValue().keySet()) { subKeys.add(new NBTKey(this.createRelativeKey(name))); } return subKeys; }
@NotNull private static List<TypeAndVariance> getTypes( @NotNull List<TypeProjectionAndVariance> projections) { List<TypeAndVariance> types = Lists.newArrayList(); for (TypeProjectionAndVariance projection : projections) { types.add( new TypeAndVariance( projection.typeProjection.getType(), merge(projection.varianceOfPosition, projection.typeProjection.getProjectionKind()))); } return types; }
private List<RelDataType> toSql(List<RelDataType> types) { return Lists.transform( types, new com.google.common.base.Function<RelDataType, RelDataType>() { public RelDataType apply(RelDataType input) { if (input instanceof RelDataTypeFactoryImpl.JavaType && ((RelDataTypeFactoryImpl.JavaType) input).getJavaClass() == Object.class) { return typeFactory.createSqlType(SqlTypeName.ANY); } return typeFactory.toSql(input); } }); }
private List<TypeParameterDescriptor> modifyTypeParametersAccordingToSuperMethods( List<TypeParameterDescriptor> autoTypeParameters) { List<TypeParameterDescriptor> result = Lists.newArrayList(); for (TypeParameterDescriptor autoParameter : autoTypeParameters) { int index = autoParameter.getIndex(); TypeParameterDescriptorImpl modifiedTypeParameter = autoTypeParameterToModified.get(autoParameter); List<Iterator<JetType>> upperBoundFromSuperFunctionsIterators = Lists.newArrayList(); for (FunctionDescriptor superFunction : superFunctions) { upperBoundFromSuperFunctionsIterators.add( superFunction.getTypeParameters().get(index).getUpperBounds().iterator()); } for (JetType autoUpperBound : autoParameter.getUpperBounds()) { List<TypeAndVariance> upperBoundsFromSuperFunctions = Lists.newArrayList(); for (Iterator<JetType> iterator : upperBoundFromSuperFunctionsIterators) { assert iterator.hasNext(); upperBoundsFromSuperFunctions.add(new TypeAndVariance(iterator.next(), INVARIANT)); } JetType modifiedUpperBound = modifyTypeAccordingToSuperMethods( autoUpperBound, upperBoundsFromSuperFunctions, UPPER_BOUND); modifiedTypeParameter.addUpperBound(modifiedUpperBound); } for (Iterator<JetType> iterator : upperBoundFromSuperFunctionsIterators) { assert !iterator.hasNext(); } modifiedTypeParameter.setInitialized(); result.add(modifiedTypeParameter); } return result; }
/** Returns the path of an object in this schema. */ public List<String> path(String name) { final List<String> list = new ArrayList<String>(); if (name != null) { list.add(name); } for (OptiqSchema s = this; s != null; s = s.parent) { if (s.parent != null || !s.name.equals("")) { // Omit the root schema's name from the path if it's the empty string, // which it usually is. list.add(s.name); } } return ImmutableList.copyOf(Lists.reverse(list)); }
/** * Converts the value to boolean, and if it is null, it uses the default value passed. * * @param obj value to convert to boolean * @param defaultValue default value * @return obj converted to boolean */ public static boolean toBoolean(Object obj, boolean defaultValue) { if (obj == null) { return defaultValue; } if (obj instanceof Boolean) { return ((Boolean) obj).booleanValue(); } else if (obj instanceof Number || obj.getClass().isPrimitive()) { int value = toInt(obj); return value != 0 ? true : false; } else if (obj instanceof String || obj instanceof CharSequence) { String str = Conversions.toString(obj); if (str.length() == 0) { return false; } if (str.equals("false")) { return false; } else { return true; } } else if (Boon.isArray(obj)) { return Boon.len(obj) > 0; } else if (obj instanceof Collection) { if (len(obj) > 0) { List list = Lists.list((Collection) obj); while (list.remove(null)) {} return Lists.len(list) > 0; } else { return false; } } else { return toBoolean(Conversions.toString(obj)); } }
private static void repathNeighbors(World world, int i, int j, int k) { TileEntity tileentity = getTileEntity(world, i, j, k); List<ChunkCoordinates> blocks = Lists.newLinkedList(); blocks.add(new ChunkCoordinates(i, j, k)); world.setBlockMetadataWithNotify(i, j, k, 8, 2); while (blocks.size() > 0) { ChunkCoordinates coords = blocks.remove(0); redirectPortal(world, tileentity, coords.posX + 1, coords.posY, coords.posZ, 5, blocks); redirectPortal(world, tileentity, coords.posX, coords.posY + 1, coords.posZ, 1, blocks); redirectPortal(world, tileentity, coords.posX, coords.posY, coords.posZ + 1, 3, blocks); redirectPortal(world, tileentity, coords.posX - 1, coords.posY, coords.posZ, 6, blocks); redirectPortal(world, tileentity, coords.posX, coords.posY - 1, coords.posZ, 2, blocks); redirectPortal(world, tileentity, coords.posX, coords.posY, coords.posZ - 1, 4, blocks); } }
private static void onpulse(World world, int i, int j, int k) { List<ChunkCoordinates> set = Lists.newLinkedList(); Stack<ChunkCoordinates> validate = new Stack<ChunkCoordinates>(); addSurrounding(set, i, j, k); while (set.size() > 0) { ChunkCoordinates coords = set.remove(0); expandPortal(world, coords.posX, coords.posY, coords.posZ, set, validate); } while (validate.size() > 0) { ChunkCoordinates coords = validate.pop(); i = coords.posX; j = coords.posY; k = coords.posZ; if (!BlockPortal.checkPortalTension(world, i, j, k)) { world.setBlock(i, j, k, Blocks.air, 0, 0); } } }
@GET @Path("/files") public List<ToDo> files() { List<ToDo> response = Lists.newArrayList(); File[] files = new File("/lib").listFiles(); if (files != null) { for (File file : files) { if (file.isFile()) response.add( new ToDo( ++id, file.getName(), file.isFile() ? file.length() : -1, System.currentTimeMillis())); } } return response; }
@Persist @SuppressWarnings("unused") private void beforeSerialization() { documentIds = Lists.transform( documents, new Function<Document, DocumentRefid>() { public DocumentRefid apply(Document document) { return new DocumentRefid(document.getId()); } }); // Remove score from attributes for serialization otherAttributesForSerialization = MapUtils.asHashMap(SimpleXmlWrappers.wrap(attributes)); otherAttributesForSerialization.remove(SCORE); if (otherAttributesForSerialization.isEmpty()) { otherAttributesForSerialization = null; } }
private List<SSTableReader> getCompactionCandidates( Iterable<SSTableReader> candidateSSTables, long now, int base) { Iterable<SSTableReader> candidates = filterOldSSTables(Lists.newArrayList(candidateSSTables), options.maxSSTableAge, now); List<List<SSTableReader>> buckets = getBuckets(createSSTableAndMinTimestampPairs(candidates), options.baseTime, base, now); logger.debug("Compaction buckets are {}", buckets); updateEstimatedCompactionsByTasks(buckets); List<SSTableReader> mostInteresting = newestBucket( buckets, cfs.getMinimumCompactionThreshold(), cfs.getMaximumCompactionThreshold(), now, options.baseTime); if (!mostInteresting.isEmpty()) return mostInteresting; return null; }
/** * Returns the targets (platforms & addons) that are available in the SDK. The target list is * created on demand the first time then cached. It will not refreshed unless {@link * #clearLocalPkg} is called to clear platforms and/or add-ons. * * <p>The array can be empty but not null. */ @NonNull public IAndroidTarget[] getTargets() { synchronized (mLocalPackages) { if (mCachedTargets == null) { List<IAndroidTarget> result = Lists.newArrayList(); LocalPkgInfo[] pkgsInfos = getPkgsInfos(EnumSet.of(PkgType.PKG_PLATFORM, PkgType.PKG_ADDON)); for (LocalPkgInfo info : pkgsInfos) { assert info instanceof LocalPlatformPkgInfo; IAndroidTarget target = ((LocalPlatformPkgInfo) info).getAndroidTarget(); if (target != null) { result.add(target); } } mCachedTargets = result; } return mCachedTargets.toArray(new IAndroidTarget[mCachedTargets.size()]); } }
private List<SSTableReader> getNextNonExpiredSSTables( Iterable<SSTableReader> nonExpiringSSTables, final int gcBefore) { int base = cfs.getMinimumCompactionThreshold(); long now = getNow(); List<SSTableReader> mostInteresting = getCompactionCandidates(nonExpiringSSTables, now, base); if (mostInteresting != null) { return mostInteresting; } // if there is no sstable to compact in standard way, try compacting single sstable whose // droppable tombstone // ratio is greater than threshold. List<SSTableReader> sstablesWithTombstones = Lists.newArrayList(); for (SSTableReader sstable : nonExpiringSSTables) { if (worthDroppingTombstones(sstable, gcBefore)) sstablesWithTombstones.add(sstable); } if (sstablesWithTombstones.isEmpty()) return Collections.emptyList(); return Collections.singletonList( Collections.min(sstablesWithTombstones, new SSTableReader.SizeComparator())); }