auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public final Object visitGetKeysInGroupCommand(InvocationContext ctx, GetKeysInGroupCommand command) throws Throwable { if (command.isGroupOwner()) { return invokeNext(ctx, command); } Address primaryOwner = dm.getCacheTopology().getDistribution(command.getGroupName()).primary(); CompletionStage<Map<Address, Response>> future = rpcManager.invokeCommand(primaryOwner, command, new MapResponseCollector(false, 1), rpcManager.getSyncRpcOptions()); return asyncInvokeNext(ctx, command, future.thenAccept(responses -> { if (!responses.isEmpty()) { Response response = responses.values().iterator().next(); if (response instanceof SuccessfulResponse) { List<CacheEntry> cacheEntries = (List<CacheEntry>) ((SuccessfulResponse) response).getResponseValue(); for (CacheEntry entry : cacheEntries) { wrapRemoteEntry(ctx, entry.getKey(), entry, false); } } } })); }

Target:
public final Object visitGetKeysInGroupCommand(InvocationContext ctx, GetKeysInGroupCommand command) throws Throwable { if (command.isGroupOwner()) { return invokeNext(ctx, command); } Address primaryOwner = dm.getCacheTopology().getDistribution(command.getGroupName()).primary(); CompletionStage<ValidResponse> future = rpcManager.invokeCommand(primaryOwner, command, SingleResponseCollector.validOnly(), rpcManager.getSyncRpcOptions()); return asyncInvokeNext(ctx, command, future.thenAccept(response -> { if (response instanceof SuccessfulResponse) { List<CacheEntry> cacheEntries = (List<CacheEntry>) response.getResponseValue(); for (CacheEntry entry : cacheEntries) { wrapRemoteEntry(ctx, entry.getKey(), entry, false); } } })); }
Source:
public Collection<String> getArchitectureViewpointIds() { ArchitectureDescriptionPreferences preferences = SashModelUtils.getArchitectureDescriptionPreferences(modelSet); if (preferences != null) return preferences.getViewpointIds(); Set<String> viewpointIds = new LinkedHashSet<String>(); MergedArchitectureContext context = getArchitectureContext(); if (context != null) { Collection<MergedArchitectureViewpoint> viewpoints = context.getDefaultViewpoints(); if (viewpoints.isEmpty()) viewpoints = context.getViewpoints(); for (MergedArchitectureViewpoint viewpoint : viewpoints) { viewpointIds.add(viewpoint.getId()); } } return viewpointIds; }

Target:
public Collection<String> getArchitectureViewpointIds() { ArchitectureDescriptionPreferences preferences = SashModelUtils.getArchitectureDescriptionPreferences(modelSet); if (preferences != null) { return preferences.getViewpointIds(); } Set<String> viewpointIds = new LinkedHashSet<String>(); MergedArchitectureContext context = getArchitectureContext(); if (context != null) { Collection<MergedArchitectureViewpoint> viewpoints = context.getDefaultViewpoints(); if (viewpoints.isEmpty()) { viewpoints = context.getViewpoints(); } for (MergedArchitectureViewpoint viewpoint : viewpoints) { viewpointIds.add(viewpoint.getId()); } } return viewpointIds; }
Source:
private ColumnChunk readPrimitive(PrimitiveField field) throws IOException { ColumnDescriptor columnDescriptor = field.getDescriptor(); PrimitiveColumnReader columnReader = columnReaders[field.getId()]; if (columnReader.getPageReader() == null) { validateParquet(currentBlockMetadata.getRowCount() > 0, "Row group has 0 rows"); ColumnChunkMetaData metadata = getColumnChunkMetaData(columnDescriptor); long startingPosition = metadata.getStartingPos(); int totalSize = toIntExact(metadata.getTotalSize()); byte[] buffer = allocateBlock(totalSize); dataSource.readFully(startingPosition, buffer); ColumnChunkDescriptor descriptor = new ColumnChunkDescriptor(columnDescriptor, metadata, totalSize); ParquetColumnChunk columnChunk = new ParquetColumnChunk(descriptor, buffer, 0); columnReader.setPageReader(columnChunk.readAllPages()); } try { return columnReader.readPrimitive(field); } catch (UnsupportedOperationException e) { throw new PrestoException(INVALID_SCHEMA_PROPERTY, format("There is a mismatch between file schema and partition schema. The column %s in file %s is declared as type %s but parquet file declared column type as %s.", Joiner.on(".").join(columnDescriptor.getPath()), dataSource.getId(), field.getType(), columnDescriptor.getType())); } }

Target:
private ColumnChunk readPrimitive(PrimitiveField field) throws IOException { ColumnDescriptor columnDescriptor = field.getDescriptor(); PrimitiveColumnReader columnReader = columnReaders[field.getId()]; if (columnReader.getPageReader() == null) { validateParquet(currentBlockMetadata.getRowCount() > 0, "Row group has 0 rows"); ColumnChunkMetaData metadata = getColumnChunkMetaData(columnDescriptor); long startingPosition = metadata.getStartingPos(); int totalSize = toIntExact(metadata.getTotalSize()); byte[] buffer = allocateBlock(totalSize); dataSource.readFully(startingPosition, buffer); ColumnChunkDescriptor descriptor = new ColumnChunkDescriptor(columnDescriptor, metadata, totalSize); ParquetColumnChunk columnChunk = new ParquetColumnChunk(descriptor, buffer, 0); columnReader.setPageReader(columnChunk.readAllPages()); } return columnReader.readPrimitive(field); }
Source:
public byte[] getAPIData() { ByteArrayOutputStream data = new ByteArrayOutputStream(); try { if (rfData != null) data.write(rfData); } catch (IOException e) { e.printStackTrace(); } return data.toByteArray(); }

Target:
public byte[] getAPIData() { ByteArrayOutputStream data = new ByteArrayOutputStream(); try { if (rfData != null) data.write(rfData); } catch (IOException e) { } return data.toByteArray(); }
Source:
protected void updateEmulatedMachines() { if (getModel().getSelectedCluster() == null) { return; } EmulatedMachine oldVal = getModel().getEmulatedMachine().getSelectedItem(); Collection<EmulatedMachine> emList = new ArrayList<>(); if (getModel().getSelectedCluster().getArchitecture().getFamily() == ArchitectureType.ppc) { emList.add(EmulatedMachine.pseries); } else { emList.add(EmulatedMachine.i440fx_seabios); emList.add(EmulatedMachine.q35_ovmf); emList.add(EmulatedMachine.q35_secureboot); } getModel().getEmulatedMachine().setItems(emList); if (oldVal != null) { getModel().getEmulatedMachine().setSelectedItem(oldVal); } }

Target:
protected void updateEmulatedMachines() { if (getModel().getSelectedCluster() == null) { return; } Collection<EmulatedMachine> emList = new ArrayList<>(); emList.add(null); if (!getModel().getEmulatedMachine().getIsChangable()) { getModel().getEmulatedMachine().setItems(emList); return; } if (getModel().getSelectedCluster().getArchitecture().getFamily() == ArchitectureType.ppc) { emList.add(EmulatedMachine.pseries); } else { emList.add(EmulatedMachine.i440fx_seabios); emList.add(EmulatedMachine.q35_ovmf); emList.add(EmulatedMachine.q35_secureboot); } getModel().getEmulatedMachine().setItems(emList); EmulatedMachine em = AsyncDataProvider.getInstance().emulatedMachineByOs(getModel().getOSType().getSelectedItem()); if (emList.contains(em)) { getModel().getEmulatedMachine().setSelectedItem(em); } }
Source:
public void preprocess(DataSetLookup lookup) { if (identityProvider == null) { return; } final List<Comparable> orgEntities = new ArrayList<Comparable>(identityProvider.getRoles()); orgEntities.add(identityProvider.getName()); final ColumnFilter columnFilter = equalsTo(COLUMN_ORGANIZATIONAL_ENTITY, orgEntities); LOGGER.debug("Adding column filter: {}", columnFilter); if (lookup.getFirstFilterOp() != null) { lookup.getFirstFilterOp().addFilterColumn(columnFilter); } else { DataSetFilter filter = new DataSetFilter(); filter.addFilterColumn(columnFilter); lookup.addOperation(filter); } if (lookup.getLastGroupOp() == null) { DataSetGroup gOp = new DataSetGroup(); gOp.setColumnGroup(new ColumnGroup(COLUMN_TASKID, COLUMN_TASKID)); for (String columnId : metadata.getColumnIds()) { AggregateFunctionType functionType = null; if (columnId.equals(COLUMN_TASKID)) { functionType = AggregateFunctionType.DISTINCT; } gOp.addGroupFunction(new GroupFunction(columnId, columnId, functionType)); } lookup.addOperation(gOp); } }

Target:
public void preprocess(DataSetLookup lookup) { if (identityProvider == null) { return; } final List<Comparable> orgEntities = new ArrayList<Comparable>(identityProvider.getRoles()); orgEntities.add(identityProvider.getName()); final ColumnFilter columnFilter = equalsTo(COLUMN_ORGANIZATIONAL_ENTITY, orgEntities); LOGGER.debug("Adding column filter: {}", columnFilter); if (lookup.getFirstFilterOp() != null) { lookup.getFirstFilterOp().addFilterColumn(columnFilter); } else { DataSetFilter filter = new DataSetFilter(); filter.addFilterColumn(columnFilter); lookup.addOperation(filter); } super.preprocess(lookup); }
Source:
public Seq<T> next() { if (!hasNext()) { throw new NoSuchElementException(); } final Seq<T> result = buffer; buffer = that.hasNext() ? that.drop(gap).take(step).toList().prependAll(buffer.drop(step)) : buffer.take(0); return result; }

Target:
public Seq<T> next() { if (buffer.length == 0) { throw new NoSuchElementException(); } final Object[] result = buffer; if (that.hasNext()) { buffer = new Object[size]; if (preserve > 0) { System.arraycopy(result, step, buffer, 0, preserve); } if (gap > 0) { drop(that, gap); buffer = take(that, buffer, preserve, size); } else { buffer = take(that, buffer, preserve, step); } } else { buffer = new Object[0]; } return Array.wrap(result); }
Source:
@Override public void execute(final Callback callback) { new Thread(new Runnable() { @Override public void run() { try { String apiKey = IMGUR_apiKey; if (new Random().nextInt(2) == 1) { apiKey = "foobar"; } HttpRequest request = post(IMGUR_UPLOAD_URL) .part("key", apiKey) .part("image", file); if (request.ok()) { Matcher m = IMGUR_URL_REGEX.matcher(request.body()); m.find(); final String url = m.group(1); Log.i(TAG, "Upload success! " + url); MAIN_THREAD.post(new Runnable() { @Override public void run() { callback.onSuccess(url); } }); } else { Log.i(TAG, String.format( "Upload failed :( Will retry in %d seconds.", RETRY_WAIT / 1000)); try { Thread.sleep(RETRY_WAIT); } catch (InterruptedException e) { e.printStackTrace(); } MAIN_THREAD.post(new Runnable() { @Override public void run() { callback.onFailure(); } }); } } catch (RuntimeException e) { e.printStackTrace(); throw e; } } }).start(); }

Target:
@Override public void execute(final Callback callback) { new Thread(new Runnable() { @Override public void run() { try { String apiKey = IMGUR_API_KEY; if (new Random().nextBoolean()) { apiKey = "foobar"; } HttpRequest request = post(IMGUR_UPLOAD_URL) .part("key", apiKey) .part("image", file); if (request.ok()) { Matcher m = IMGUR_URL_REGEX.matcher(request.body()); m.find(); final String url = m.group(1); Log.i(TAG, "Upload success! " + url); MAIN_THREAD.post(new Runnable() { @Override public void run() { callback.onSuccess(url); } }); } else { Log.i(TAG, String.format( "Upload failed :( Will retry in %d seconds.", RETRY_WAIT / 1000)); try { Thread.sleep(RETRY_WAIT); } catch (InterruptedException e) { e.printStackTrace(); throw new RuntimeException(e); } MAIN_THREAD.post(new Runnable() { @Override public void run() { callback.onFailure(); } }); } } catch (RuntimeException e) { e.printStackTrace(); throw e; } } }).start(); }
Source:
public Void visitInsert(Insert<?> node, Integer indent) { append(indent, "INSERT"); builder.append(' '); append(indent, "INTO"); builder.append(' '); node.table().accept(this, indent); builder.append(' '); var columns = node.columns().iterator(); if (columns.hasNext()) { builder.append('('); while (columns.hasNext()) { builder.append(columns.next()); if (columns.hasNext()) { builder.append(", "); } } builder.append(')'); } builder.append(' '); node.insertSource().accept(this, indent); var returning = node.returningClause().iterator(); if (returning.hasNext()) { append(indent, "RETURNING"); while (returning.hasNext()) { builder.append(' '); returning.next().accept(this, indent); if (returning.hasNext()) { builder.append(','); } } } return null; }

Target:
public Void visitInsert(Insert<?> node, Integer indent) { append(indent, "INSERT"); builder.append(' '); append(indent, "INTO"); builder.append(' '); node.table().accept(this, indent); builder.append(' '); var columns = node.columns().iterator(); if (columns.hasNext()) { builder.append('('); while (columns.hasNext()) { builder.append(columns.next()); if (columns.hasNext()) { builder.append(", "); } } builder.append(')'); } builder.append(' '); node.insertSource().accept(this, indent); var duplicateKeyContext = node.duplicateKeyContext(); if (duplicateKeyContext.getType() != NONE) { builder.append(" ON CONFLICT"); var constraintColumns = duplicateKeyContext.getConstraintColumns().iterator(); if (constraintColumns.hasNext()) { builder.append(" ("); while (constraintColumns.hasNext()) { builder.append(constraintColumns.next()); if (constraintColumns.hasNext()) { builder.append(", "); } } builder.append(')'); } switch (duplicateKeyContext.getType()) { case ON_CONFLICT_DO_NOTHING: builder.append(" DO NOTHING"); break; case ON_CONFLICT_DO_UPDATE_SET: builder.append(" DO UPDATE"); var assignments = duplicateKeyContext.getAssignments().iterator(); if (assignments.hasNext()) { builder.append(" SET "); while (assignments.hasNext()) { assignments.next().accept(this, indent); if (assignments.hasNext()) { builder.append(", "); } } } break; case NONE: default: } } var returning = node.returningClause().iterator(); if (returning.hasNext()) { append(indent, "RETURNING"); while (returning.hasNext()) { builder.append(' '); returning.next().accept(this, indent); if (returning.hasNext()) { builder.append(','); } } } return null; }
Source:
public static void loadSortListFromJSONArray(List<AbstractExpression> sortExpressions, List<SortDirectionType> sortDirections, JSONObject jobj) throws JSONException { if (jobj.has(AbstractExpression.SortMembers.SORT_COLUMNS.name())) { sortExpressions.clear(); if (sortDirections != null) { sortDirections.clear(); } JSONArray jarray = jobj.getJSONArray(SortMembers.SORT_COLUMNS.name()); int size = jarray.length(); for (int ii = 0; ii < size; ii += 1) { JSONObject tempObj = jarray.getJSONObject(ii); if (sortDirections != null) { sortExpressions.add( AbstractExpression.fromJSONChild(tempObj, SortMembers.SORT_EXPRESSION.name()) ); if (sortDirections != null && tempObj.has(SortMembers.SORT_DIRECTION.name())) { sortDirections.add( SortDirectionType.get(tempObj.getString( SortMembers.SORT_DIRECTION.name())) ); } } } } assert(sortDirections == null || sortExpressions.size() == sortDirections.size()); }

Target:
public static void loadSortListFromJSONArray(List<AbstractExpression> sortExpressions, List<SortDirectionType> sortDirections, JSONObject jobj) throws JSONException { if (jobj.has(AbstractExpression.SortMembers.SORT_COLUMNS.name())) { sortExpressions.clear(); if (sortDirections != null) { sortDirections.clear(); } JSONArray jarray = jobj.getJSONArray(SortMembers.SORT_COLUMNS.name()); int size = jarray.length(); for (int ii = 0; ii < size; ii += 1) { JSONObject tempObj = jarray.getJSONObject(ii); sortExpressions.add( AbstractExpression.fromJSONChild(tempObj, SortMembers.SORT_EXPRESSION.name()) ); if (sortDirections != null) { if (sortDirections != null && tempObj.has(SortMembers.SORT_DIRECTION.name())) { sortDirections.add( SortDirectionType.get(tempObj.getString( SortMembers.SORT_DIRECTION.name())) ); } } } } assert(sortDirections == null || sortExpressions.size() == sortDirections.size()); }
Source:
public Set<Type> getImportTypes() { Set<Type> imported = new HashSet<Type>( getAssignment().getImportTypes().size() + 1 ); imported.addAll( getAssignment().getImportTypes() ); imported.add( enumType ); return imported; }

Target:
public Set<Type> getImportTypes() { Set<Type> imported = new HashSet<Type>( getAssignment().getImportTypes() ); imported.add( enumType ); return imported; }
Source:
public void prepareServerOnce() throws Exception { if(!serverConfigDone) { log.trace("*** preparing server configuration"); ManagementClient managementClient; log.trace("*** starting server"); container.start(DEFAULT_JBOSSAS); final ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient(); managementClient = new ManagementClient(client, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http"); log.info("*** will configure server now"); SSLRealmSetupTool.setup(managementClient); log.trace("*** restarting server"); container.stop(DEFAULT_JBOSSAS); container.start(DEFAULT_JBOSSAS); managementClient = new ManagementClient(client, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http"); SSLRealmSetupTool.readSSLRealmConfig(managementClient); serverConfigDone = true; } else { log.trace("*** Server already prepared, skipping config procedure"); } }

Target:
public void prepareServerOnce() throws Exception { if(!serverConfigDone) { log.trace("*** preparing server configuration"); ManagementClient managementClient; log.trace("*** starting server"); container.start(DEFAULT_JBOSSAS); final ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient(); managementClient = new ManagementClient(client, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http"); log.trace("*** will configure server now"); SSLRealmSetupTool.setup(managementClient); log.trace("*** restarting server"); container.stop(DEFAULT_JBOSSAS); container.start(DEFAULT_JBOSSAS); managementClient = new ManagementClient(client, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http"); SSLRealmSetupTool.readSSLRealmConfig(managementClient); serverConfigDone = true; } else { log.trace("*** Server already prepared, skipping config procedure"); } }
Source:
public Optional<RuntimeModel> registerFile(String fileName) { if (fileName == null || fileName.trim().isEmpty()) { logger.error("Invalid file name: {}", fileName); throw new IllegalArgumentException("Invalid file name."); } File file = new File(fileName); if (!file.exists()) { logger.error("File does not exist: {}", fileName); throw new IllegalArgumentException("File does not exist"); } if (!importValidationService.validate(fileName)) { logger.error("File does not have a valid structure: {}", fileName); throw new IllegalArgumentException("Not a valid file structure."); } try (FileInputStream fis = new FileInputStream(fileName)) { String importId = file.getName().replaceAll(".zip", ""); return register(importId, fis); } catch (IOException e) { logger.error("Not able to load file {}", fileName, e); throw new IllegalArgumentException("Error loading import file: " + fileName, e); } }

Target:
public Optional<RuntimeModel> registerFile(String fileName) { if (fileName == null || fileName.trim().isEmpty()) { logger.error("Invalid file name: {}", fileName); throw new IllegalArgumentException("Invalid file name."); } File file = new File(fileName); if (!file.exists()) { logger.error("File does not exist: {}", fileName); throw new IllegalArgumentException("File does not exist"); } if (!importValidationService.validate(fileName)) { logger.error("File does not have a valid structure: {}", fileName); throw new IllegalArgumentException("Not a valid file structure."); } try (FileInputStream fis = new FileInputStream(fileName)) { String importId = FilenameUtils.getBaseName(file.getPath()); return register(importId, fis); } catch (IOException e) { logger.error("Not able to load file {}", fileName, e); throw new IllegalArgumentException("Error loading import file: " + fileName, e); } }
Source:
public static List<TelemetryBis.TelemetryField> getRowsFromTable(Telemetry msg, String name) { Objects.requireNonNull(msg); for (TelemetryBis.TelemetryField field : msg.getDataGpbkvList()) { TelemetryBis.TelemetryField subField = findFieldWithName(field, "ROW_" + name); if (subField != null) { return subField.getFieldsList(); } } return null; }

Target:
public static List<TelemetryBis.TelemetryField> getRowsFromTable(Telemetry msg, String name) { if (Objects.isNull(msg) || Objects.isNull(name)) { return Collections.emptyList(); } for (TelemetryBis.TelemetryField field : msg.getDataGpbkvList()) { TelemetryBis.TelemetryField subField = findFieldWithName(field, "ROW_" + name); if (subField != null) { return subField.getFieldsList(); } } return Collections.emptyList(); }
Source:
private static HashMap<String, String> extractJsonObjects(final String jsonStr) throws JSONException { final JSONObject jsonObject = new JSONObject(jsonStr); final HashMap<String, String> responseItems = new HashMap<>(); final Iterator<?> i = jsonObject.keys(); while (i.hasNext()) { final String key = (String) i.next(); responseItems.put(key, jsonObject.getString(key)); } return responseItems; }

Target:
private static Map<String, String> extractJsonObjects(final String jsonStr) throws JSONException { final JSONObject jsonObject = new JSONObject(jsonStr); final Map<String, String> responseItems = new HashMap<>(); final Iterator<?> i = jsonObject.keys(); while (i.hasNext()) { final String key = (String) i.next(); responseItems.put(key, jsonObject.getString(key)); } return responseItems; }
Source:
public void serialize(Writer writer) throws IOException { for (Entry<String, HeadRule> entry : headRules.entrySet()) { final String type = entry.getKey(); final HeadRule headRule = entry.getValue(); writer.write(Integer.toString(headRule.tags.length + 2)); writer.write(' '); writer.write(type); writer.write(' '); if (headRule.leftToRight) writer.write("1"); else writer.write("0"); for (String tag : headRule.tags) { writer.write(' '); writer.write(tag); } writer.write('\n'); } writer.flush(); }

Target:
public void serialize(Writer writer) throws IOException { for (Entry<String, HeadRule> entry : headRules.entrySet()) { String type = entry.getKey(); HeadRule headRule = entry.getValue(); writer.write(Integer.toString(headRule.tags.length + 2)); writer.write(' '); writer.write(type); writer.write(' '); if (headRule.leftToRight) writer.write("1"); else writer.write("0"); for (String tag : headRule.tags) { writer.write(' '); writer.write(tag); } writer.write('\n'); } writer.flush(); }
Source:
public String getCustomDefaultContributorRoleDescription(){ if (dvObject instanceof Dataverse && isCustomDefaultConributorRole()){ return defaultContributorRoleAlias.equals("none") ? BundleUtil.getStringFromBundle("permission.default.contributor.role.none" ) :roleService.findCustomRoleByAliasAndOwner(defaultContributorRoleAlias,dvObject.getId() ).getDescription(); } else { return ""; } }

Target:
public String getCustomDefaultContributorRoleDescription(){ if (dvObject instanceof Dataverse && isCustomDefaultContributorRole()){ return defaultContributorRoleAlias.equals(DataverseRole.NONE) ? BundleUtil.getStringFromBundle("permission.default.contributor.role.none.decription" ) :roleService.findCustomRoleByAliasAndOwner(defaultContributorRoleAlias,dvObject.getId() ).getDescription(); } else { return ""; } }
Source:
HiveCompressionCodec( Class<? extends CompressionCodec> codec, CompressionKind orcCompressionKind, CompressionCodecName parquetCompressionCodec, Predicate<HiveStorageFormat> supportedStorageFormats) { this.codec = Optional.ofNullable(codec); this.orcCompressionKind = requireNonNull(orcCompressionKind, "orcCompressionKind is null"); this.parquetCompressionCodec = Optional.ofNullable(parquetCompressionCodec); this.supportedStorageFormats = requireNonNull(supportedStorageFormats); }

Target:
HiveCompressionCodec( Class<? extends CompressionCodec> codec, CompressionKind orcCompressionKind, CompressionCodecName parquetCompressionCodec, Predicate<HiveStorageFormat> supportedStorageFormats) { this.codec = Optional.ofNullable(codec); this.orcCompressionKind = requireNonNull(orcCompressionKind, "orcCompressionKind is null"); this.parquetCompressionCodec = Optional.ofNullable(parquetCompressionCodec); this.supportedStorageFormats = requireNonNull(supportedStorageFormats, "supportedStorageFormats is null"); }
Source:
public void testZooKeeperLeaderElectionRetrieval() throws Exception { final TestingLeaderElectionEventHandler electionEventHandler = new TestingLeaderElectionEventHandler(TEST_LEADER); final TestingLeaderRetrievalEventHandler retrievalEventHandler = new TestingLeaderRetrievalEventHandler(); LeaderElectionDriver leaderElectionDriver = null; LeaderRetrievalDriver leaderRetrievalDriver = null; try { leaderElectionDriver = ZooKeeperUtils.createLeaderElectionDriverFactory(client, configuration) .createLeaderElectionDriver(electionEventHandler, electionEventHandler::handleError, TEST_URL); electionEventHandler.init(leaderElectionDriver); leaderRetrievalDriver = ZooKeeperUtils.createLeaderRetrievalDriverFactory(client, configuration) .createLeaderRetrievalDriver(retrievalEventHandler, retrievalEventHandler::handleError); electionEventHandler.waitForLeader(timeout); assertThat(electionEventHandler.getConfirmedLeaderInformation(), is(TEST_LEADER)); retrievalEventHandler.waitForNewLeader(timeout); assertThat(retrievalEventHandler.getLeaderSessionID(), is(TEST_LEADER.getLeaderSessionID())); assertThat(retrievalEventHandler.getAddress(), is(TEST_LEADER.getLeaderAddress())); } finally { if (leaderElectionDriver != null) { leaderElectionDriver.close(); } if (leaderRetrievalDriver != null) { leaderRetrievalDriver.close(); } } }

Target:
public void testZooKeeperLeaderElectionRetrieval() throws Exception { final TestingLeaderElectionEventHandler electionEventHandler = new TestingLeaderElectionEventHandler(TEST_LEADER); final TestingLeaderRetrievalEventHandler retrievalEventHandler = new TestingLeaderRetrievalEventHandler(); LeaderElectionDriver leaderElectionDriver = null; LeaderRetrievalDriver leaderRetrievalDriver = null; try { leaderElectionDriver = createAndInitLeaderElectionDriver(client, electionEventHandler); leaderRetrievalDriver = ZooKeeperUtils.createLeaderRetrievalDriverFactory(client, configuration) .createLeaderRetrievalDriver(retrievalEventHandler, retrievalEventHandler::handleError); electionEventHandler.waitForLeader(timeout); assertThat(electionEventHandler.getConfirmedLeaderInformation(), is(TEST_LEADER)); retrievalEventHandler.waitForNewLeader(timeout); assertThat(retrievalEventHandler.getLeaderSessionID(), is(TEST_LEADER.getLeaderSessionID())); assertThat(retrievalEventHandler.getAddress(), is(TEST_LEADER.getLeaderAddress())); } finally { if (leaderElectionDriver != null) { leaderElectionDriver.close(); } if (leaderRetrievalDriver != null) { leaderRetrievalDriver.close(); } } }
Source:
protected static boolean processConfig() { CollectorConfiguration config = configService.getCollector(null, null, null, null); if (config != null) { try { updateInstrumentation(config); } catch (Exception e) { log.severe("Failed to update instrumentation rules: " + e); } configExecutor.shutdownNow(); } return config != null; }

Target:
protected static boolean processConfig() { CollectorConfiguration config = configService.getCollector(null, null, null, null); if (config != null) { try { updateInstrumentation(config); } catch (Exception e) { log.severe("Failed to update instrumentation rules: " + e); } } return config != null; }
Source:
public void should_format_passed_scenario() throws Throwable { CucumberFeature feature = TestHelper.feature("path/test.feature", "Feature: feature name\n" + " Scenario: scenario name\n" + " Given first step\n" + " When second step\n" + " Then third step\n"); features.add(feature); stepsToResult.put("first step", result("passed")); stepsToResult.put("second step", result("passed")); stepsToResult.put("third step", result("passed")); stepDuration = Duration.ofNanos(1L); String formatterOutput = runFeaturesWithFormatter(); String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + "<testsuite failures=\"0\" name=\"io.cucumber.core.plugin.JUnitFormatter\" skipped=\"0\" tests=\"1\" time=\"0.003\">\n" + " <testcase classname=\"feature name\" name=\"scenario name\" time=\"0.003\">\n" + " <system-out><![CDATA[" + "Given first step............................................................passed\n" + "When second step............................................................passed\n" + "Then third step.............................................................passed\n" + "]]></system-out>\n" + " </testcase>\n" + "</testsuite>\n"; assertXmlEqual(expected, formatterOutput); }

Target:
public void should_format_passed_scenario() throws Throwable { CucumberFeature feature = TestHelper.feature("path/test.feature", "Feature: feature name\n" + " Scenario: scenario name\n" + " Given first step\n" + " When second step\n" + " Then third step\n"); features.add(feature); stepsToResult.put("first step", result("passed")); stepsToResult.put("second step", result("passed")); stepsToResult.put("third step", result("passed")); stepDuration = Duration.ofMillis(1L); String formatterOutput = runFeaturesWithFormatter(); String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + "<testsuite failures=\"0\" name=\"io.cucumber.core.plugin.JUnitFormatter\" skipped=\"0\" tests=\"1\" time=\"0.003\">\n" + " <testcase classname=\"feature name\" name=\"scenario name\" time=\"0.003\">\n" + " <system-out><![CDATA[" + "Given first step............................................................passed\n" + "When second step............................................................passed\n" + "Then third step.............................................................passed\n" + "]]></system-out>\n" + " </testcase>\n" + "</testsuite>\n"; assertXmlEqual(expected, formatterOutput); }
Source:
public NoOpApexPluginDispatcher() { super("NoOpPluginManager"); }

Target:
public NoOpApexPluginDispatcher() { super(NoOpApexPluginDispatcher.class.getName()); }
Source:
protected Endpoint createEndpoint(final String uri, final String remaining, final Map<String, Object> parameters) throws Exception { LOG.info("Creating CM Endpoint ... "); final String url = CMConstants.DEFAULT_SCHEME + remaining; if (!UrlValidator.getInstance().isValid(url)) { final String errorMessage = String.format("HOST provided: %s seem to be invalid. Remember SCHEME has to be excluded.", url); final Exception t = new InvalidURLException(errorMessage); LOG.error(errorMessage, t); throw t; } LOG.info("Uri=[{}], path=[{}], parameters=[{}]", new Object[] {URISupport.sanitizeUri(uri), URISupport.sanitizePath(remaining), parameters }); final CMConfiguration config = new CMConfiguration(); setProperties(config, parameters); LOG.info("Validating uri based configuration"); final Set<ConstraintViolation<CMConfiguration>> constraintViolations = validator.validate(config); if (constraintViolations.size() > 0) { final StringBuffer msg = new StringBuffer(); for (final ConstraintViolation<CMConfiguration> cv : constraintViolations) { msg.append(String.format("- Invalid value for %s: %s", cv.getPropertyPath().toString(), cv.getMessage())); } LOG.error(msg.toString()); throw new InvalidUriEndpointException(msg.toString()); } LOG.info("CMConfiguration - OK!"); LOG.info("Creating CMEndpoint"); final CMEndpoint endpoint = new CMEndpoint(uri, this); endpoint.setConfiguration(config); endpoint.setHost(remaining); return endpoint; }

Target:
protected Endpoint createEndpoint(final String uri, final String remaining, final Map<String, Object> parameters) throws Exception { LOG.debug("Creating CM Endpoint ... "); final String url = CMConstants.DEFAULT_SCHEME + remaining; if (!UrlValidator.getInstance().isValid(url)) { throw new ResolveEndpointFailedException(uri, String.format("HOST provided: %s seem to be invalid. Remember SCHEME has to be excluded.", url)); } LOG.debug("Uri=[{}], path=[{}], parameters=[{}]", new Object[] {URISupport.sanitizeUri(uri), URISupport.sanitizePath(remaining), parameters }); final CMConfiguration config = new CMConfiguration(); setProperties(config, parameters); LOG.debug("Validating uri based configuration"); final Set<ConstraintViolation<CMConfiguration>> constraintViolations = validator.validate(config); if (constraintViolations.size() > 0) { final StringBuffer msg = new StringBuffer(); for (final ConstraintViolation<CMConfiguration> cv : constraintViolations) { msg.append(String.format("- Invalid value for %s: %s", cv.getPropertyPath().toString(), cv.getMessage())); } throw new ResolveEndpointFailedException(uri, msg.toString()); } LOG.debug("CMConfiguration - OK!"); LOG.debug("Creating CMEndpoint"); final CMEndpoint endpoint = new CMEndpoint(uri, this); endpoint.setConfiguration(config); endpoint.setHost(remaining); return endpoint; }
Source:
public ProjectSubmissionOutputFileParser(Reader source) { if(source != null) { bufferedReader = new BufferedReader(source); } }

Target:
public ProjectSubmissionOutputFileParser(Reader source) { if(source != null) { bufferedReader = new BufferedReader(source); } else throw new NullPointerException(); }
Source:
public Mono<AuthenticationRecord> authenticate() { String defaultScope = KnownAuthorityHosts.getDefaultScope(authorityHost); if (defaultScope == null) { return Mono.error(new AuthenticationRequiredException("Authenticating in this environment requires" + " specifying a TokenRequestContext.")); } return authenticate(new TokenRequestContext().addScopes(defaultScope)); }

Target:
public Mono<AuthenticationRecord> authenticate() { String defaultScope = KnownAuthorityHosts.getDefaultScope(authorityHost); if (defaultScope == null) { return Mono.error(logger.logExceptionAsError(new CredentialUnavailableException("Authenticating in this " + "environment requires specifying a TokenRequestContext."))); } return authenticate(new TokenRequestContext().addScopes(defaultScope)); }
Source:
public void writeAllTo(OutputStream out) throws IOException { for (BytesInput input : inputs) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("write " + input.size() + " bytes to out"); } if (LOGGER.isDebugEnabled() && input instanceof SequenceBytesIn) { LOGGER.debug("{"); } input.writeAllTo(out); if (LOGGER.isDebugEnabled() && input instanceof SequenceBytesIn) { LOGGER.debug("}"); } } }

Target:
public void writeAllTo(OutputStream out) throws IOException { for (BytesInput input : inputs) { LOGGER.debug("write bytes to out", input.size()); if (input instanceof SequenceBytesIn) { LOGGER.debug("{"); } input.writeAllTo(out); if (input instanceof SequenceBytesIn) { LOGGER.debug("}"); } } }
Source:
public Response get(@ApiParam(value = "Plan Id") @PathParam("id") Long id) { Plan plan = planService.get(id); if (plan == null) { return getPlanNotFound(id); } else { return Response.ok(plan).build(); } }

Target:
public Response get(@ApiParam(value = "Plan Id") @PathParam("id") Long id) throws PlanNotFoundException { return Response.ok(planService.get(id)).build(); }
Source:
public int hashCode() { return (getElementName() + getJid().toString()).hashCode(); }

Target:
public final int hashCode() { return (getElementName() + getJid().toString()).hashCode(); }
Source:
public static IOHub create(Executor executor) throws IOException { IOHub result = new IOHub(executor); executor.execute(result); if (Launcher.isWindows()) { LOGGER.log(Level.FINE, "IOHub runs on Windows. There are known issues with Selector#select() hanging, running an additional watcher thread. See JENKINS-47965 for more info"); executor.execute(new WindowsIOHubSelectorWatcher(result)); } return result; }

Target:
public static IOHub create(Executor executor) throws IOException { IOHub result = new IOHub(executor); executor.execute(result); LOGGER.log(Level.FINE, "Staring an additional Selector wakeup thread. See JENKINS-47965 for more info"); executor.execute(new IOHubSelectorWatcher(result)); return result; }
Source:
public Entry getEntryFromTuple(YailList tuple) { try { String xValue = tuple.getString(0); String yValue = tuple.getString(1); try { int x = (int)Math.floor(Float.parseFloat(xValue)); float y = Float.parseFloat(yValue); return new BarEntry(x, y); } catch (NumberFormatException e) { } } catch (Exception e) { } return null; }

Target:
public Entry getEntryFromTuple(YailList tuple) { try { String xValue = tuple.getString(0); String yValue = tuple.getString(1); try { int x = (int)Math.floor(Float.parseFloat(xValue)); float y = Float.parseFloat(yValue); return new BarEntry(x, y); } catch (NumberFormatException e) { this.view.getForm().dispatchErrorOccurredEvent(this.view.chartComponent, "GetEntryFromTuple", ErrorMessages.ERROR_INVALID_CHART_ENTRY_VALUES, xValue, yValue); } } catch (NullPointerException e) { this.view.getForm().dispatchErrorOccurredEvent(this.view.chartComponent, "GetEntryFromTuple", ErrorMessages.ERROR_NULL_CHART_ENTRY_VALUES); } catch (IndexOutOfBoundsException e) { this.view.getForm().dispatchErrorOccurredEvent(this.view.chartComponent, "GetEntryFromTuple", ErrorMessages.ERROR_INSUFFICIENT_CHART_ENTRY_VALUES, getTupleSize(), tuple.size()); } return null; }
Source:
public Map<String, ActionInfo> format(RevisionResource rsrc) throws OrmException { ChangeData cd = changeDataFactory.create(db.get(), rsrc.getControl()); return toRevisionActionInfoMap(cd, rsrc.getPatchSet().getId()); }

Target:
public Map<String, ActionInfo> format(RevisionResource rsrc) { return toActionMap(rsrc); }
Source:
@Test public void testRequestSuccess() throws Throwable { enqueueFromFile("announce_2016_11_21.json"); AnnouncementClient.Callback cb = mock(AnnouncementClient.Callback.class); request(cb); server().takeRequest(); verify(cb).success(any(List.class)); verify(cb, never()).error(any(Throwable.class)); }

Target:
@Test public void testRequestSuccess() throws Throwable { enqueueFromFile("announce_2016_11_21.json"); Callback cb = mock(Callback.class); request(cb); server().takeRequest(); verify(cb).success(anyListOf(Card.class)); verify(cb, never()).error(any(Throwable.class)); }
Source:
public RoughToRealVerificationOperation(OrcsApi orcsApi, BranchId branchId, XResultData results, ArtifactReadable destinationArtifact, RoughArtifactCollector rawData, IArtifactImportResolver artifactResolver, boolean deleteUnmatchedArtifacts, IArtifactExtractor extractor) { this.results = results; this.orcsApi = orcsApi; this.branchId = branchId; this.rawData = rawData; this.artifactResolver = artifactResolver; this.destinationArtifact = destinationArtifact; this.roughToRealArtifacts = new HashMap<>(); roughToRealArtifacts.put(rawData.getParentRoughArtifact(), this.destinationArtifact); }

Target:
public RoughToRealVerificationOperation(OrcsApi orcsApi, BranchId branchId, XResultData results, ArtifactReadable destinationArtifact, RoughArtifactCollector rawData, IArtifactImportResolver artifactResolver, boolean deleteUnmatchedArtifacts, IArtifactExtractor extractor) { this.results = results; this.orcsApi = orcsApi; this.branchId = branchId; this.rawData = rawData; this.artifactResolver = artifactResolver; this.destinationArtifact = destinationArtifact; this.roughToRealArtifacts = new HashMap<>(); roughToRealArtifacts.put(rawData.getParentRoughArtifact(), destinationArtifact); }
Source:
private KualiDecimal getTotalRequestFileRequestAmount(ConcurRequestExtractFile requestExtractFile) { double detailLinesApprovedAmountSum = 0; if ( (requestExtractFile.getRequestDetails() == null) || (requestExtractFile.getRequestDetails().isEmpty()) ) { return new KualiDecimal(detailLinesApprovedAmountSum); } else { List<ConcurRequestExtractRequestDetailFileLine> requestDetailLines = requestExtractFile.getRequestDetails(); for (ConcurRequestExtractRequestDetailFileLine detailLine : requestDetailLines) { detailLinesApprovedAmountSum = detailLinesApprovedAmountSum + detailLine.getRequestAmount().doubleValue(); } return new KualiDecimal(detailLinesApprovedAmountSum); } }

Target:
private KualiDecimal getTotalRequestFileRequestAmount(ConcurRequestExtractFile requestExtractFile) { KualiDecimal detailLinesApprovedAmountSum = KualiDecimal.ZERO; if ( (requestExtractFile.getRequestDetails() == null) || (requestExtractFile.getRequestDetails().isEmpty()) ) { return detailLinesApprovedAmountSum; } else { List<ConcurRequestExtractRequestDetailFileLine> requestDetailLines = requestExtractFile.getRequestDetails(); for (ConcurRequestExtractRequestDetailFileLine detailLine : requestDetailLines) { detailLinesApprovedAmountSum = detailLinesApprovedAmountSum.add(detailLine.getRequestAmount()); } return detailLinesApprovedAmountSum; } }
Source:
public void eventReceived(Object output) { if (output instanceof MIOutput) { MIOOBRecord[] records = ((MIOutput)output).getMIOOBRecords(); for (MIOOBRecord r : records) { if (r instanceof MINotifyAsyncOutput) { MINotifyAsyncOutput notifyOutput = (MINotifyAsyncOutput)r; String asyncClass = notifyOutput.getAsyncClass(); if ("record-started".equals(asyncClass) || "record-stopped".equals(asyncClass)) { if ("record-stopped".equals(asyncClass)) { fReverseTraceMethod = ReverseTraceMethod.STOP_TRACE; getSession().dispatchEvent(new GdbReverseModeChangedDMEvent(fCommandControl.getContext(), false), getProperties()); } else { getConnection().queueCommand( fCommandFactory.createCLIInfoRecord(getConnection().getContext()), new DataRequestMonitor<MIinfoRecord>(getExecutor(), null) { @Override public void handleSuccess() { MIinfoRecord output = getData(); fReverseTraceMethod = output.getReverseMethod(); getSession().dispatchEvent(new GdbReverseModeChangedDMEvent(fCommandControl.getContext(), true), getProperties()); } }); } } } } } }

Target:
public void eventReceived(Object output) { if (output instanceof MIOutput) { MIOOBRecord[] records = ((MIOutput)output).getMIOOBRecords(); for (MIOOBRecord r : records) { if (r instanceof MINotifyAsyncOutput) { MINotifyAsyncOutput notifyOutput = (MINotifyAsyncOutput)r; String asyncClass = notifyOutput.getAsyncClass(); if ("record-started".equals(asyncClass) || "record-stopped".equals(asyncClass)) { if ("record-stopped".equals(asyncClass)) { fReverseTraceMethod = ReverseTraceMethod.STOP_TRACE; setReverseModeEnabled(false); } else { getConnection().queueCommand( fCommandFactory.createCLIInfoRecord(getConnection().getContext()), new DataRequestMonitor<CLIInfoRecordInfo>(getExecutor(), null) { @Override public void handleSuccess() { CLIInfoRecordInfo output = getData(); fReverseTraceMethod = output.getReverseMethod(); setReverseModeEnabled(true); } }); } } } } } }
Source:
public void onClose(final int code, final String reason, final boolean remote) { if (state != ConnectionState.DISCONNECTED) { activityTimer.cancelTimeouts(); factory.queueOnEventThread(new Runnable() { @Override public void run() { updateState(ConnectionState.DISCONNECTED); factory.shutdownThreads(); } }); } else { log.error("Received close from underlying socket when already disconnected. " + "Close code [" + code + "], Reason [" + reason + "], Remote [" + remote + "]"); } }

Target:
public void onClose(final int code, final String reason, final boolean remote) { if (state == ConnectionState.DISCONNECTED) { log.error("Received close from underlying socket when already disconnected. " + "Close code [" + code + "], Reason [" + reason + "], Remote [" + remote + "]"); return; } activityTimer.cancelTimeouts(); factory.queueOnEventThread(new Runnable() { @Override public void run() { updateState(ConnectionState.DISCONNECTED); factory.shutdownThreads(); } }); }
Source:
public GatewayResponse capture(CaptureGatewayRequest request) { String url = stripeGatewayConfig.getUrl() + "/v1/charges/" + request.getTransactionId() + "/capture"; GatewayAccountEntity gatewayAccount = request.getGatewayAccount(); GatewayResponse.GatewayResponseBuilder<BaseResponse> responseBuilder = GatewayResponse.GatewayResponseBuilder.responseBuilder(); try { Response captureResponse = client.postRequest( URI.create(url), StringUtils.EMPTY, ImmutableMap.of(AUTHORIZATION, StripeAuthUtil.getAuthHeaderValue(stripeGatewayConfig)), APPLICATION_FORM_URLENCODED_TYPE, format("gateway-operations.%s.%s.capture", gatewayAccount.getGatewayName(), gatewayAccount.getType())); return responseBuilder.withResponse(StripeCaptureResponse.of(captureResponse)).build(); } catch (GatewayClientException e) { GatewayError gatewayError = GatewayError.unexpectedStatusCodeFromGateway(e .getResponse() .readEntity(StripeErrorResponse.class) .getError() .getMessage()); return responseBuilder.withGatewayError(gatewayError).build(); } catch (GatewayClientRuntimeException e) { return responseBuilder.withGatewayError(processGatewayException(e)).build(); } }

Target:
public GatewayResponse capture(CaptureGatewayRequest request) { String url = stripeGatewayConfig.getUrl() + "/v1/charges/" + request.getTransactionId() + "/capture"; GatewayAccountEntity gatewayAccount = request.getGatewayAccount(); GatewayResponse.GatewayResponseBuilder<BaseResponse> responseBuilder = GatewayResponse.GatewayResponseBuilder.responseBuilder(); try { Response captureResponse = client.postRequest( URI.create(url), StringUtils.EMPTY, ImmutableMap.of(AUTHORIZATION, StripeAuthUtil.getAuthHeaderValue(stripeGatewayConfig)), APPLICATION_FORM_URLENCODED_TYPE, format("gateway-operations.%s.%s.capture", gatewayAccount.getGatewayName(), gatewayAccount.getType())); return responseBuilder.withResponse(StripeCaptureResponse.of(captureResponse)).build(); } catch (GatewayClientException e) { GatewayError gatewayError = GatewayError.unexpectedStatusCodeFromGateway(e .getResponse() .readEntity(StripeErrorResponse.class) .getError() .getMessage()); return responseBuilder.withGatewayError(gatewayError).build(); } catch (GatewayClientRuntimeException e) { return responseBuilder.withGatewayError(GatewayError.of(e)).build(); } }
Source:
private AuthConfig authConfigUsingCredentialsStoreOrHelper(String hostName, JsonNode config) throws Exception { final String credsStoreName = config.at("/credsStore").asText(); final String credHelper = config.at("/credHelpers/" + hostName).asText(); if (StringUtils.isNotBlank(credHelper)) { return runCredentialProvider(hostName, credHelper); } else if (StringUtils.isNotBlank(credsStoreName)) { return runCredentialProvider(hostName, credsStoreName); } else { throw new UnsupportedOperationException(); } }

Target:
private AuthConfig authConfigUsingCredentialsStoreOrHelper(String hostName, JsonNode config) throws Exception { final JsonNode credsStoreName = config.at("/credsStore"); final JsonNode credHelper = config.at("/credHelpers/" + hostName); if (!credHelper.isMissingNode()) { return runCredentialProvider(hostName, credHelper.asText()); } else if (!credsStoreName.isMissingNode()) { return runCredentialProvider(hostName, credsStoreName.asText()); } else { throw new IllegalStateException("Unsupported Docker config auths settings!"); } }
Source:
public void shouldRegisterDefaultHealthCheck() { Set<String> registered = healthCheckRegistryService.getNames(); assertNotNull(registered); System.out.println(registered); assertTrue(registered.size() == 1); assertTrue(registered.contains("threadDeadlockHealthCheck")); }

Target:
public void shouldRegisterDefaultHealthCheck() { Set<String> registered = healthCheckRegistryService.getNames(); assertNotNull(registered); assertEquals(1, registered.size()); assertTrue(registered.contains("threadDeadlockHealthCheck")); }
Source:
private void submit(long workerId, JobCommand.Builder command) { if (!mWorkerIdToPendingCommands.containsKey(workerId)) { mWorkerIdToPendingCommands.put(workerId, Lists.newArrayList()); } mWorkerIdToPendingCommands.get(workerId).add(command.build()); }

Target:
private synchronized void submit(long workerId, JobCommand.Builder command) { if (!mWorkerIdToPendingCommands.containsKey(workerId)) { mWorkerIdToPendingCommands.put(workerId, Lists.newArrayList()); } mWorkerIdToPendingCommands.get(workerId).add(command.build()); }