auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private AsyncJobStatus buildJobStatus(JobBuilder builder) { if (builder == null) { throw new IllegalArgumentException("job builder is null"); } AsyncJobStatus job = new AsyncJobStatus(); job.setJobClass(builder.getJobClass()); job.setName(builder.getJobName()); job.setGroup(builder.getJobGroup()); job.setOrigin(Util.getHostname()); job.setCorrelationId((String) MDC.get(LoggingFilter.CSID)); Principal principal = this.principalProvider.get(); job.setPrincipal(principal != null ? principal.getName() : null); job.setMaxAttempts(builder.getRetryCount() + 1); job.setJobData(builder.getTaskArguments()); return job; }

Target:
private AsyncJobStatus buildJobStatus(JobBuilder builder) { if (builder == null) { throw new IllegalArgumentException("job builder is null"); } AsyncJobStatus job = new AsyncJobStatus(); job.setJobKey(builder.getJobKey()); job.setName(builder.getJobName()); job.setGroup(builder.getJobGroup()); job.setOrigin(Util.getHostname()); job.setCorrelationId((String) MDC.get(LoggingFilter.CSID)); Principal principal = this.principalProvider.get(); job.setPrincipal(principal != null ? principal.getName() : null); job.setMaxAttempts(builder.getRetryCount() + 1); job.setJobData(builder.getJobArguments()); return job; }
Source:
public void onCompletion(RecordMetadata md, Exception e) { if ( e != null ) { this.failedMessageCount.inc(); this.failedMessageMeter.mark(); LOGGER.error(e.getClass().getSimpleName() + " @ " + position + " -- " + key); LOGGER.error(e.getLocalizedMessage()); if ( e instanceof RecordTooLargeException ) { LOGGER.error("Considering raising max.request.size broker-side."); String kafkaFallbackTopic = this.context.getConfig().kafkaFallbackTopic; if (kafkaFallbackTopic != null) { publishFallbackTopic(kafkaFallbackTopic); } } else if (!this.context.getConfig().ignoreProducerError) { this.context.terminate(e); return; } } else { this.succeededMessageCount.inc(); this.succeededMessageMeter.mark(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("-> key:" + key + ", partition:" + md.partition() + ", offset:" + md.offset()); LOGGER.debug(" " + this.json); LOGGER.debug(" " + position); LOGGER.debug(""); } } cc.markCompleted(); }

Target:
public void onCompletion(RecordMetadata md, Exception e) { if ( e != null ) { context.failedMessageCount.inc(); context.failedMessageMeter.mark(); LOGGER.error(e.getClass().getSimpleName() + " @ " + position + " -- " + key); LOGGER.error(e.getLocalizedMessage()); boolean nonFatal = e instanceof RecordTooLargeException || context.maxwell.getConfig().ignoreProducerError; if (nonFatal) { if (context.fallbackTopic == null) { cc.markCompleted(); } else { publishFallback(md, e); } } else { context.maxwell.terminate(e); } } else { context.producedMessageCount.inc(); context.producedMessageMeter.mark(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("-> key:" + key + ", partition:" + md.partition() + ", offset:" + md.offset()); LOGGER.debug(" " + this.json); LOGGER.debug(" " + position); LOGGER.debug(""); } cc.markCompleted(); } }
Source:
public synchronized String nextValue() { try { return current = reader.readLine(); } catch(NullPointerException e) { System.err.println("NullPointerException: " + filename + ':' + current); throw e; } catch(IOException e) { throw new RuntimeException(e); } }

Target:
public synchronized String nextValue() { try { return current = reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } }
Source:
public EventType getEventTypeByTopic(final String topic, final Client client) { if (!client.getClientId().equals(securitySettings.getAdminClientId())) { throw new ForbiddenAccessException("Request is forbidden for user " + client.getClientId()); } final Optional<String> etName = timelineDbRepository.listTimelinesOrdered().stream() .filter(tl -> tl.isActive()) .filter(tl -> tl.getTopic().equals(topic)) .findFirst() .map(Timeline::getEventType); if (etName.isPresent()) { return etName.map(etn -> { try { return eventTypeRepository.findByName(etn); } catch (final NakadiException e) { throw new NakadiRuntimeException(e); } }).get(); } return eventTypeRepository.list().stream() .filter(et -> et.getTopic().equals(topic)) .findFirst() .orElseThrow(() -> new NoTopicFoundException("No topic found: " + topic)); }

Target:
public EventType getEventTypeByTopic(final String topic, final Client client) { if (!client.getClientId().equals(securitySettings.getAdminClientId())) { throw new ForbiddenAccessException("Request is forbidden for user " + client.getClientId()); } final Optional<String> etName = timelineDbRepository.listActiveTimelinesByTopic(topic) .map(Timeline::getEventType); if (etName.isPresent()) { return etName.map(etn -> { try { return eventTypeRepository.findByName(etn); } catch (final NakadiException e) { throw new NakadiRuntimeException(e); } }).get(); } return eventTypeRepository.list().stream() .filter(et -> et.getTopic().equals(topic)) .findFirst() .orElseThrow(() -> new NoTopicFoundException("No topic found: " + topic)); }
Source:
private Content content( final String path, final String ref ) throws IOException { final String name = "ref"; RtContent content = null; final JsonStructure structure = this.request.method(Request.GET) .uri().path(path).queryParam(name, ref).back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(JsonResponse.class) .json().read(); if (structure instanceof JsonObject) { content = new RtContent( this.entry.uri().queryParam(name, ref).back(), this.owner, ((JsonObject) structure).getString("path") ); } return content; }

Target:
private Content content( final String path, final String ref ) throws IOException { final String name = "ref"; RtContent content = null; final JsonStructure structure = this.request.method(Request.GET) .uri().path(path).queryParam(name, ref).back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(JsonResponse.class) .json().read(); if (JsonValue.ValueType.OBJECT.equals(structure.getValueType())) { content = new RtContent( this.entry.uri().queryParam(name, ref).back(), this.owner, ((JsonObject) structure).getString("path") ); } return content; }
Source:
public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ContextRefreshedEvent) { if (this.context.equals(((ContextRefreshedEvent) event).getApplicationContext())) { if (zkConnection.isConnected()) { registerWithZooKeeper(zkConnection.getClient()); } zkConnection.addListener(new ContainerConnectionListener()); } } else if (event instanceof EmbeddedServletContainerInitializedEvent) { this.containerAttributes.put(ContainerAttributes.PORT_KEY, String.valueOf(((EmbeddedServletContainerInitializedEvent) event).getEmbeddedServletContainer() .getPort())); containerRepository.update(new Container(containerAttributes.getId(), containerAttributes)); } }

Target:
public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ContextRefreshedEvent) { if (this.context.equals(((ContextRefreshedEvent) event).getApplicationContext())) { if (zkConnection.isConnected()) { registerWithZooKeeper(zkConnection.getClient()); } zkConnection.addListener(new ContainerConnectionListener()); } } else if (event instanceof EmbeddedServletContainerInitializedEvent) { String namespace = ((EmbeddedServletContainerInitializedEvent) event).getApplicationContext().getNamespace(); if (namespace != null && namespace.equals(MGMT_CONTEXT_NAMESPACE)) { managementPort = ((EmbeddedServletContainerInitializedEvent) event).getEmbeddedServletContainer().getPort(); this.containerAttributes.setManagementPort(String.valueOf(managementPort)); if (zkConnection.isConnected()) { containerRepository.update(new Container(containerAttributes.getId(), containerAttributes)); } } } }
Source:
public void init(ServletConfig config) throws ServletException { super.init(config); LOG.debug("InitServlet start..."); executor = Executors.newFixedThreadPool(ExecutorServiceHelper.getInstance().getExecutorPoolSize()); largeJobExecutor = Executors.newFixedThreadPool(ExecutorServiceHelper.getInstance() .getLargeJobExecutorPoolSize()); SessionFactory session = HibernateUtil.getSessionFactory(); EventLoggerFactory.getInstance().registerLoggers(); }

Target:
public void init(ServletConfig config) throws ServletException { super.init(config); executor = Executors.newFixedThreadPool(ExecutorServiceHelper.getInstance().getExecutorPoolSize()); largeJobExecutor = Executors.newFixedThreadPool(ExecutorServiceHelper.getInstance() .getLargeJobExecutorPoolSize()); HibernateUtil.getSessionFactory(); EventLoggerFactory.getInstance().registerLoggers(); }
Source:
public void testFloatRead() throws Exception { MessageType requestedSchema = parseMessageType("message test { required float float_field;}"); ParquetMetadata metadata = ParquetFileReader.readFooter(conf, file); for (BlockMetaData block : metadata.getBlocks()) { Map<ColumnDescriptor, Dictionary> result = ParquetFileReader.readDictionary(block, file, conf, requestedSchema); for (Map.Entry<ColumnDescriptor, Dictionary> entry : result.entrySet()) { Dictionary dictionary = entry.getValue(); for (int i = 0; i < ENGLISH_CHARACTER_NUMBER; i++) { assertEquals((float) intValues[i % ENGLISH_CHARACTER_NUMBER] * 2.0, dictionary.decodeToFloat(i), 1e-15); } } } }

Target:
public void testFloatRead() throws Exception { MessageType requestedSchema = parseMessageType("message test { required float float_field;}"); ParquetMetadata metadata = ParquetFileReader.readFooter(conf, file); ParquetFileReader fileReader = new ParquetFileReader(conf, metadata.getFileMetaData(), file, metadata.getBlocks(), requestedSchema.getColumns()); DictionaryPageReadStore dictionaryReadStore = fileReader.getCurrentRowGroupDictionaries(requestedSchema); ColumnDescriptor column = requestedSchema.getColumns().get(0); DictionaryReader dictionaryReader = new DictionaryReader(column, dictionaryReadStore); Dictionary dictionary = dictionaryReader.readDictionary(); for (int i = 0; i < intValues.length; i++) { assertEquals((float) intValues[i % intValues.length] * 2.0, dictionary.decodeToFloat(i), 1e-15); } fileReader.close(); }
Source:
private void init() { Composite optionPane = (Composite) this.getControl(); optionPane.setLayout(new GridLayout()); optionPane.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, true)); final SelectionListener linkedListener = new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { getBatchWizard().setLinked(((Button) e.widget).getSelection()); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }; Button fLink = new Button(optionPane, SWT.RADIO); fLink.setText(Messages.ImportTraceWizardPageScan_2); fLink.setSelection(true); fLink.setLayoutData(new GridData()); fLink.addSelectionListener(linkedListener); Button fCopy = new Button(optionPane, SWT.RADIO); fCopy.setText(Messages.ImportTraceWizardPageScan_3); fCopy.setLayoutData(new GridData()); fCopy.addSelectionListener(linkedListener); Button fOverwrite = new Button(optionPane, SWT.CHECK); fOverwrite.setText(Messages.ImportTraceWizardPageScan_4); fOverwrite.setLayoutData(new GridData()); fOverwrite.setSelection(true); fOverwrite.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { getBatchWizard().setOverwrite(((Button) e.widget).getSelection()); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); }

Target:
private void init() { Composite optionPane = (Composite) this.getControl(); optionPane.setLayout(new GridLayout()); optionPane.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, true)); final SelectionListener linkedListener = new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { getBatchWizard().setLinked(((Button) e.widget).getSelection()); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }; Button fLink = new Button(optionPane, SWT.RADIO); fLink.setText(Messages.ImportTraceWizardLinkTraces); fLink.setSelection(true); fLink.setLayoutData(new GridData()); fLink.addSelectionListener(linkedListener); Button fCopy = new Button(optionPane, SWT.RADIO); fCopy.setText(Messages.ImportTraceWizardCopyTraces); fCopy.setLayoutData(new GridData()); fCopy.addSelectionListener(linkedListener); Button fOverwrite = new Button(optionPane, SWT.CHECK); fOverwrite.setText(Messages.ImportTraceWizardOverwriteTraces); fOverwrite.setLayoutData(new GridData()); fOverwrite.setSelection(true); fOverwrite.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { getBatchWizard().setOverwrite(((Button) e.widget).getSelection()); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); }
Source:
private void readBatchHelper( int num, ColumnVector column, TypeInfo columnType, int rowId) throws IOException { switch (columnType.getCategory()) { case PRIMITIVE: PrimitiveTypeInfo primitiveColumnType = (PrimitiveTypeInfo) columnType; readBatchForPrimitiveType(num, column, primitiveColumnType, rowId); break; case LIST: break; case MAP: MapTypeInfo mapColumnType = (MapTypeInfo) columnType; MapColumnVector mapColumn = (MapColumnVector) column; readBatchHelper(num, mapColumn.keys, mapColumnType.getMapKeyTypeInfo(), rowId); readBatchHelper(num, mapColumn.values, mapColumnType.getMapKeyTypeInfo(), rowId); break; case STRUCT: StructTypeInfo structTypeInfo = (StructTypeInfo) columnType; StructColumnVector structColumn = (StructColumnVector) column; List<TypeInfo> typeInfos = structTypeInfo.getAllStructFieldTypeInfos(); for (int i = 0; i < typeInfos.size(); i++) { readBatch(num, structColumn.fields[i], typeInfos.get(i)); } break; case UNION: break; default: throw new IOException("Unsupported category " + columnType.getCategory().name()); } }

Target:
private void readBatchHelper( int num, ColumnVector column, TypeInfo columnType, int rowId) throws IOException { PrimitiveTypeInfo primitiveColumnType = (PrimitiveTypeInfo) columnType; switch (primitiveColumnType.getPrimitiveCategory()) { case INT: case BYTE: case SHORT: readIntegers(num, (LongColumnVector) column, rowId); break; case DATE: case INTERVAL_YEAR_MONTH: case LONG: readLongs(num, (LongColumnVector) column, rowId); break; case BOOLEAN: readBooleans(num, (LongColumnVector) column, rowId); break; case DOUBLE: readDoubles(num, (DoubleColumnVector) column, rowId); break; case BINARY: case STRING: case CHAR: case VARCHAR: readBinaries(num, (BytesColumnVector) column, rowId); break; case FLOAT: readFloats(num, (DoubleColumnVector) column, rowId); break; case DECIMAL: readDecimal(num, (DecimalColumnVector) column, rowId); break; case INTERVAL_DAY_TIME: case TIMESTAMP: default: throw new IOException("Unsupported type: " + type); } }
Source:
protected static KeyManagerFactory buildKeyManagerFactory(File certChainFile, File keyFile, String keyPassword, KeyManagerFactory kmf) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException, CertificateException, KeyException, IOException { String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm"); if (algorithm == null) { algorithm = "SunX509"; } return buildKeyManagerFactory(certChainFile, algorithm, keyFile, keyPassword, kmf, KeyStore.getDefaultType()); }

Target:
protected static KeyManagerFactory buildKeyManagerFactory(File certChainFile, File keyFile, String keyPassword, KeyManagerFactory kmf) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException, CertificateException, KeyException, IOException { return buildKeyManagerFactory(certChainFile, keyFile, keyPassword, kmf, KeyStore.getDefaultType()); }
Source:
public BigtableTable(AbstractBigtableConnection bigtableConnection, TableName tableName, BigtableOptions options, BigtableDataClient client, ExecutorService executorService) { this.bigtableConnection = bigtableConnection; this.tableName = tableName; this.options = options; this.client = client; putAdapter = new PutAdapter(getConfiguration().getInt("hbase.client.keyvalue.maxsize", -1)); mutationAdapter = Adapters.createMutationsAdapter(putAdapter); rowMutationsAdapter = new RowMutationsAdapter(mutationAdapter); this.executorService = MoreExecutors.listeningDecorator(executorService); this.bigtableTableName = options.getClusterName().toTableName(tableName.getNameAsString()); this.batchExecutor = new BatchExecutor( client, options, this.bigtableTableName, this.executorService, putAdapter, rowMutationsAdapter); }

Target:
public BigtableTable(AbstractBigtableConnection bigtableConnection, TableName tableName, BigtableOptions options, BigtableDataClient client, ExecutorService executorService) { this.bigtableConnection = bigtableConnection; this.tableName = tableName; this.options = options; this.client = client; putAdapter = Adapters.createPutAdapter(getConfiguration()); mutationAdapter = Adapters.createMutationsAdapter(putAdapter); rowMutationsAdapter = new RowMutationsAdapter(mutationAdapter); this.executorService = MoreExecutors.listeningDecorator(executorService); this.bigtableTableName = options.getClusterName().toTableName(tableName.getNameAsString()); this.batchExecutor = new BatchExecutor( client, options, this.bigtableTableName, this.executorService, putAdapter, rowMutationsAdapter); }
Source:
public void startProvisioning(ProvisioningConfiguration req) { if (!req.isValid()) { doImmediateProvisioningFailure(IpManagerEvent.ERROR_INVALID_PROVISIONING); return; } final ScanResultInfo scanResultInfo = req.mScanResultInfo; mLastBssid = scanResultInfo != null ? MacAddress.fromString(scanResultInfo.getBssid()) : null; sendMessage(CMD_START, new android.net.shared.ProvisioningConfiguration(req)); }

Target:
public void startProvisioning(ProvisioningConfiguration req) { if (!req.isValid()) { doImmediateProvisioningFailure(IpManagerEvent.ERROR_INVALID_PROVISIONING); return; } final ScanResultInfo scanResultInfo = req.mScanResultInfo; mCurrentBssid = null; if (scanResultInfo != null) { try { mCurrentBssid = MacAddress.fromString(scanResultInfo.getBssid()); } catch (IllegalArgumentException e) { Log.wtf(mTag, "Invalid BSSID: " + scanResultInfo.getBssid() + " in provisioning configuration", e); } } sendMessage(CMD_START, new android.net.shared.ProvisioningConfiguration(req)); }
Source:
private void doubleBuffer(int wanted) { int bufferLength = buffer.length * 2; while (bufferLength < wanted) { bufferLength *= 2; } byte[] buf = new byte[bufferLength]; moveBufferTo(buf); buffer = buf; }

Target:
private void doubleBuffer(int wanted) { final int bufferLength = Integer.highestOneBit(wanted) << 1; final byte[] buf = new byte[bufferLength]; moveBufferTo(buf); buffer = buf; }
Source:
protected Collection<Integer> translateForStreamingInternal( final BroadcastStateTransformation<IN1, IN2, OUT> transformation, final Context context) { checkNotNull(transformation); checkNotNull(context); CoBroadcastWithNonKeyedOperator<IN1, IN2, OUT> operator = new CoBroadcastWithNonKeyedOperator<>( transformation.getUserFunction(), transformation.getBroadcastStateDescriptors()); return translateInternal( transformation, transformation.getNonBroadcastStream(), transformation.getBroadcastStream(), SimpleOperatorFactory.of(operator), null , null , null , context); }

Target:
protected Collection<Integer> translateForStreamingInternal( final BroadcastStateTransformation<IN1, IN2, OUT> transformation, final Context context) { checkNotNull(transformation); checkNotNull(context); CoBroadcastWithNonKeyedOperator<IN1, IN2, OUT> operator = new CoBroadcastWithNonKeyedOperator<>( transformation.getUserFunction(), transformation.getBroadcastStateDescriptors()); return translateInternal( transformation, transformation.getRegularInput(), transformation.getBroadcastInput(), SimpleOperatorFactory.of(operator), null , null , null , context); }
Source:
public static ArchivedExecutionGraph createFromInitializingJob( JobID jobId, String jobName, JobStatus jobStatus, @Nullable Throwable throwable, long initializationTimestamp) { long failureTime = System.currentTimeMillis(); Map<JobVertexID, ArchivedExecutionJobVertex> archivedTasks = Collections.emptyMap(); List<ArchivedExecutionJobVertex> archivedVerticesInCreationOrder = Collections.emptyList(); final Map<String, SerializedValue<OptionalFailure<Object>>> serializedUserAccumulators = Collections.emptyMap(); StringifiedAccumulatorResult[] archivedUserAccumulators = new StringifiedAccumulatorResult[]{}; final long[] timestamps = new long[JobStatus.values().length]; timestamps[JobStatus.INITIALIZING.ordinal()] = initializationTimestamp; String jsonPlan = "{}"; ErrorInfo failureInfo = null; if (throwable != null) { Preconditions.checkState(jobStatus == JobStatus.FAILED); failureInfo = new ErrorInfo(throwable, failureTime); timestamps[JobStatus.FAILED.ordinal()] = failureTime; } return new ArchivedExecutionGraph( jobId, jobName, archivedTasks, archivedVerticesInCreationOrder, timestamps, jobStatus, failureInfo, jsonPlan, archivedUserAccumulators, serializedUserAccumulators, new ExecutionConfig().archive(), false, null, null, null); }

Target:
public static ArchivedExecutionGraph createFromInitializingJob( JobID jobId, String jobName, JobStatus jobStatus, @Nullable Throwable throwable, long initializationTimestamp) { Map<JobVertexID, ArchivedExecutionJobVertex> archivedTasks = Collections.emptyMap(); List<ArchivedExecutionJobVertex> archivedVerticesInCreationOrder = Collections.emptyList(); final Map<String, SerializedValue<OptionalFailure<Object>>> serializedUserAccumulators = Collections.emptyMap(); StringifiedAccumulatorResult[] archivedUserAccumulators = new StringifiedAccumulatorResult[]{}; final long[] timestamps = new long[JobStatus.values().length]; timestamps[JobStatus.INITIALIZING.ordinal()] = initializationTimestamp; String jsonPlan = "{}"; ErrorInfo failureInfo = null; if (throwable != null) { Preconditions.checkState(jobStatus == JobStatus.FAILED); long failureTime = System.currentTimeMillis(); failureInfo = new ErrorInfo(throwable, failureTime); timestamps[JobStatus.FAILED.ordinal()] = failureTime; } return new ArchivedExecutionGraph( jobId, jobName, archivedTasks, archivedVerticesInCreationOrder, timestamps, jobStatus, failureInfo, jsonPlan, archivedUserAccumulators, serializedUserAccumulators, new ExecutionConfig().archive(), false, null, null, null); }
Source:
public void stopNoteExecution(String noteId, ServiceContext context, ServiceCallback<Note> callback) throws IOException { if (!checkPermission(noteId, Permission.RUNNER, Message.OP.STOP_NOTE_EXECUTION, context, callback)) { return; } Note note = notebook.getNote(noteId); if (note == null) { callback.onFailure(new NoteNotFoundException(noteId), context); return; } for (Paragraph paragraph : note.getParagraphs()) { if (paragraph.isRunning()) { paragraph.abort(); break; } } callback.onSuccess(note, context); }

Target:
public void stopNoteExecution(String noteId, ServiceContext context, ServiceCallback<Note> callback) throws IOException { if (!checkPermission(noteId, Permission.RUNNER, Message.OP.STOP_NOTE_EXECUTION, context, callback)) { return; } Note note = notebook.getNote(noteId); if (note == null) { callback.onFailure(new NoteNotFoundException(noteId), context); return; } note.abortExecution(); for (Paragraph paragraph : note.getParagraphs()) { if (paragraph.isRunning()) { paragraph.abort(); break; } } callback.onSuccess(note, context); }
Source:
protected List<JsonObject> runYoutubeDL(CrawlURI uri) { ProcessBuilder pb = new ProcessBuilder("youtube-dl", "--ignore-config", "--simulate", "--dump-json", "--format=best", uri.toString()); logger.fine("running " + pb.command()); Process proc = null; try { proc = pb.start(); } catch (IOException e) { logger.log(Level.WARNING, "youtube-dl failed " + pb.command(), e); return (List<JsonObject>) Collections.EMPTY_LIST; } String stdout = null; String stderr = null; try { stdout = readToEnd( new InputStreamReader(proc.getInputStream(), "UTF-8")); stderr = readToEnd( new InputStreamReader(proc.getErrorStream(), "UTF-8")); } catch (IOException e) { logger.log(Level.WARNING, "problem reading output from youtube-dl " + pb.command(), e); return (List<JsonObject>) Collections.EMPTY_LIST; } try { if (proc.waitFor() != 0) { logger.fine("youtube-dl exited with status " + proc.waitFor() + " " + pb.command() + "\n=== stdout ===\n" + stdout + "\n=== stderr ===\n" + stderr); return (List<JsonObject>) Collections.EMPTY_LIST; } } catch (InterruptedException e) { proc.destroyForcibly(); } ArrayList<JsonObject> ydlJsons = new ArrayList<JsonObject>(); JsonStreamParser parser = new JsonStreamParser(stdout); try { while (parser.hasNext()) { ydlJsons.add((JsonObject) parser.next()); } } catch (JsonParseException e) { logger.log(Level.FINE, "problem parsing json from youtube-dl " + pb.command() + "\n=== stdout ===\n" + stdout + "\n=== stderr ===\n" + stderr, e); return (List<JsonObject>) Collections.EMPTY_LIST; } return ydlJsons; }

Target:
protected List<JsonObject> runYoutubeDL(CrawlURI uri) { ProcessBuilder pb = new ProcessBuilder("youtube-dl", "--ignore-config", "--simulate", "--dump-json", "--format=best", uri.toString()); logger.fine("running " + pb.command()); Process proc = null; try { proc = pb.start(); } catch (IOException e) { logger.log(Level.WARNING, "youtube-dl failed " + pb.command(), e); return null; } ProcessOutput output; try { output = readOutput(proc); } catch (IOException e) { logger.log(Level.WARNING, "problem reading output from youtube-dl " + pb.command(), e); return null; } try { if (proc.waitFor() != 0) { logger.fine("youtube-dl exited with status " + proc.waitFor() + " " + pb.command() + "\n=== stdout ===\n" + output.stdout + "\n=== stderr ===\n" + output.stderr); return null; } } catch (InterruptedException e) { proc.destroyForcibly(); } List<JsonObject> ydlJsons = new ArrayList<JsonObject>(); JsonStreamParser parser = new JsonStreamParser(output.stdout); try { while (parser.hasNext()) { ydlJsons.add((JsonObject) parser.next()); } } catch (JsonParseException e) { logger.log(Level.FINE, "problem parsing json from youtube-dl " + pb.command() + "\n=== stdout ===\n" + output.stdout + "\n=== stderr ===\n" + output.stderr, e); return null; } return ydlJsons; }
Source:
private int getCreditsToAdd(int linkCredits) { final CoreSubscriber<? super Message> subscriber = downstream.get(); final long r = requested; final boolean hasBackpressure = r != Long.MAX_VALUE; if (subscriber == null || r == 0) { logger.info("Not adding credits. No downstream subscribers or items requested."); return 0; } final int creditsToAdd; final int expectedTotalCredit; if (prefetch == 0) { if (r <= Integer.MAX_VALUE) { expectedTotalCredit = (int) r; } else { expectedTotalCredit = Integer.MAX_VALUE; } } else { expectedTotalCredit = prefetch; } synchronized (queueLock) { final int queuedMessages = pendingMessages.get(); final int pending = queuedMessages + linkCredits; if (hasBackpressure) { creditsToAdd = Math.max(expectedTotalCredit - pending, 0); } else { creditsToAdd = minimumNumberOfMessages >= queuedMessages ? Math.max(expectedTotalCredit - pending, 0) : 0; } } return creditsToAdd; }

Target:
private int getCreditsToAdd(int linkCredits) { final CoreSubscriber<? super Message> subscriber = downstream.get(); final long r = requested; final boolean hasBackpressure = r != Long.MAX_VALUE; if (subscriber == null || r == 0) { logger.info("Not adding credits. No downstream subscribers or items requested."); return 0; } final int creditsToAdd; final int expectedTotalCredit; if (prefetch == 0) { if (r <= Integer.MAX_VALUE) { expectedTotalCredit = (int) r; } else { expectedTotalCredit = Integer.MAX_VALUE; } } else { expectedTotalCredit = prefetch; } logger.info("linkCredits: '{}', expectedTotalCredit: '{}'", linkCredits, expectedTotalCredit); synchronized (queueLock) { final int queuedMessages = pendingMessages.get(); final int pending = queuedMessages + linkCredits; if (hasBackpressure) { creditsToAdd = Math.max(expectedTotalCredit - pending, 0); } else { creditsToAdd = minimumNumberOfMessages >= queuedMessages ? Math.max(expectedTotalCredit - pending, 0) : 0; } logger.info("prefetch: '{}', requested: '{}', linkCredits: '{}', expectedTotalCredit: '{}', queuedMessages:" + "'{}', creditsToAdd: '{}', messageQueue.size(): '{}'", getPrefetch(), r, linkCredits, expectedTotalCredit, queuedMessages, creditsToAdd, messageQueue.size()); } return creditsToAdd; }
Source:
public Graph load(StageIdentifier stageIdentifier, TempGraphFactory tempGraphFactory, final XSLTTransformerRegistry transformerRegistry) throws GoIntegrationException { LOGGER.debug("Attempting to import stage with url <" + stageIdentifier + "> !"); long importStartingTime = System.currentTimeMillis(); try { Stage stage = stageFinder.findStageWithIdentifier(stageIdentifier); String baseUri = "https://localhost:8154/go"; Graph graph = loadIsolatedStageGraph(stageIdentifier, tempGraphFactory, transformerRegistry, stage, baseUri); importPipeline(pipelineInstanceLoader.loadPipelineForShine(stage.getPipelineId()), graph, transformerRegistry, baseUri); importJobs(graph, transformerRegistry, stage, baseUri); return graph; } finally { LOGGER.debug("Done importing stage with url <" + stageIdentifier + "> with " + (System.currentTimeMillis() - importStartingTime) + " ms!"); } }

Target:
public Graph load(StageIdentifier stageIdentifier, TempGraphFactory tempGraphFactory, final XSLTTransformerRegistry transformerRegistry) throws GoIntegrationException { LOGGER.debug("Attempting to import stage with url <{}> !", stageIdentifier); long importStartingTime = System.currentTimeMillis(); try { Stage stage = stageFinder.findStageWithIdentifier(stageIdentifier); String baseUri = "https://localhost:8154/go"; Graph graph = loadIsolatedStageGraph(stageIdentifier, tempGraphFactory, transformerRegistry, stage, baseUri); importPipeline(pipelineInstanceLoader.loadPipelineForShine(stage.getPipelineId()), graph, transformerRegistry, baseUri); importJobs(graph, transformerRegistry, stage, baseUri); return graph; } finally { LOGGER.debug("Done importing stage with url <{}> with ms!", stageIdentifier, System.currentTimeMillis() - importStartingTime); } }
Source:
private void checkProcStatistics(Client client) throws NoConnectionsException, IOException, ProcCallException { VoltTable vt; vt = client.callProcedure("@Statistics", "PROCEDUREPROFILE", 1).getResults()[0]; System.out.println(vt.toString()); }

Target:
private void checkProcStatistics(Client client) throws NoConnectionsException, IOException, ProcCallException { VoltTable vt; vt = client.callProcedure("@Statistics", "PROCEDUREPROFILE", 1).getResults()[0]; }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { Connection connection = null; IProject project = null; ISelection selection = HandlerUtil.getCurrentSelection(event); final IDockerImage image = UIUtils.getFirstElement(selection, IDockerImage.class); if (image == null || OpenShiftUIUtils.hasOpenShiftExplorerSelection()) { project = ResourceUtils.getProject(UIUtils.getFirstElement(selection, IResource.class)); if(project != null) { connection = ConnectionsRegistryUtil.getConnectionFor(project); } else { connection = UIUtils.getFirstElement(selection, Connection.class); } } if(connection == null) { connection = OpenShiftUIUtils.getExplorerDefaultConnection(Connection.class); } runWizard(HandlerUtil.getActiveWorkbenchWindow(event).getShell(), image, project,connection); return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { Connection connection = null; IProject project = null; ISelection selection = HandlerUtil.getCurrentSelection(event); final IDockerImage image = UIUtils.getFirstElement(selection, IDockerImage.class); if (image == null || OpenShiftUIUtils.hasOpenShiftExplorerSelection()) { selection = OpenShiftUIUtils.getOpenShiftExplorerSelection(); project = ResourceUtils.getProject(UIUtils.getFirstElement(selection, IResource.class)); if(project != null) { connection = ConnectionsRegistryUtil.getConnectionFor(project); } else { connection = UIUtils.getFirstElement(selection, Connection.class); } } if(connection == null) { connection = OpenShiftUIUtils.getExplorerDefaultConnection(Connection.class); } runWizard(HandlerUtil.getActiveWorkbenchWindow(event).getShell(), image, project,connection); return null; }
Source:
private void syncUsers(Collection<ServiceAccount> serviceAccounts) { if (!fiatClientConfigurationProperties.isEnabled() || !fiatService.isPresent() || serviceAccounts == null || !fiatConfigurationProperties.getRoleSync().isEnabled()) { return; } try { List<String> rolesToSync = serviceAccounts.stream() .map(sa -> sa.getMemberOf()) .flatMap(Collection::stream) .distinct() .collect(Collectors.toList()); fiatService.get().sync(rolesToSync); log.debug("Synced users with roles: ", rolesToSync); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null) fiatPermissionEvaluator.invalidatePermission((String) auth.getPrincipal()); } catch (RetrofitError re) { log.warn("Error syncing users", re); } }

Target:
private void syncUsers(Collection<ServiceAccount> serviceAccounts) { if (!fiatClientConfigurationProperties.isEnabled() || !fiatService.isPresent() || serviceAccounts == null || !fiatConfigurationProperties.getRoleSync().isEnabled()) { return; } try { List<String> rolesToSync = serviceAccounts.stream() .map(sa -> sa.getMemberOf()) .flatMap(Collection::stream) .distinct() .collect(Collectors.toList()); fiatService.get().sync(rolesToSync); log.debug("Synced users with roles: {}", rolesToSync); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null) { fiatPermissionEvaluator.invalidatePermission((String) auth.getPrincipal()); } } catch (RetrofitError re) { log.warn("Error syncing users", re); } }
Source:
public void signUpWithIntentToParticipate() throws Exception { String email = TestUtils.makeRandomTestEmail(AuthenticationServiceTest.class); StudyParticipant participant = new StudyParticipant.Builder() .withEmail(email) .withPassword("P@ssword`1").build(); IdentifierHolder holder = null; try { IntentToParticipate intent = new IntentToParticipate.Builder() .withScope(SharingScope.NO_SHARING) .withPhone(TestConstants.PHONE) .withStudy(TestConstants.TEST_STUDY_IDENTIFIER) .withOsName(OperatingSystem.ANDROID) .withConsentSignature(new ConsentSignature.Builder() .withName("Name") .withBirthdate("1970-01-01").build()) .withSubpopGuid(TestConstants.TEST_STUDY_IDENTIFIER).build(); intentService.submitIntentToParticipate(intent); study.setEmailVerificationEnabled(false); holder = authService.signUp(study, participant, true); CriteriaContext context = new CriteriaContext.Builder() .withStudyIdentifier(TestConstants.TEST_STUDY) .build(); SignIn signIn = new SignIn.Builder().withStudy(TestConstants.TEST_STUDY_IDENTIFIER).withEmail(email) .withPassword("P@ssword`1").build(); authService.signIn(study, context, signIn); } finally { if (holder != null) { userAdminService.deleteUser(study, holder.getIdentifier()); } } }

Target:
public void signUpWithIntentToParticipate() throws Exception { String email = TestUtils.makeRandomTestEmail(AuthenticationServiceTest.class); StudyParticipant participant = new StudyParticipant.Builder() .withPhone(TestConstants.PHONE) .withEmail(email) .withPassword(PASSWORD).build(); IdentifierHolder holder = null; try { IntentToParticipate intent = new IntentToParticipate.Builder() .withScope(SharingScope.NO_SHARING) .withPhone(TestConstants.PHONE) .withStudyId(TestConstants.TEST_STUDY_IDENTIFIER) .withOsName(OperatingSystem.ANDROID) .withConsentSignature(new ConsentSignature.Builder() .withName("Name") .withBirthdate("1970-01-01").build()) .withSubpopGuid(TestConstants.TEST_STUDY_IDENTIFIER).build(); intentService.submitIntentToParticipate(intent); study.setEmailVerificationEnabled(false); holder = authService.signUp(study, participant, true); CriteriaContext context = new CriteriaContext.Builder() .withStudyIdentifier(TestConstants.TEST_STUDY) .build(); SignIn signIn = new SignIn.Builder().withStudy(TestConstants.TEST_STUDY_IDENTIFIER) .withEmail(email).withPassword(PASSWORD).build(); authService.signIn(study, context, signIn); } finally { if (holder != null) { userAdminService.deleteUser(study, holder.getIdentifier()); } } }
Source:
public HttpResponse addDocument(String apiName, String version, String provider, String docName, String docType, String sourceType, String docUrl, String summary, String docLocation) throws APIManagerIntegrationTestException { try { checkAuthentication(); return HttpRequestUtil.doPost(new URL(backEndUrl + "/publisher/site/blocks/documentation/ajax/docs.jag") , "action=addDocumentation&provider=" + provider + "&apiName=" + apiName + "&version=" + version + "&docName=" + docName + "&docType=" + docType + "&sourceType=" + sourceType + "&docUrl" + docUrl + "=&summary=" + summary + "&docLocation=" + docLocation, requestHeaders); } catch (Exception e) { throw new APIManagerIntegrationTestException("Exception when Adding document to a API", e); } }

Target:
public HttpResponse addDocument(String apiName, String version, String provider, String docName, String docType, String sourceType, String docUrl, String summary, String docLocation) throws APIManagerIntegrationTestException { try { checkAuthentication(); return HttpRequestUtil.doPost( new URL(backendURL + "/publisher/site/blocks/documentation/ajax/docs.jag"), "action=addDocumentation&provider=" + provider + "&apiName=" + apiName + "&version=" + version + "&docName=" + docName + "&docType=" + docType + "&sourceType=" + sourceType + "&docUrl" + docUrl + "=&summary=" + summary + "&docLocation=" + docLocation, requestHeaders); } catch (Exception e) { throw new APIManagerIntegrationTestException("Exception when Adding document to a API", e); } }
Source:
public void shouldFailAStripeNotificationWithAnUnexpectedContentType() throws Exception { String transactionId = randomId(); createNewChargeWith(AUTHORISATION_SUCCESS, transactionId); given() .port(testContext.getPort()) .body("") .contentType(TEXT_XML) .post(NOTIFICATION_PATH) .then() .statusCode(415); }

Target:
public void shouldFailAStripeNotificationWithAnUnexpectedContentType() { String transactionId = randomId(); createNewChargeWith(AUTHORISATION_SUCCESS, transactionId); given() .port(testContext.getPort()) .body("") .contentType(TEXT_XML) .post(NOTIFICATION_PATH) .then() .statusCode(415); }
Source:
public void testLogReturnDoesntLogWhenLogLevelInactive() throws Exception { Log log = mock(Log.class); when(log.isDebugEnabled()).thenReturn(false); LoggedUtils.logReturn(log, "", new LoggedOverridingSubclass(), new Object()); }

Target:
public void testLogReturnDoesntLogWhenLogLevelInactive() throws Exception { Log log = mock(Log.class); LoggedUtils.logReturn(log, "", new LoggedOverridingSubclass(), new Object()); verify(log, never()).traceFormat(any(String.class), any()); verify(log, never()).debugFormat(any(String.class), any()); verify(log, never()).infoFormat(any(String.class), any()); verify(log, never()).warnFormat(any(String.class), any()); verify(log, never()).errorFormat(any(String.class), any()); verify(log, never()).fatalFormat(any(String.class), any()); }
Source:
protected void render0(FunctionRenderContext context) { Object[] jsonPathElements = new Object[context.getArgumentsSize() - 1]; for (int i = 1; i < context.getArgumentsSize(); i++) { try { jsonPathElements[i - 1] = Integer.parseInt(JpqlFunctionUtil.unquoteSingleQuotes(context.getArgument(i))); } catch (NumberFormatException e) { jsonPathElements[i - 1] = JpqlFunctionUtil.unquoteDoubleQuotes(JpqlFunctionUtil.unquoteSingleQuotes(context.getArgument(i))); } } String jsonPath = toJsonPath(jsonPathElements, jsonPathElements.length, true); context.addChunk("coalesce(json_value("); context.addArgument(0); context.addChunk(" format json,'"); context.addChunk(jsonPath); context.addChunk("'),json_query("); context.addArgument(0); context.addChunk(" format json,'"); context.addChunk(jsonPath); context.addChunk("'))"); }

Target:
protected void render0(FunctionRenderContext context) { List<Object> jsonPathElements = AbstractJsonGetFunction.retrieveJsonPathElements(context, 1); String jsonPath = toJsonPath(jsonPathElements, jsonPathElements.size(), true); context.addChunk("coalesce(json_value("); context.addArgument(0); context.addChunk(" format json,'"); context.addChunk(jsonPath); context.addChunk("'),json_query("); context.addArgument(0); context.addChunk(" format json,'"); context.addChunk(jsonPath); context.addChunk("'))"); }
Source:
private void populateOptions(Configuration configuration) { batchAccount = configuration.getExecution().getOptions().get("batchAccount"); batchKey = configuration.getExecution().getOptions().get("batchKey"); batchUri = configuration.getExecution().getOptions().get("batchUri"); batchServicePoolId = configuration.getExecution().getOptions().get("batchServicePoolId"); dockerImageName = configuration.getExecution().getOptions().get("dockerImageName"); dockerArgs = configuration.getExecution().getOptions().get("dockerArgs"); }

Target:
private void populateOptions(Configuration configuration) { batchAccount = configuration.getExecution().getOptions().get(BATCH_ACCOUNT); batchKey = configuration.getExecution().getOptions().get(BATCH_KEY); batchUri = configuration.getExecution().getOptions().get(BATCH_URI); batchPoolId = configuration.getExecution().getOptions().get(BATCH_POOL_ID); dockerImageName = configuration.getExecution().getOptions().get(DOCKER_IMAGE_NAME); dockerArgs = configuration.getExecution().getOptions().get(DOCKER_ARGS); }
Source:
private Optional<String> getGraphUUID() { final Diagram diagram = getDiagram(); if (Objects.isNull(diagram)) { return Optional.empty(); } final Graph graph = diagram.getGraph(); if (Objects.isNull(graph)) { return Optional.empty(); } return Optional.of(graph.getUUID()); }

Target:
private Optional<String> getGraphUUID() { if (Objects.isNull(getGraph())) { return Optional.empty(); } return Optional.of(getGraph().getUUID()); }
Source:
public static float parseDistance(final String distanceText, final DistanceUnit unit) throws NumberFormatException { return convertDistance(Float.parseFloat(distanceText), unit); }

Target:
public static float parseDistance(final String distanceText, final DistanceUnit unit) throws NumberFormatException { return convertDistance(Float.parseFloat(distanceText.replace(',', '.')), unit); }
Source:
public static boolean compareCurrentPatients(Object patient1, Object patient2) { Patient p1 = (Patient) patient1; Patient p2 = (Patient) patient2; if (p1.getIdentifier().size() == p2.getIdentifier().size()) { for (int i = 0; i < p1.getIdentifier().size(); i++) { if (!p1.getIdentifier().get(i).equalsDeep(p2.getIdentifier().get(i))) { return false; } } } if (p1.getName().size() > 0 && p2.getName().size() > 0) { if (!p1.getName().get(0).equalsDeep(p2.getName().get(0))) { return false; } } if (p1.getTelecom().size() > 0 && p2.getTelecom().size() > 0) { if (!p1.getTelecom().get(0).equalsDeep(p2.getTelecom().get(0))) { return false; } } if (null != p1.getGender()) { if (!p1.getGender().equals(p2.getGender())) { return false; } } if (null != p1.getDeceased()) { if (!p1.getDeceased().equalsDeep(p2.getDeceased())) { return false; } } if (p1.getAddress().size() > 0 && p2.getAddress().size() > 0) { if (!p1.getAddress().get(0).equalsDeep(p2.getAddress().get(0))) { return false; } } if (null != p1.getMaritalStatus()) { if (!p1.getMaritalStatus().equalsDeep(p2.getMaritalStatus())) { return false; } } if (null != p1.getMultipleBirth()) { if (!p1.getMultipleBirth().equalsDeep(p2.getMultipleBirth())) { return false; } } if (null != p1.getGeneralPractitioner()) { if (!p1.getGeneralPractitioner().equals(p2.getGeneralPractitioner())) { return false; } } return p1.getActive() == p2.getActive(); }

Target:
public static boolean compareCurrentPatients(Object patient1, Object patient2) { Patient p1 = (Patient) patient1; Patient p2 = (Patient) patient2; if (p1.getIdentifier().size() == p2.getIdentifier().size()) { for (int i = 0; i < p1.getIdentifier().size(); i++) { if (!p1.getIdentifier().get(i).equalsDeep(p2.getIdentifier().get(i))) { return false; } } } else { return false; } if (p1.getName().size() > 0 && p2.getName().size() > 0) { if (!p1.getName().get(0).equalsDeep(p2.getName().get(0))) { return false; } } if (p1.getTelecom().size() > 0 && p2.getTelecom().size() > 0) { if (!p1.getTelecom().get(0).equalsDeep(p2.getTelecom().get(0))) { return false; } } if (null != p1.getGender()) { if (!p1.getGender().equals(p2.getGender())) { return false; } } if (null != p1.getDeceased()) { if (!p1.getDeceased().equalsDeep(p2.getDeceased())) { return false; } } if (p1.getAddress().size() > 0 && p2.getAddress().size() > 0) { if (!p1.getAddress().get(0).equalsDeep(p2.getAddress().get(0))) { return false; } } if (null != p1.getMaritalStatus()) { if (!p1.getMaritalStatus().equalsDeep(p2.getMaritalStatus())) { return false; } } if (null != p1.getMultipleBirth()) { if (!p1.getMultipleBirth().equalsDeep(p2.getMultipleBirth())) { return false; } } if (null != p1.getGeneralPractitioner()) { if (!p1.getGeneralPractitioner().equals(p2.getGeneralPractitioner())) { return false; } } return p1.getActive() == p2.getActive(); }
Source:
protected static SimpleClusterTierClientEntity createClientEntity(String name, ServerStoreConfiguration configuration, boolean create) throws Exception { Connection connection = CONNECTION_SERVICE.connect(CLUSTER_URI, new Properties()); ClusterTierManagerClientEntityFactory entityFactory = new ClusterTierManagerClientEntityFactory(connection); if (create) { entityFactory.create(name, new ServerSideConfiguration("defaultResource", Collections.<String, ServerSideConfiguration.Pool>emptyMap())); } else { entityFactory.retrieve(name, null); } SimpleClusterTierClientEntity clientEntity = (SimpleClusterTierClientEntity) entityFactory.fetchOrCreateClusteredStoreEntity(name, name, configuration, true); clientEntity.validate(configuration); return clientEntity; }

Target:
protected static SimpleClusterTierClientEntity createClientEntity(String name, ServerStoreConfiguration configuration, boolean create) throws Exception { Connection connection = CONNECTION_SERVICE.connect(CLUSTER_URI, new Properties()); ClusterTierManagerClientEntityFactory entityFactory = new ClusterTierManagerClientEntityFactory(connection); if (create) { entityFactory.create(name, new ServerSideConfiguration("defaultResource", Collections.emptyMap())); } SimpleClusterTierClientEntity clientEntity = (SimpleClusterTierClientEntity) entityFactory.fetchOrCreateClusteredStoreEntity(name, name, configuration, true); clientEntity.validate(configuration); return clientEntity; }
Source:
public void testGetLong_pos8() { fixture.position(8); long result = fixture.getLong(); assertEquals(result, 0x0102030405060708L); }

Target:
public void testGetLong_pos8() throws CTFReaderException { fixture.position(8); final long result = fixture.getLong(); assertEquals(result, 0x0102030405060708L); }
Source:
private SafeHtml navigateDiff(final FileInfo info) { SafeHtmlBuilder b = new SafeHtmlBuilder(); if (Gerrit.isSignedIn() && DiffView.UNIFIED_DIFF.equals(Gerrit.getUserAccount() .getGeneralPreferences().getDiffView()) && !info.binary()) { b.openAnchor().setAttribute("href", diffUrl(info, "side-by-side")) .setAttribute("title", "Switch to Side-By-Side view") .append("Side_By-Side").closeAnchor(); } else if (Gerrit.isSignedIn() && DiffView.SIDE_BY_SIDE.equals(Gerrit.getUserAccount() .getGeneralPreferences().getDiffView())) { b.openAnchor().setAttribute("href", diffUrl(info, "unified")) .setAttribute("title", "Switch to Unified view").append("Unified") .closeAnchor(); } return b; }

Target:
private SafeHtml navigateDiff(final FileInfo info) { SafeHtmlBuilder b = new SafeHtmlBuilder(); if (Gerrit.isSignedIn()) { if (DiffView.UNIFIED_DIFF.equals(Gerrit.getUserAccount() .getGeneralPreferences().getDiffView()) && !info.binary()) { b.openAnchor().setAttribute("href", diffUrl(info, "side-by-side")) .setAttribute("title", Util.C.sideBySideView()) .append("Side_By-Side").closeAnchor(); } else if (DiffView.SIDE_BY_SIDE.equals(Gerrit.getUserAccount() .getGeneralPreferences().getDiffView())) { b.openAnchor().setAttribute("href", diffUrl(info, "unified")) .setAttribute("title", Util.C.unifiedView()).append("Unified") .closeAnchor(); } } return b; }