auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void run() { directoryProviderLock.lock(); try { long start = System.nanoTime(); int oldIndex = current; int index = oldIndex == 1 ? 2 : 1; Path destinationFile = destination.resolve( Integer.valueOf( index ).toString() ); try { log.tracef( "Copying %s into %s", source, destinationFile ); FileHelper.synchronize( source, destinationFile, true, copyChunkSize ); current = index; } catch (IOException e) { log.unableToSynchronizeSource( indexName, e ); return; } try { Files.delete( destination.resolve( CURRENT_DIR_NAME[oldIndex] ) ); Files.createFile( destination.resolve( CURRENT_DIR_NAME[index] ) ); } catch (IOException e) { log.unableToCreateCurrentMarker( indexName, e ); } log.tracef( "Copy for %s took %d ms", indexName, TimeUnit.NANOSECONDS.toMillis( System.nanoTime() - start ) ); } finally { directoryProviderLock.unlock(); inProgress.set( false ); } }

Target:
public void run() { directoryProviderLock.lock(); final boolean traceEnabled = log.isTraceEnabled(); try { long startTime = 0; if ( traceEnabled ) { startTime = System.nanoTime(); } int oldIndex = current; int index = oldIndex == 1 ? 2 : 1; Path destinationFile = destination.resolve( Integer.valueOf( index ).toString() ); try { log.tracef( "Copying %s into %s", source, destinationFile ); FileHelper.synchronize( source, destinationFile, true ); current = index; } catch (IOException e) { log.unableToSynchronizeSource( indexDir.toString(), e ); return; } try { Files.delete( destination.resolve( CURRENT_DIR_NAME[oldIndex] ) ); } catch (IOException e) { log.unableToRemovePreviousMarker( indexDir.toString(), e ); } try { Files.createFile( destination.resolve( CURRENT_DIR_NAME[index] ) ); } catch (IOException e) { log.unableToCreateCurrentMarker( indexDir.toString(), e ); } if ( traceEnabled ) { log.tracef( "Copy for %s took %d ms", indexDir.toString(), TimeUnit.NANOSECONDS.toMillis( System.nanoTime() - startTime ) ); } } finally { directoryProviderLock.unlock(); inProgress.set( false ); } }
Source:
public boolean determineDoubleRelationshipRecordUnits( Estimates inputEstimates ) { doubleRelationshipRecordUnits = recordFormats.relationship().getMaxId() > 2L << 36 && inputEstimates.numberOfRelationships() > DOUBLE_RELATIONSHIP_RECORD_UNIT_THRESHOLD; return doubleRelationshipRecordUnits; }

Target:
public boolean determineDoubleRelationshipRecordUnits( Estimates inputEstimates ) { doubleRelationshipRecordUnits = recordFormats.hasCapability( Capability.SECONDARY_RECORD_UNITS ) && inputEstimates.numberOfRelationships() > DOUBLE_RELATIONSHIP_RECORD_UNIT_THRESHOLD; return doubleRelationshipRecordUnits; }
Source:
public boolean shouldAlertUpgrade(ArrayList<RpmVersion> isos, String hostOs) { boolean alert = false; DateTimeFormat format = DateTimeFormat.getFormat("yyyyMMdd"); String nodeInfo[] = hostOs.split("-"); String formattedISOVersion = null; for (RpmVersion iso: isos) { try { formattedISOVersion = String.valueOf(iso); formattedISOVersion = formattedISOVersion.substring(formattedISOVersion.length() - 8); Date dateISO = format.parse(formattedISOVersion); Date dateNodeISO = format.parse(nodeInfo[2].split("\\.")[0].trim()); if (dateISO.compareTo(dateNodeISO)>0) { alert = true; break; } } catch (IllegalArgumentException er) { logger.info("IllegalArgumentException error: " + er); } } return alert; }

Target:
public boolean shouldAlertUpgrade(ArrayList<RpmVersion> isos, String hostOs) { boolean alert = false; for (RpmVersion iso: isos) { try { String nodeInfo[] = hostOs.split("-"); String formattedISOversion = iso.getValue(); formattedISOversion = formattedISOversion.substring(formattedISOversion.length() - 8); Date dateISO = dateISOformat.parse(formattedISOversion); Date dateNodeISO = dateISOformat.parse(nodeInfo[2].split("\\.")[0].trim()); if (dateISO.compareTo(dateNodeISO)>0) { alert = true; break; } } catch (Exception ex) { getLogger().error("Error while trying to determine host upgrade alert", ex); } } return alert; }
Source:
protected void refreshAnchorTypes() { Type type = info.getFreshSignature(); TypeScope scope = new TypeScope(); for (OutputAnchor anchor : outputs) { if (type instanceof FunType) { FunType ftype = (FunType)type; anchor.setFreshRequiredType(ftype.getArgument(), scope); type = ftype.getResult(); } else { new RuntimeException("too many arguments in this functionblock " + name.getText()); } } input.setFreshRequiredType(type, scope); }

Target:
protected void refreshAnchorTypes() { Type type = info.getFreshSignature(); TypeScope scope = new TypeScope(); for (OutputAnchor anchor : outputs) { if (type instanceof FunType) { FunType ftype = (FunType)type; anchor.setFreshRequiredType(ftype.getArgument(), scope); type = ftype.getResult(); } else { throw new RuntimeException("too many arguments in this matchblock " + name.getText()); } } input.setFreshRequiredType(type, scope); }
Source:
private Connection getNonCommittingConnection() { Connection connection = conn.get(); try { connection.setAutoCommit(false); return connection; } catch (SQLException e) { throw new RuntimeException(e); } }

Target:
private Connection getNonCommittingConnection() { Connection connection = conn.get(); try { connection.setAutoCommit(false); connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); return connection; } catch (SQLException e) { throw new RuntimeException(e); } }
Source:
void resumeReadsInternal(boolean wakeup) { synchronized (lock) { state |= STATE_READS_RESUMED; if (wakeup) state |= STATE_READS_AWAKEN; else if (!anyAreSet(state, STATE_READS_RESUMED)) return; if (!anyAreSet(state, STATE_IN_LISTENER_LOOP)) { state |= STATE_IN_LISTENER_LOOP; getFramedChannel().runInIoThread(new Runnable() { @Override public void run() { try { boolean readAgain; do { synchronized(lock) { state &= ~STATE_READS_AWAKEN; } ChannelListener<? super R> listener = getReadListener(); if (listener == null || !isReadResumed()) { return; } ChannelListeners.invokeChannelListener((R) AbstractFramedStreamSourceChannel.this, listener); final boolean moreData = (frameDataRemaining > 0 && data != null) || !pendingFrameData.isEmpty() || anyAreSet(state, STATE_WAITNG_MINUS_ONE); synchronized (lock) { readAgain =((isReadResumed() && moreData) || allAreSet(state, STATE_READS_AWAKEN)) && allAreClear(state,STATE_CLOSED | STATE_STREAM_BROKEN); if (!readAgain) state &= ~STATE_IN_LISTENER_LOOP; } } while (readAgain); } catch (RuntimeException e) { synchronized (lock) { state &= ~STATE_IN_LISTENER_LOOP; } } } }); } } }

Target:
void resumeReadsInternal(boolean wakeup) { synchronized (lock) { state |= STATE_READS_RESUMED; if (wakeup) state |= STATE_READS_AWAKEN; else if (!anyAreSet(state, STATE_READS_RESUMED)) return; if (!anyAreSet(state, STATE_IN_LISTENER_LOOP)) { state |= STATE_IN_LISTENER_LOOP; getFramedChannel().runInIoThread(new Runnable() { @Override public void run() { try { boolean readAgain; do { synchronized(lock) { state &= ~STATE_READS_AWAKEN; } ChannelListener<? super R> listener = getReadListener(); if (listener == null || !isReadResumed()) { return; } ChannelListeners.invokeChannelListener((R) AbstractFramedStreamSourceChannel.this, listener); final boolean moreData = (frameDataRemaining > 0 && data != null) || !pendingFrameData.isEmpty() || anyAreSet(state, STATE_WAITNG_MINUS_ONE); synchronized (lock) { readAgain =((isReadResumed() && moreData) || allAreSet(state, STATE_READS_AWAKEN)) && allAreClear(state,STATE_CLOSED | STATE_STREAM_BROKEN); if (!readAgain) state &= ~STATE_IN_LISTENER_LOOP; } } while (readAgain); } catch (RuntimeException | Error e) { synchronized (lock) { state &= ~STATE_IN_LISTENER_LOOP; } } } }); } } }
Source:
public FastqWriter getFirstOfPair() { return firstOfPair; }

Target:
private FastqWriter getFirstOfPair() { return firstOfPair; }
Source:
public void contextOfObject() { final String key1 = "Key1"; final String value1 = "first-value"; Map<Object, Object> keyValueMap = new HashMap<>(); keyValueMap.put(key1, value1); Context keyValueContext = Context.of(keyValueMap); System.out.printf("Key1 value %s%n", keyValueContext.getData(key1).get().toString()); END: com.azure.core.util.context.of#map }

Target:
public void contextOfObject() { final String key1 = "Key1"; final String value1 = "first-value"; Map<Object, Object> keyValueMap = new HashMap<>(); keyValueMap.put(key1, value1); Context keyValueContext = Context.of(keyValueMap); System.out.printf("Key1 value %s%n", keyValueContext.getData(key1).get()); END: com.azure.core.util.context.of#map }
Source:
public static void registerModuleSource(IAnalysisModuleSource source) { synchronized (fSources) { fSources.add(source); refreshModules(); } }

Target:
public static synchronized void registerModuleSource(IAnalysisModuleSource source) { fSources.add(source); refreshModules(); }
Source:
public String execute(String container, Blob blob) { String blobName = blob.getMetadata().getName(); Payload payload = blob.getPayload(); Long length = payload.getContentMetadata().getContentLength(); checkNotNull(length, "please invoke payload.getContentMetadata().setContentLength(length) prior to azure block upload"); checkArgument(length <= (MAX_NUMBER_OF_BLOCKS * MAX_BLOCK_SIZE)); Long offset = 0L; List<String> blockIds = new LinkedList<String>(); int blockCount = 0; int totalBlocks = (int) Math.ceil(length / MAX_BLOCK_SIZE) + 1; long bytesWritten = 0; while (offset < length) { blockCount++; long chunkSize = MAX_BLOCK_SIZE; if (blockCount >= totalBlocks) { chunkSize = length % MAX_BLOCK_SIZE; } bytesWritten += chunkSize; Payload block = slicer.slice(payload, offset, chunkSize); offset += MultipartUploadStrategy.MAX_BLOCK_SIZE; String blockName = blobName + "-" + offset + "-" + new SecureRandom().nextInt(); byte blockIdBytes[] = Hashing.md5().hashBytes(blockName.getBytes()).asBytes(); String blockId = BaseEncoding.base64().encode(blockIdBytes); blockIds.add(blockId); client.putBlock(container, blobName, blockId, block); } assert(bytesWritten == length); return client.putBlockList(container, blobName, blockIds); }

Target:
public String execute(String container, Blob blob) { String blobName = blob.getMetadata().getName(); Payload payload = blob.getPayload(); long length = payload.getContentMetadata().getContentLength(); checkNotNull(length, "please invoke payload.getContentMetadata().setContentLength(length) prior to azure block upload"); checkArgument(length <= (MAX_NUMBER_OF_BLOCKS * MAX_BLOCK_SIZE)); long offset = 0L; List<String> blockIds = Lists.newArrayList(); int blockCount = 0; int totalBlocks = (int) Math.ceil(((double)length) / MAX_BLOCK_SIZE); long bytesWritten = 0; while (offset < length) { blockCount++; long chunkSize = MAX_BLOCK_SIZE; if (blockCount >= totalBlocks) { chunkSize = length % MAX_BLOCK_SIZE; } bytesWritten += chunkSize; Payload block = slicer.slice(payload, offset, chunkSize); offset += MultipartUploadStrategy.MAX_BLOCK_SIZE; String blockName = blobName + "-" + offset + "-" + new SecureRandom().nextInt(); byte blockIdBytes[] = Hashing.md5().hashBytes(blockName.getBytes()).asBytes(); String blockId = BaseEncoding.base64().encode(blockIdBytes); blockIds.add(blockId); client.putBlock(container, blobName, blockId, block); } assert(bytesWritten == length); return client.putBlockList(container, blobName, blockIds); }
Source:
protected void executeQueryCommand() { SSHClient client = null; try { client = connect(getParameters().getServerName()); validateFingerprint(client, getParameters().getFingerprint()); authenticate(client, "root", getParameters().getRootPassword()); String serversXml = executeCommand(client); getQueryReturnValue().setReturnValue(extractServers(serversXml)); } catch (Exception e) { throw new RuntimeException(e); } finally { if (client != null) { client.disconnect(); } } }

Target:
protected void executeQueryCommand() { SSHClient client = null; try { client = connect(getParameters().getServerName()); validateFingerprint(client, getParameters().getFingerprint()); authenticate(client, ROOT, getParameters().getPassword()); String serversXml = executeCommand(client); getQueryReturnValue().setReturnValue(extractServers(serversXml)); } catch (Exception e) { throw new RuntimeException(e); } finally { if (client != null) { client.disconnect(); } } }
Source:
public boolean spawnWeatherEntity(Entity entity, Cause cause) { checkNotNull(entity, "Entity cannot be null!")return addWeatherEffect((net.minecraft.entity.Entity) entity); }

Target:
public boolean spawnWeatherEntity(Entity entity, Cause cause) { checkNotNull(entity, "Entity cannot be null!"); return addWeatherEffect((net.minecraft.entity.Entity) entity); }
Source:
public DetectorOptions build() { message = Optional.ofNullable(message).orElse(""); suppressor = Optional.ofNullable(suppressor).orElse(NeverSuppress.INSTANCE); computePattern(); return DetectorOptions.this; }

Target:
public DetectorOptions build() { message = Optional.ofNullable(message).orElse(""); suppressor = Optional.ofNullable(suppressor).orElse(NeverSuppress.INSTANCE); pattern = Optional.ofNullable(format).map(this::createPattern).orElse(null); return DetectorOptions.this; }
Source:
public static void write(final int major, final Slice slice, final OutputStream outputStream) throws IOException { slice.nofBlocks = 1 + slice.external.size() + (slice.embeddedRefBlock == null ? 0 : 1); { slice.contentIDs = new int[slice.external.size()]; final int i = 0; for (final int id : slice.external.keySet()) slice.contentIDs[i] = id; } slice.headerBlock = Block.uncompressedSliceHeaderBlock(createSliceHeaderBlockContent(major, slice)); slice.headerBlock.write(major, outputStream); slice.coreBlock.write(major, outputStream); for (final ExternalDataBlock block : slice.external.values()) block.write(major, outputStream); }

Target:
public static void write(final int major, final Slice slice, final OutputStream outputStream) throws IOException { slice.nofBlocks = 1 + slice.external.size() + (slice.embeddedRefBlock == null ? 0 : 1); { slice.contentIDs = new int[slice.external.size()]; final int i = 0; for (final int id : slice.external.keySet()) slice.contentIDs[i] = id; } slice.headerBlock = Block.createRawSliceHeaderBlock(createSliceHeaderBlockContent(major, slice)); slice.headerBlock.write(major, outputStream); slice.coreBlock.write(major, outputStream); for (final Block block : slice.external.values()) block.write(major, outputStream); }
Source:
private Diff getMasterEquivalenceForReferenceChange(ReferenceChange diff, boolean mergeRightToLeft) { Diff masterDiff = null; final Iterator<Diff> equivalentDiffs = diff.getEquivalence().getDifferences().iterator(); final Iterator<Diff> eOppositeDiffs = Iterators.filter(equivalentDiffs, isDiffOnEOppositeOf(diff)); while (masterDiff == null && eOppositeDiffs.hasNext()) { final ReferenceChange candidate = (ReferenceChange)eOppositeDiffs.next(); if (isOneToManyAndAdd(diff, candidate, mergeRightToLeft)) { masterDiff = candidate; } else if (!isSet(diff, mergeRightToLeft) && isOneToOneAndSet(diff, candidate, mergeRightToLeft)) { masterDiff = candidate; } } if (masterDiff == null) { for (Diff equivalentDiff : diff.getEquivalence().getDifferences()) { if (equivalentDiff instanceof FeatureMapChange) { masterDiff = equivalentDiff; break; } } } return masterDiff; }

Target:
private Diff getMasterEquivalenceForReferenceChange(ReferenceChange diff, boolean mergeRightToLeft) { Diff masterDiff = getMasterEquivalenceOnEOpposite(diff, mergeRightToLeft); if (masterDiff == null) { masterDiff = getMasterEquivalenceFeatureMap(diff); } return masterDiff; }
Source:
MockChartLayout() { layoutWidth = ComponentConstants.VIDEOPLAYER_PREFERRED_WIDTH; layoutHeight = ComponentConstants.VIDEOPLAYER_PREFERRED_HEIGHT; }

Target:
MockChartLayout() { layoutWidth = ComponentConstants.CHART_PREFERRED_WIDTH; layoutHeight = ComponentConstants.CHART_PREFERRED_HEIGHT; }
Source:
public <E extends Throwable> E expectError(Class<E> clazz, long timeoutMillis, String errorMsg) throws Exception { Thread.sleep(timeoutMillis); if (env.asyncErrors.isEmpty()) { env.flop(String.format("%s within %d ms", errorMsg, timeoutMillis)); } else { Throwable thrown = env.asyncErrors.remove(0); if (thrown != null && clazz.isInstance(thrown)) { return (E) thrown; } else if (thrown != null) { env.flop(String.format("%s within %d ms; Got %s but expected %s", errorMsg, timeoutMillis, thrown.getClass().getCanonicalName(), clazz.getCanonicalName())); } else { env.flop(String.format("%s within %d ms; Got `null` but expected %s", errorMsg, timeoutMillis, clazz.getCanonicalName())); } } return null; }

Target:
public <E extends Throwable> E expectError(Class<E> clazz, long timeoutMillis, String errorMsg) throws Exception { Thread.sleep(timeoutMillis); if (env.asyncErrors.isEmpty()) { env.flop(String.format("%s within %d ms", errorMsg, timeoutMillis)); } else { Throwable thrown = env.asyncErrors.remove(0); if (clazz.isInstance(thrown)) { return (E) thrown; } else { env.flop(String.format("%s within %d ms; Got %s but expected %s", errorMsg, timeoutMillis, thrown.getClass().getCanonicalName(), clazz.getCanonicalName())); } } return null; }
Source:
public void beginFormat(Format format, Map<String, String> parameters) { if (this.previousFormatParameters != null) { if (!this.previousFormatParameters.equals(parameters)) { printParameters(parameters, false); } this.previousFormatParameters = null; } else if (this.previousFormatParameters == null) { printParameters(parameters, false); } switch (format) { case BOLD: handleEmptyParameters(); getXWikiPrinter().printBeginBold(); break; case ITALIC: handleEmptyParameters(); getXWikiPrinter().printBeginItalic(); break; case STRIKEDOUT: print("--"); break; case UNDERLINED: print("__"); break; case SUPERSCRIPT: print("^^"); break; case SUBSCRIPT: print(",,"); break; case MONOSPACE: print("##"); break; case NONE: break; default: break; } }

Target:
public void beginFormat(Format format, Map<String, String> parameters) { if (this.previousFormatParameters != null && !parameters.isEmpty()) { if (!this.previousFormatParameters.equals(parameters)) { printParameters(parameters, false); } this.previousFormatParameters = null; } else if (this.previousFormatParameters == null) { printParameters(parameters, false); } switch (format) { case BOLD: handleEmptyParameters(); getXWikiPrinter().printBeginBold(); break; case ITALIC: handleEmptyParameters(); getXWikiPrinter().printBeginItalic(); break; case STRIKEDOUT: print("--"); break; case UNDERLINED: print("__"); break; case SUPERSCRIPT: print("^^"); break; case SUBSCRIPT: print(",,"); break; case MONOSPACE: print("##"); break; case NONE: break; default: break; } }
Source:
@Test public void verbose() throws Exception { DurableTask task = new PowershellScript("$VerbosePreference = \"Continue\"; Write-Verbose \"Hello, World!\""); task.captureOutput(); Controller c = task.launch(new EnvVars(), ws, launcher, listener); while (c.exitStatus(ws, launcher) == null) { Thread.sleep(100); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); c.writeLog(ws, baos); assertEquals(0, c.exitStatus(ws, launcher).intValue()); assertThat(baos.toString(), containsString("Hello, World!")); c.stop(ws,launcher); c.cleanup(ws); }

Target:
@Test public void verbose() throws Exception { DurableTask task = new PowershellScript("$VerbosePreference = \"Continue\"; Write-Verbose \"Hello, World!\""); task.captureOutput(); Controller c = task.launch(new EnvVars(), ws, launcher, listener); while (c.exitStatus(ws, launcher) == null) { Thread.sleep(100); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); c.writeLog(ws, baos); assertEquals(0, c.exitStatus(ws, launcher).intValue()); assertThat(baos.toString(), containsString("Hello, World!")); c.cleanup(ws); }
Source:
void experimentWithMissingValuesReturnsNotAvailable() { String experimentAccession = "E-GEOD-71585"; ImmutableList<String> cellIdsWithMissingValues = ImmutableList.of( "SRR2138737", "SRR2140225", "SRR2139550", "SRR2139566"); Map<String, String> result = subject.getMetadataValueForCellIds(experimentAccession, SingleCellAnalyticsCollectionProxy.CHARACTERISTIC_INFERRED_CELL_TYPE, cellIdsWithMissingValues); assertThat(result.values()).containsOnly("not available"); }

Target:
void experimentWithMissingValuesReturnsNotAvailable() { String experimentAccession = "E-GEOD-71585"; ImmutableList<String> cellIdsWithMissingValues = ImmutableList.of( "SRR2138737", "SRR2140225", "SRR2139550", "SRR2139566"); Map<String, String> result = subject.getMetadataValueForCellIds(experimentAccession, SingleCellAnalyticsCollectionProxy.CHARACTERISTIC_INFERRED_CELL_TYPE, cellIdsWithMissingValues); assertThat(result.values()).containsOnly(MISSING_METADATA_VALUE_PLACEHOLDER); }
Source:
public List<EmailWrapper> generateFeedbackSessionPublishedEmails(FeedbackSessionAttributes session) { boolean isEmailNeeded = fsLogic.isFeedbackSessionViewableToStudents(session); List<StudentAttributes> students = isEmailNeeded ? studentsLogic.getStudentsForCourse(session.getCourseId()) : new ArrayList<StudentAttributes>(); List<InstructorAttributes> instructors = isEmailNeeded ? instructorsLogic.getInstructorsForCourse(session.getCourseId()) : new ArrayList<InstructorAttributes>(); return generateFeedbackSessionPublishedEmails(session, students, instructors); }

Target:
public List<EmailWrapper> generateFeedbackSessionPublishedEmails(FeedbackSessionAttributes session) { boolean isEmailNeeded = fsLogic.isFeedbackSessionViewableToStudents(session); List<InstructorAttributes> instructors = isEmailNeeded ? instructorsLogic.getInstructorsForCourse(session.getCourseId()) : new ArrayList<>(); List<StudentAttributes> students = isEmailNeeded ? studentsLogic.getStudentsForCourse(session.getCourseId()) : new ArrayList<>(); return generateFeedbackSessionPublishedEmails(session, students, instructors); }
Source:
public CircularBuffer(int n, int spin) { if (n < 0 || n > MAX_SIZE) throw new RuntimeException(String.format("Error: value too large: %d%n", n)); final int size = (0 == n) ? 1 : (0 == (n & (n - 1))) ? n : (1 << (32 - Integer.numberOfLeadingZeros(n))); buffer = (T[])new Object[size]; buffermask = size - 1; spinMillis = spin; }

Target:
public CircularBuffer(int n, int spin) { if (n < 0) { throw new IllegalArgumentException(String.format("Error: value cannot be negative: %d", n)); } if (n > MAX_SIZE) { throw new IllegalArgumentException(String.format("Error: value too large: %d", n)); } final int size = (0 == n) ? 1 : (0 == (n & (n - 1))) ? n : (1 << (32 - Integer.numberOfLeadingZeros(n))); buffer = (T[])new Object[size]; buffermask = size - 1; spinMillis = spin; }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; StorageDevice other = (StorageDevice) obj; if (canCreateBrick == null) { if (other.canCreateBrick != null) return false; } else if (!canCreateBrick.equals(other.canCreateBrick)) return false; if (description == null) { if (other.description != null) return false; } else if (!description.equals(other.description)) return false; if (devPath == null) { if (other.devPath != null) return false; } else if (!devPath.equals(other.devPath)) return false; if (devType == null) { if (other.devType != null) return false; } else if (!devType.equals(other.devType)) return false; if (devUuid == null) { if (other.devUuid != null) return false; } else if (!devUuid.equals(other.devUuid)) return false; if (fsType == null) { if (other.fsType != null) return false; } else if (!fsType.equals(other.fsType)) return false; if (fsUuid == null) { if (other.fsUuid != null) return false; } else if (!fsUuid.equals(other.fsUuid)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (mountPoint == null) { if (other.mountPoint != null) return false; } else if (!mountPoint.equals(other.mountPoint)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (size == null) { if (other.size != null) return false; } else if (!size.equals(other.size)) return false; if (vdsId == null) { if (other.vdsId != null) return false; } else if (!vdsId.equals(other.vdsId)) return false; return true; }

Target:
public boolean equals(Object obj) { if ((obj != null) && (obj instanceof StorageDevice)) { StorageDevice storageDevice = (StorageDevice) obj; if (ObjectUtils.objectsEqual(getId(), storageDevice.getId()) && (ObjectUtils.objectsEqual(getCanCreateBrick(), storageDevice.getCanCreateBrick())) && (ObjectUtils.objectsEqual(getDescription(), storageDevice.getDescription())) && (ObjectUtils.objectsEqual(getDevPath(), storageDevice.getDevPath())) && (ObjectUtils.objectsEqual(getDevType(), storageDevice.getDevType())) && (ObjectUtils.objectsEqual(getDevUuid(), storageDevice.getDevUuid())) && (ObjectUtils.objectsEqual(getFsType(), storageDevice.getFsType())) && (ObjectUtils.objectsEqual(getFsUuid(), storageDevice.getFsUuid())) && (ObjectUtils.objectsEqual(getMountPoint(), storageDevice.getMountPoint())) && (ObjectUtils.objectsEqual(getName(), storageDevice.getName())) && (ObjectUtils.objectsEqual(getSize(), storageDevice.getSize())) && (ObjectUtils.objectsEqual(getVdsId(), storageDevice.getVdsId()))) { return true; } } return false; }
Source:
public static void listObject_test5() throws Exception { int i; int totalObjsNr = 1050; System.out.println("Test: listObjects(final String bucketName, final String prefix, final boolean recursive)"); String[] filenames = new String[totalObjsNr]; for (i = 0; i < totalObjsNr; i++) { String filename = createFile(1); client.putObject(bucketName, filename, filename); Files.delete(Paths.get(filename)); filenames[i] = filename; } i = 0; for (Result<?> r : client.listObjects(bucketName, "minio", true)) { ignore(i++, r.get()); } if (i != totalObjsNr) { throw new Exception("[FAILED] Test: listObject_test5(), number of items found: " + i); } for (i = 0; i < totalObjsNr; i++) { client.removeObject(bucketName, filenames[i]); } }

Target:
public static void listObject_test5() throws Exception { int i; int objCount = 1050; System.out.println("Test: recursive: listObjects(final String bucketName, final String prefix" + ", final boolean recursive)"); String[] objectNames = new String[objCount]; String baseFilename = createFile(1); for (i = 0; i < objCount; i++) { objectNames[i] = baseFilename + "-" + i; client.putObject(bucketName, objectNames[i], baseFilename); } Files.delete(Paths.get(baseFilename)); i = 0; for (Result<?> r : client.listObjects(bucketName, "minio", true)) { ignore(i++, r.get()); } if (i != objCount) { throw new Exception("[FAILED] Test: recursive: listObject_test5(), number of items, expected: " + objCount + ", found: " + i); } for (i = 0; i < objCount; i++) { client.removeObject(bucketName, objectNames[i]); } }
Source:
public void transform(StructuredRecord in, Emitter<StructuredRecord> emitter) throws Exception { StructuredRecord.Builder builder = StructuredRecord.builder(outSchema); Schema inSchema = in.getSchema(); List<Field> inFields = inSchema.getFields(); for (Field field : inFields) { String name = field.getName(); if (!outSchemaMap.containsKey(name)) { continue; } Schema.Type outFieldType = outSchemaMap.get(name); if (!compMap.containsKey(name) || compMap.get(name) == CompressorType.NONE) { builder.set(name, in.get(name)); } else { byte[] obj = new byte[0]; if (field.getSchema().getType() == Schema.Type.BYTES) { obj = in.get(name); } else if (field.getSchema().getType() == Schema.Type.STRING) { obj = ((String) in.get(name)).getBytes("UTF-8"); } byte[] outValue = new byte[0]; CompressorType type = compMap.get(name); if (type == CompressorType.SNAPPY) { outValue = Snappy.compress(obj); } else if (type == CompressorType.ZIP) { outValue = zip(obj); } else if (type == CompressorType.GZIP) { outValue = gzip(obj); } if (outFieldType == Schema.Type.BYTES) { if (outValue != null) { builder.set(name, outValue); } } else { LOG.warn("Output field '" + name + "' is not of BYTES. In order to emit compressed data, you should set " + "it to type BYTES."); } } } emitter.emit(builder.build()); }

Target:
public void transform(StructuredRecord in, Emitter<StructuredRecord> emitter) throws Exception { StructuredRecord.Builder builder = StructuredRecord.builder(outSchema); Schema inSchema = in.getSchema(); List<Field> inFields = inSchema.getFields(); for (Field field : inFields) { String name = field.getName(); if (!outSchemaMap.containsKey(name)) { continue; } Schema.Type outFieldType = outSchemaMap.get(name); if (!compMap.containsKey(name) || compMap.get(name) == CompressorType.NONE) { builder.set(name, in.get(name)); } else { byte[] obj = new byte[0]; if (field.getSchema().getType() == Schema.Type.BYTES) { obj = in.get(name); } else if (field.getSchema().getType() == Schema.Type.STRING) { obj = Bytes.toBytes((String) in.get(name)); } byte[] outValue = new byte[0]; CompressorType type = compMap.get(name); if (type == CompressorType.SNAPPY) { outValue = Snappy.compress(obj); } else if (type == CompressorType.ZIP) { outValue = zip(obj); } else if (type == CompressorType.GZIP) { outValue = gzip(obj); } if (outFieldType == Schema.Type.BYTES) { if (outValue != null) { builder.set(name, outValue); } } else { LOG.warn("Output field '" + name + "' is not of BYTES. In order to emit compressed data, you should set " + "it to type BYTES."); } } } emitter.emit(builder.build()); }
Source:
public Optional<UpgradeNodeRequest> deleteFWUpgradeNode(final UpgradeNodeRequest upgradeNode){ try { final Map<String, ExpectedAttributeValue> deleteConditions = new HashMap<String, ExpectedAttributeValue>(); deleteConditions.put(GROUP_NAME_ATTRIBUTE_NAME, new ExpectedAttributeValue( new AttributeValue().withS(upgradeNode.groupName) )); deleteConditions.put(FROM_FW_VERSION_ATTRIBUTE_NAME, new ExpectedAttributeValue( new AttributeValue().withN(upgradeNode.fromFWVersion.toString()) )); HashMap<String, AttributeValue> keys = new HashMap<String, AttributeValue>(); keys.put(GROUP_NAME_ATTRIBUTE_NAME, new AttributeValue().withS(upgradeNode.groupName)); keys.put(FROM_FW_VERSION_ATTRIBUTE_NAME, new AttributeValue().withN(upgradeNode.fromFWVersion.toString())); final DeleteItemRequest deleteItemRequest = new DeleteItemRequest() .withTableName(tableName) .withKey(keys) .withExpected(deleteConditions) .withReturnValues(ReturnValue.ALL_OLD); final DeleteItemResult result = this.dynamoDBClient.deleteItem(deleteItemRequest); return attributeValuesToUpgradeNode(result.getAttributes()); } catch (AmazonServiceException ase) { LOGGER.error("Failed to delete Upgrade Node for Group: {}, error {}", upgradeNode.groupName, ase.getMessage()); } return Optional.absent(); }

Target:
public Optional<UpgradeNodeRequest> deleteFWUpgradeNode(final UpgradeNodeRequest upgradeNode){ try { final Map<String, ExpectedAttributeValue> deleteConditions = new HashMap<String, ExpectedAttributeValue>(); deleteConditions.put(GROUP_NAME_ATTRIBUTE_NAME, new ExpectedAttributeValue( new AttributeValue().withS(upgradeNode.groupName) )); deleteConditions.put(FROM_FW_VERSION_ATTRIBUTE_NAME, new ExpectedAttributeValue( new AttributeValue().withN(upgradeNode.fromFWVersion.toString()) )); HashMap<String, AttributeValue> keys = new HashMap<String, AttributeValue>(); keys.put(GROUP_NAME_ATTRIBUTE_NAME, new AttributeValue().withS(upgradeNode.groupName)); keys.put(FROM_FW_VERSION_ATTRIBUTE_NAME, new AttributeValue().withN(upgradeNode.fromFWVersion.toString())); final DeleteItemRequest deleteItemRequest = new DeleteItemRequest() .withTableName(tableName) .withKey(keys) .withExpected(deleteConditions) .withReturnValues(ReturnValue.ALL_OLD); final DeleteItemResult result = this.dynamoDBClient.deleteItem(deleteItemRequest); return attributeValuesToUpgradeNode(result.getAttributes()); } catch (AmazonServiceException ase) { LOGGER.error("Failed to delete Upgrade Node for Group: {}. Service error {}", upgradeNode.groupName, ase.getMessage()); } catch (AmazonClientException awcEx){ LOGGER.error("Failed to delete Upgrade Node for Group: {}. Client error: {}", awcEx.getMessage()); } catch (Exception e) { LOGGER.error("Exception thrown while deleting upgrade node. {}", e.getMessage()); return Optional.absent(); } return Optional.absent(); }
Source:
public void testRemovingExecutor() throws Exception { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); Executor executor = loader.addExecutor("localhost1", 12345); loader.removeExecutor("localhost1", 12345); Executor fetchedExecutor = loader.fetchExecutor("localhost1", 12345); Assert.assertNull(fetchedExecutor); }

Target:
public void testRemovingExecutor() throws Exception { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); Executor executor = loader.addExecutor("localhost1", 12345); Assert.assertNotNull(executor); loader.removeExecutor("localhost1", 12345); Executor fetchedExecutor = loader.fetchExecutor("localhost1", 12345); Assert.assertNull(fetchedExecutor); }
Source:
public Container getContainer(String accountName, String containerName) throws AccountServiceException { Container primaryResult = primaryAccountService.getContainer(accountName, containerName); try { Container secondaryResult = secondaryAccountService.getContainer(accountName, containerName); if (++getContainerRequestCount % 100 < config.samplingPercentageForGetContainerConsistencyCheck && primaryResult != null && !primaryResult.equals(secondaryResult)) { logger.warn("Inconsistency detected between primary and secondary for accountName ={}, containerName = {}", accountName, containerName); accountServiceMetrics.getContainerDataInconsistencyCount.inc(); } } catch (Exception e) { accountServiceMetrics.getContainerDataInconsistencyCount.inc(); logger.error("get container failed for secondary for accountName={}, containerName={}", accountName, containerName, e); } return primaryResult; }

Target:
public Container getContainer(String accountName, String containerName) throws AccountServiceException { Container primaryResult = primaryAccountService.getContainer(accountName, containerName); if (shouldCompare()) { try { Container secondaryResult = secondaryAccountService.getContainer(accountName, containerName); if (primaryResult != null && !primaryResult.equals(secondaryResult)) { logger.warn("Inconsistency detected between primary and secondary for accountName ={}, containerName = {}", accountName, containerName); accountServiceMetrics.accountDataInconsistencyCount.inc(); } } catch (Exception e) { accountServiceMetrics.accountDataInconsistencyCount.inc(); logger.error("get container failed for secondary for accountName={}, containerName={}", accountName, containerName, e); } } return primaryResult; }
Source:
public AuthorizationResponse authorize(final AuthorizationRequest request) throws AuthorizationDeniedException { if (request == null) { throw new IllegalArgumentException("Authorization request must not be null"); } Callable<AuthorizationResponse> callable = new Callable<AuthorizationResponse>() { @Override public AuthorizationResponse call() throws Exception { if (request.getAudience() == null) { request.setAudience(configuration.getResource()); } else { request.setAudience(request.getAudience()); } HttpMethod<AuthorizationResponse> method = http.<AuthorizationResponse>post(serverConfiguration.getTokenEndpoint()); if (token != null) { method = method.authorizationBearer(token.call()); } return method .authentication() .uma(request) .response() .json(AuthorizationResponse.class) .execute(); } }; try { return callable.call(); } catch (Exception cause) { return Throwables.retryAndWrapExceptionIfNecessary(callable, token, "Failed to obtain authorization data", cause); } }

Target:
public AuthorizationResponse authorize(final AuthorizationRequest request) throws AuthorizationDeniedException { if (request == null) { throw new IllegalArgumentException("Authorization request must not be null"); } Callable<AuthorizationResponse> callable = new Callable<AuthorizationResponse>() { @Override public AuthorizationResponse call() throws Exception { if (request.getAudience() == null) { request.setAudience(configuration.getResource()); } HttpMethod<AuthorizationResponse> method = http.<AuthorizationResponse>post(serverConfiguration.getTokenEndpoint()); if (token != null) { method = method.authorizationBearer(token.call()); } return method .authentication() .uma(request) .response() .json(AuthorizationResponse.class) .execute(); } }; try { return callable.call(); } catch (Exception cause) { return Throwables.retryAndWrapExceptionIfNecessary(callable, token, "Failed to obtain authorization data", cause); } }
Source:
public Cursor find(SessionLocal session, SearchRow first, SearchRow last) { ArrayList<Value> params = Utils.newSmallArrayList(); StringBuilder builder = new StringBuilder("SELECT * FROM ").append(targetTableName).append(" T"); boolean f = false; for (int i = 0; first != null && i < first.getColumnCount(); i++) { Value v = first.getValue(i); if (v != null) { builder.append(f ? " AND " : " WHERE "); f = true; Column col = table.getColumn(i); col.getSQL(builder, sqlFlags); if (v == ValueNull.INSTANCE) { builder.append(" IS NULL"); } else { builder.append(">="); addParameter(builder, col); params.add(v); } } } for (int i = 0; last != null && i < last.getColumnCount(); i++) { Value v = last.getValue(i); if (v != null) { builder.append(f ? " AND " : " WHERE "); f = true; Column col = table.getColumn(i); col.getSQL(builder, sqlFlags); if (v == ValueNull.INSTANCE) { builder.append(" IS NULL"); } else { builder.append("<="); addParameter(builder, col); params.add(v); } } } String sql = builder.toString(); try { PreparedStatement prep = link.execute(sql, params, false, session); if (link.getFetchSize() != -1) { prep.setFetchSize(link.getFetchSize()); } ResultSet rs = prep.getResultSet(); return new LinkedCursor(link, rs, session, sql, prep); } catch (Exception e) { throw TableLink.wrapException(sql, e); } }

Target:
public Cursor find(SessionLocal session, SearchRow first, SearchRow last) { ArrayList<Value> params = Utils.newSmallArrayList(); StringBuilder builder = new StringBuilder("SELECT * FROM ").append(targetTableName).append(" T"); boolean f = false; for (int i = 0; first != null && i < first.getColumnCount(); i++) { Value v = first.getValue(i); if (v != null) { builder.append(f ? " AND " : " WHERE "); f = true; Column col = table.getColumn(i); col.getSQL(builder, sqlFlags); if (v == ValueNull.INSTANCE) { builder.append(" IS NULL"); } else { builder.append(">="); addParameter(builder, col); params.add(v); } } } for (int i = 0; last != null && i < last.getColumnCount(); i++) { Value v = last.getValue(i); if (v != null) { builder.append(f ? " AND " : " WHERE "); f = true; Column col = table.getColumn(i); col.getSQL(builder, sqlFlags); if (v == ValueNull.INSTANCE) { builder.append(" IS NULL"); } else { builder.append("<="); addParameter(builder, col); params.add(v); } } } String sql = builder.toString(); try { PreparedStatement prep = link.execute(sql, params, false, session); ResultSet rs = prep.getResultSet(); return new LinkedCursor(link, rs, session, sql, prep); } catch (Exception e) { throw TableLink.wrapException(sql, e); } }
Source:
public String render(final GetBucketResult br) { if( !br.getObjIterator().hasNext()) { return "No objects were reported in the bucket '" + br.getBucketName() + "'"; } return ASCIITable.getInstance().getTable(getHeaders(), formatBucketList(br.getObjIterator())); }

Target:
public String render(final GetBucketResult br) { if( (null == br.getObjIterator()) || !br.getObjIterator().hasNext()) { return "No objects were reported in bucket '" + br.getBucketName() + "'"; } return ASCIITable.getInstance().getTable(getHeaders(), formatBucketList(br.getObjIterator())); }
Source:
public Query<T> withTimeoutAndMaxScatterGatherBytes(Query<T> query, ServerConfig serverConfig) { Query<T> new_query = QueryContexts.verifyMaxQueryTimeout( QueryContexts.withMaxScatterGatherBytes( QueryContexts.withDefaultTimeout( query, Math.min(serverConfig.getDefaultQueryTimeout(), serverConfig.getMaxQueryTimeout()) ), serverConfig.getMaxScatterGatherBytes() ), serverConfig.getMaxQueryTimeout() ); return new_query.withOverriddenContext(ImmutableMap.of(DirectDruidClient.QUERY_FAIL_TIME, this.startTimeMillis + QueryContexts.getTimeout(new_query))); }

Target:
public Query<T> withTimeoutAndMaxScatterGatherBytes(Query<T> query, ServerConfig serverConfig) { Query<T> newQuery = QueryContexts.verifyMaxQueryTimeout( QueryContexts.withMaxScatterGatherBytes( QueryContexts.withDefaultTimeout( query, Math.min(serverConfig.getDefaultQueryTimeout(), serverConfig.getMaxQueryTimeout()) ), serverConfig.getMaxScatterGatherBytes() ), serverConfig.getMaxQueryTimeout() ); return newQuery.withOverriddenContext(ImmutableMap.of(DirectDruidClient.QUERY_FAIL_TIME, this.startTimeMillis + QueryContexts.getTimeout(newQuery))); }
Source:
public Queue<Selectable> createFlowTriggerEventQueue(DistroxUpgradeTriggerEvent event) { Queue<Selectable> chain = new ConcurrentLinkedQueue<>(); chain.add(new StackEvent(SaltUpdateEvent.SALT_UPDATE_EVENT.event(), event.getResourceId(), event.accepted())); chain.add(new DatalakeClusterUpgradeTriggerEvent(CLUSTER_UPGRADE_INIT_EVENT.event(), event.getResourceId(), event.accepted(), event.getImageChangeDto().getImageId())); chain.add(new StackImageUpdateTriggerEvent(FlowChainTriggers.STACK_IMAGE_UPDATE_TRIGGER_EVENT, event.getImageChangeDto())); if (event.isReplaceVms()) { LOGGER.warn("Replace VMs for DistroX is not implemented!"); } return chain; }

Target:
public Queue<Selectable> createFlowTriggerEventQueue(DistroxUpgradeTriggerEvent event) { Queue<Selectable> chain = new ConcurrentLinkedQueue<>(); chain.add(new StackEvent(SaltUpdateEvent.SALT_UPDATE_EVENT.event(), event.getResourceId(), event.accepted())); chain.add(new ClusterUpgradeTriggerEvent(CLUSTER_UPGRADE_INIT_EVENT.event(), event.getResourceId(), event.accepted(), event.getImageChangeDto().getImageId())); chain.add(new StackImageUpdateTriggerEvent(FlowChainTriggers.STACK_IMAGE_UPDATE_TRIGGER_EVENT, event.getImageChangeDto())); if (event.isReplaceVms()) { LOGGER.warn("Replace VMs for DistroX is not implemented!"); } return chain; }
Source:
private void addCpuPinning(final String compatibilityVersion) { final String cpuPinning = vm.getCpuPinning(); if (cpuPinning != null && !cpuPinning.isEmpty() && Boolean.TRUE.equals(Config.<Boolean> GetValue(ConfigValues.CpuPinningEnabled, compatibilityVersion)) && cpuPinning != null) { final XmlRpcStruct pinDict = new XmlRpcStruct(); for (String pin : cpuPinning.split("_")) { final String[] split = pin.split("#"); pinDict.add(split[0], split[1]); } createInfo.add(VdsProperties.cpuPinning, pinDict); } }

Target:
private void addCpuPinning(final String compatibilityVersion) { final String cpuPinning = vm.getCpuPinning(); if (!StringUtils.isEmpty(cpuPinning) && Boolean.TRUE.equals(Config.<Boolean> GetValue(ConfigValues.CpuPinningEnabled, compatibilityVersion)) && cpuPinning != null) { final XmlRpcStruct pinDict = new XmlRpcStruct(); for (String pin : cpuPinning.split("_")) { final String[] split = pin.split("#"); pinDict.add(split[0], split[1]); } createInfo.add(VdsProperties.cpuPinning, pinDict); } }
Source:
public void testTreeHasherWith1MBPayload() throws IOException { TreeHash th = TreeHash.Hasher.buildTreeHashFromPayload(new ByteSourcePayload(getData(1 * MB))); assertEquals(th.getLinearHash().toString(), "9bc1b2a288b26af7257a36277ae3816a7d4f16e89c1e7e77d0a5c48bad62b360"); assertEquals(th.getTreeHash().toString(), "9bc1b2a288b26af7257a36277ae3816a7d4f16e89c1e7e77d0a5c48bad62b360"); }

Target:
public void testTreeHasherWith1MBPayload() throws IOException { TreeHash th = TreeHash.Hasher.buildTreeHashFromPayload(new ByteSourcePayload(getData(1 * MB))); assertEquals(th.getLinearHash(), HashCode.fromString("9bc1b2a288b26af7257a36277ae3816a7d4f16e89c1e7e77d0a5c48bad62b360")); assertEquals(th.getTreeHash(), HashCode.fromString("9bc1b2a288b26af7257a36277ae3816a7d4f16e89c1e7e77d0a5c48bad62b360")); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); layersShown = false; usePolygon = false; Mapbox.getInstance(this, getString(R.string.access_token)); setContentView(R.layout.activity_isochrone); mapView = findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(@NonNull final MapboxMap mapboxMap) { IsochroneActivity.this.mapboxMap = mapboxMap; mapboxMap.setStyle(Style.LIGHT, new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { mapboxMap.addOnMapClickListener(IsochroneActivity.this); initIsochroneCenterSymbolLayer(); findViewById(R.id.switch_isochrone_style_fab).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { usePolygon = !usePolygon; redrawIsochroneData(lastSelectedLatLng); } }); Toast.makeText(IsochroneActivity.this, getString(R.string.click_on_map_instruction), Toast.LENGTH_SHORT).show(); } }); } }); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); layersShown = false; usePolygon = false; Mapbox.getInstance(this, getString(R.string.access_token)); setContentView(R.layout.activity_isochrone); mapView = findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(@NonNull final MapboxMap mapboxMap) { IsochroneActivity.this.mapboxMap = mapboxMap; mapboxMap.setStyle(Style.LIGHT, new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull final Style style) { mapboxMap.addOnMapClickListener(IsochroneActivity.this); initIsochroneCenterSymbolLayer(style); findViewById(R.id.switch_isochrone_style_fab).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { usePolygon = !usePolygon; redrawIsochroneData(style, lastSelectedLatLng); } }); Toast.makeText(IsochroneActivity.this, getString(R.string.click_on_map_instruction), Toast.LENGTH_SHORT).show(); } }); } }); }
Source:
protected <T extends AnkiActivity> T startActivityNormallyOpenCollectionWithIntent(Class<T> clazz, Intent i) { ActivityController multimediaController = Robolectric.buildActivity(clazz, i) .create().start().resume().visible(); return (T) multimediaController.get(); }

Target:
protected <T extends AnkiActivity> T startActivityNormallyOpenCollectionWithIntent(Class<T> clazz, Intent i) { ActivityController controller = Robolectric.buildActivity(clazz, i) .create().start().resume().visible(); return (T) controller.get(); }