auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void createDestinationBondDefinitionsAndCopyAttachments() { <START> Map<String, Bond> sourceBondsByName = sourceMapper.calcBondsByName(); Map<String, Bond> destinationBondsByName = destinationMapper.calcBondsByName(); <END> for (Map.Entry<String, List<String>> bondEntry : destinationBondSlavesByName.entrySet()) { String bondName = bondEntry.getKey(); Bond sourceBond = sourceBondsByName.get(bondName); CreateOrUpdateBond createOrUpdateBond = createBond(bondName, bondEntry.getValue(), sourceBond.getBondOptions()); if (destinationBondsByName.containsKey(bondName)) { Bond destinationBond = destinationBondsByName.get(bondName); Guid bondId = destinationBond.getId(); bondsToRemove.remove(bondId); if (destinationBond.getIsManagement()) { List<String> bondNames = new ArrayList<>(destinationBondSlavesByName.keySet()); createOrUpdateBond.setName(findNextAvailableBondName(bondNames)); } else { createOrUpdateBond.setId(bondId); } } bondsToApply.add(createOrUpdateBond); attachmentsToApply.addAll(copyRelevantPartsFromNetworkAttachmentsAndModify(sourceBond.getId(), createOrUpdateBond.getName())); } }</code><technical_language>isnt this duplication? call mapper c'tor</technical_language>

Target:
private void createDestinationBondDefinitionsAndCopyAttachments() { for (Map.Entry<String, List<String>> bondEntry : destinationBondSlavesByName.entrySet()) { String bondName = bondEntry.getKey(); Bond sourceBond = sourceMapper.getBondByName(bondName); CreateOrUpdateBond createOrUpdateBond = createBond(bondName, bondEntry.getValue(), sourceBond.getBondOptions()); Bond destinationBond = destinationMapper.getBondByName(bondName); if (destinationBond != null) { Guid bondId = destinationBond.getId(); bondsToRemove.remove(bondId); if (destinationBond.getIsManagement()) { List<String> bondNames = new ArrayList<>(destinationBondSlavesByName.keySet()); createOrUpdateBond.setName(findNextAvailableBondName(bondNames)); } else { createOrUpdateBond.setId(bondId); } } bondsToApply.add(createOrUpdateBond); attachmentsToApply.addAll(copyRelevantPartsFromNetworkAttachmentsAndModify(sourceBond.getId(), createOrUpdateBond.getName())); } }
Source:
<code>public void onLoadFinished(Loader<Cursor> loader, Cursor data) { data.moveToFirst(); route.buildFromCursor(data, DBAdapter.getInstance()); stops = route.getStops(); int currentPosition = predictionViewPager.getCurrentItem(); int realPosition = stopViewPagerAdapter.getRealPosition(currentPosition); stopViewPagerAdapter.updatePredictions(realPosition, stops.get(realPosition).getPredictions()); int previousPosition = realPosition - 1; <START> if (previousPosition == -1) { <END> previousPosition = stops.size(); } stopViewPagerAdapter.updatePredictions(previousPosition, stops.get(previousPosition).getPredictions()); int nextPosition = realPosition + 1; if (nextPosition >= stops.size()) { nextPosition = 0; } stopViewPagerAdapter.updatePredictions(nextPosition, stops.get(nextPosition).getPredictions()); updateMapItems((ArrayList) route.getVehicles(), false); }</code><technical_language>sense modulo operator handle wrapping of stops int previousPosition = --realPosition % stops.size();</technical_language>

Target:
public void onLoadFinished(Loader<Cursor> loader, Cursor data) { data.moveToFirst(); route.buildFromCursor(data, DBAdapter.getInstance()); stops = route.getStops(); int currentPosition = predictionViewPager.getCurrentItem(); int realPosition = stopViewPagerAdapter.getRealPosition(currentPosition); stopViewPagerAdapter.updatePredictions(realPosition, stops.get(realPosition).getPredictions()); int previousPosition = (realPosition - 1) % stops.size(); if (previousPosition < 0) { previousPosition += stops.size(); } stopViewPagerAdapter.updatePredictions(previousPosition, stops.get(previousPosition).getPredictions()); int nextPosition = (realPosition + 1) % stops.size(); stopViewPagerAdapter.updatePredictions(nextPosition, stops.get(nextPosition).getPredictions()); updateMapItems((ArrayList) route.getVehicles(), false); }
Source:
<code>public boolean isNoexcept(boolean inCalledContext) { ICPPFunction overload = getOverload(); if (overload != null) { <START> return EvalUtil.evaluateNoexceptSpecifier(overload.getType().getNoexceptSpecifier()); <END> } return fArg1.isNoexcept(inCalledContext) && fArg2.isNoexcept(inCalledContext); }</code><technical_language>If overload result (overload is noexcept) && (arg1 is noexcept) && (arg2 is noexcept)</technical_language>

Target:
public boolean isNoexcept(boolean inCalledContext) { ICPPFunction overload = getOverload(); if (overload != null) { if (!EvalUtil.evaluateNoexceptSpecifier(overload.getType().getNoexceptSpecifier())) return false; } return fArg1.isNoexcept(inCalledContext) && fArg2.isNoexcept(inCalledContext); }
Source:
<code>public void createTable(ConnectorSession session, ConnectorTableMetadata tableMetadata, boolean ignoreExisting) { ConnectorTableMetadata existingTable = tables.putIfAbsent(tableMetadata.getTable(), tableMetadata); if (existingTable != null && !ignoreExisting) { <START> throw new IllegalArgumentException(format("Table %s already exists", tableMetadata.getTable())); <END> } }</code><technical_language>message format match renameTable()</technical_language>

Target:
public void createTable(ConnectorSession session, ConnectorTableMetadata tableMetadata, boolean ignoreExisting) { ConnectorTableMetadata existingTable = tables.putIfAbsent(tableMetadata.getTable(), tableMetadata); if (existingTable != null && !ignoreExisting) { throw new IllegalArgumentException("Target table already exists: " + tableMetadata.getTable()); } }
Source:
<code>public final Method setAccessible() { try { AccessPermissionChecker.checkAccessPermission(cachedMethod); } catch (AccessControlException ex) { <START> throw new IllegalArgumentException("Illegal access to method" + cachedMethod.getName()); <END> } return cachedMethod; }</code><technical_language>arguments this method IllegalArgumentException right. good remove try/catch wrap in a GroovyRuntimeException (to capture cachedMethod.getName)</technical_language>

Target:
public final Method setAccessible() { AccessPermissionChecker.checkAccessPermission(cachedMethod); return cachedMethod; }
Source:
<code><START> private byte[] deserialize(NamedKey key, byte[] bytes) <END> { final byte[] data = transcoder.decompress(bytes); final ByteBuffer buf = ByteBuffer.wrap(data); final int keyLength = buf.getInt(); final byte[] keyBytes = new byte[keyLength]; buf.get(keyBytes); final byte[] value = new byte[buf.remaining()]; buf.get(value); Preconditions.checkState(Arrays.equals(keyBytes, key.toByteArray()), "Keys do not match, possible hash collision?"); return value; }</code><technical_language>here, want move some of common memcached / redis cache code druid-processing reuse it</technical_language>

Target:
private byte[] deserialize(NamedKey key, byte[] bytes) { final byte[] data = transcoder.decompress(bytes); return CacheImplUtils.deserializeValue(key, data); }
Source:
<code>private void addParentLinksRecursive(Process child, LinkedList<DefaultTreeNode> result) { Process parent = child.getParent(); if (Objects.nonNull(parent)) { URI uri = ServiceManager.getProcessService().getMetadataFileUri(parent); DefaultTreeNode tree = new DefaultTreeNode(); tree.setExpanded(true); try { List<IncludedStructuralElement> includedStructuralElementList = determineIncludedStructuralElementPathToChildRecursive( ServiceManager.getMetsService().loadWorkpiece(uri).getRootElement(), child.getId()); DefaultTreeNode parentNode = tree; if (Objects.isNull(includedStructuralElementList)) { new DefaultTreeNode(new StructureTreeNode(this, parent.getTitle(), true, true, parent), tree); } else { for (IncludedStructuralElement includedStructuralElement : includedStructuralElementList) { StructuralElementViewInterface structuralElementView = dataEditor.getRuleset() .getStructuralElementView(includedStructuralElement.getType(), dataEditor.getAcquisitionStage(), dataEditor.getPriorityList()); parentNode = new DefaultTreeNode( new StructureTreeNode(this, structuralElementView.getLabel(), false, true, null), parentNode); parentNode.setExpanded(true); } } } catch (IOException e) { Helper.setErrorMessage("metadataReadError", e.getMessage(), logger, e); new DefaultTreeNode(new StructureTreeNode(this, parent.getTitle(), true, true, parent), tree); } result.addFirst(tree); <START> addParentLinksRecursive(parent, result); <END> } }</code><technical_language>brain-overload Reduce complexity of this method</technical_language>

Target:
private void addParentLinksRecursive(Process child, LinkedList<DefaultTreeNode> result) { Process parent = child.getParent(); if (Objects.isNull(parent)) { return; } URI uri = ServiceManager.getProcessService().getMetadataFileUri(parent); DefaultTreeNode tree = new DefaultTreeNode(); tree.setExpanded(true); try { IncludedStructuralElement rootElement = ServiceManager.getMetsService().loadWorkpiece(uri).getRootElement(); List<IncludedStructuralElement> includedStructuralElementList = determineIncludedStructuralElementPathToChildRecursive(rootElement, child.getId()); DefaultTreeNode parentNode = tree; if (includedStructuralElementList.isEmpty()) { addTreeNode(parent.getTitle(), true, true, parent, tree); } else { for (IncludedStructuralElement includedStructuralElement : includedStructuralElementList) { parentNode = addTreeNode(includedStructuralElement.getType(), true, null, parentNode); } } } catch (IOException e) { Helper.setErrorMessage("metadataReadError", e.getMessage(), logger, e); addTreeNode(parent.getTitle(), true, true, parent, tree); } result.addFirst(tree); addParentLinksRecursive(parent, result); }
Source:
<code><START> public Surface<Double, Double, DoubleMatrix1D> getParameterSensitivitySurface(final DoubleMatrix1D modelParameters) { <END> final BasisFunctionAggregation<double[]> bSpline = new BasisFunctionAggregation<>(_bSplines, modelParameters.getData()); final Function2D<Double, DoubleMatrix1D> func = new Function2D<Double, DoubleMatrix1D>() { @Override public DoubleMatrix1D evaluate(final Double t, final Double k) { return bSpline.weightSensitivity(new double[] {t, k }); } }; return new FunctionalSurface<>(func); }</code><technical_language>Check args</technical_language>

Target:
public Surface<Double, Double, DoubleMatrix1D> getParameterSensitivitySurface(final DoubleMatrix1D modelParameters) { ArgumentChecker.notNull(modelParameters, "modelParameters"); final BasisFunctionAggregation<double[]> bSpline = new BasisFunctionAggregation<>(_bSplines, modelParameters.getData()); final Function2D<Double, DoubleMatrix1D> func = new Function2D<Double, DoubleMatrix1D>() { @Override public DoubleMatrix1D evaluate(final Double t, final Double k) { return bSpline.weightSensitivity(new double[] {t, k }); } }; return new FunctionalSurface<>(func); }
Source:
<code>public static String invertSortKey(String sk) { if (sk.equalsIgnoreCase("z")) { return "/"; <START> } <END> StringBuilder inv = new StringBuilder(16); inv.setLength(16); formatHexLong(inv, -1l - parseUnsignedHex(sk)); return inv.toString(); }</code><technical_language>For completeness invert '/' 'z'</technical_language>

Target:
public static String invertSortKey(String sk) { if (sk.equalsIgnoreCase("z")) { return "/"; } else if (sk.equalsIgnoreCase("/")) { return "z"; } StringBuilder inv = new StringBuilder(16); inv.setLength(16); formatHexLong(inv, -1l - parseUnsignedHex(sk)); return inv.toString(); }
Source:
<code>private void approveOne(final PatchSet.Id patchSetId) throws NoSuchChangeException, OrmException, EmailException, Failure { <START> final Change.Id changeId = patchSetId.getParentKey(); <END> if (changeComment == null) { changeComment = ""; } Set<ApprovalCategoryValue.Id> aps = new HashSet<ApprovalCategoryValue.Id>(); for (ApproveOption ao : optionList) { Short v = ao.value(); if (v != null) { aps.add(new ApprovalCategoryValue.Id(ao.getCategoryId(), v)); } } try { publishCommentsFactory.create(patchSetId, changeComment, aps, forceMessage).call(); if (abandonChange) { final ReviewResult result = abandonChangeFactory.create( patchSetId, changeComment).call(); handleReviewResultErrors(result); } else if (restoreChange) { final ReviewResult result = restoreChangeFactory.create( patchSetId, changeComment).call(); handleReviewResultErrors(result); } if (submitChange) { final ReviewResult result = submitFactory.create(patchSetId).call(); handleReviewResultErrors(result); } } catch (InvalidChangeOperationException e) { throw error(e.getMessage()); } catch (IllegalStateException e) { throw error(e.getMessage()); } if (publishPatchSet) { final ReviewResult result = publishDraftFactory.create(patchSetId).call(); handleReviewResultErrors(result); } else if (deleteDraftPatchSet) { final ReviewResult result = deleteDraftPatchSetFactory.create(patchSetId).call(); handleReviewResultErrors(result); } }</code><technical_language>This variable is anymore removed</technical_language>

Target:
private void approveOne(final PatchSet.Id patchSetId) throws NoSuchChangeException, OrmException, EmailException, Failure { if (changeComment == null) { changeComment = ""; } Set<ApprovalCategoryValue.Id> aps = new HashSet<ApprovalCategoryValue.Id>(); for (ApproveOption ao : optionList) { Short v = ao.value(); if (v != null) { aps.add(new ApprovalCategoryValue.Id(ao.getCategoryId(), v)); } } try { publishCommentsFactory.create(patchSetId, changeComment, aps, forceMessage).call(); if (abandonChange) { final ReviewResult result = abandonChangeFactory.create( patchSetId, changeComment).call(); handleReviewResultErrors(result); } else if (restoreChange) { final ReviewResult result = restoreChangeFactory.create( patchSetId, changeComment).call(); handleReviewResultErrors(result); } if (submitChange) { final ReviewResult result = submitFactory.create(patchSetId).call(); handleReviewResultErrors(result); } } catch (InvalidChangeOperationException e) { throw error(e.getMessage()); } catch (IllegalStateException e) { throw error(e.getMessage()); } if (publishPatchSet) { final ReviewResult result = publishDraftFactory.create(patchSetId).call(); handleReviewResultErrors(result); } else if (deleteDraftPatchSet) { final ReviewResult result = deleteDraftPatchSetFactory.create(patchSetId).call(); handleReviewResultErrors(result); } }
Source:
<code>private void sendPage(String page, HttpServerRequest request, HttpServerResponse response) throws HttpAuthenticationException { if (response.forward(page)) { return; } HttpScope application = request.getScope(Scope.APPLICATION); if (application != null && application.supportsResources()) { try (InputStream pageStream = application.getResource(page)) { if (pageStream != null) { OutputStream responseStream = response.getOutputStream(); if (responseStream != null) { byte[] content = new byte[1024]; int length; while ((length = pageStream.read(content)) > 0) { responseStream.write(content, 0, length); } <START> response.setStatusCode(OK); <END> return; } } } catch (IOException e) { throw new HttpAuthenticationException(e); } } URI requestURI = request.getRequestURI(); StringBuilder sb = new StringBuilder(); String scheme = requestURI.getScheme(); sb.append(scheme); sb.append("://"); sb.append(requestURI.getHost()); int port = requestURI.getPort(); if (appendPort(scheme, port)) { sb.append(':').append(port); } sb.append(contextPath); sb.append(page); sendRedirect(response, sb.toString()); }</code><technical_language>FORM authentication is need able support this framework in conjunction other authentication mechanisms, this stage SPI released in a .Final of WildFly Elytron WildFly is other custom mechanism implementations out implemented based current behaviour of framework</technical_language>

Target:
private void sendPage(String page, HttpServerRequest request, HttpServerResponse response) throws HttpAuthenticationException { if (response.forward(page)) { return; } HttpScope application = request.getScope(Scope.APPLICATION); if (application != null && application.supportsResources()) { try (InputStream pageStream = application.getResource(page)) { if (pageStream != null) { OutputStream responseStream = response.getOutputStream(); if (responseStream != null) { byte[] content = new byte[1024]; int length; while ((length = pageStream.read(content)) > 0) { responseStream.write(content, 0, length); } return; } } } catch (IOException e) { throw new HttpAuthenticationException(e); } } URI requestURI = request.getRequestURI(); StringBuilder sb = new StringBuilder(); String scheme = requestURI.getScheme(); sb.append(scheme); sb.append("://"); sb.append(requestURI.getHost()); int port = requestURI.getPort(); if (appendPort(scheme, port)) { sb.append(':').append(port); } sb.append(contextPath); sb.append(page); sendRedirect(response, sb.toString()); }
Source:
<code>public Image imageFor(Entity entity, int facing, int secondaryPos) { EntityImage entityImage = getFromCache(entity, secondaryPos); if (entityImage == null) { <START> System.err.println("Unable to load image for entity: " + entity.getShortNameRaw()); END> return getGenericImage(entity, -1, mechTileset); } return entityImage.getFacing(facing); }</code><technical_language>stop calling out system.println useful this file replace calls actual logging</technical_language>

Target:
public Image imageFor(Entity entity, int facing, int secondaryPos) { EntityImage entityImage = getFromCache(entity, secondaryPos); if (entityImage == null) { DefaultMmLogger.getInstance().error(getClass(), "imageFor()", "Unable to load image for entity: " + entity.getShortNameRaw()); return getGenericImage(entity, -1, mechTileset); } return entityImage.getFacing(facing); }
Source:
<code>public static List<PostAggregator> prepareAggregations( <START> List<String> otherOutputNames, <END> List<AggregatorFactory> aggFactories, List<PostAggregator> postAggs ) { Preconditions.checkNotNull(aggFactories, "aggregations cannot be null"); final Map<String, AggregatorFactory> aggsFactoryMap = Maps.newHashMap(); for (AggregatorFactory aggFactory : aggFactories) { Preconditions.checkArgument(!aggsFactoryMap.containsKey(aggFactory.getName()), "[%s] already defined", aggFactory.getName()); aggsFactoryMap.put(aggFactory.getName(), aggFactory); } if (postAggs != null && !postAggs.isEmpty()) { final Set<String> combinedOutputNames = Sets.newHashSet(aggsFactoryMap.keySet()); combinedOutputNames.addAll(otherOutputNames); List<PostAggregator> decorated = Lists.newArrayListWithExpectedSize(postAggs.size()); for (final PostAggregator postAgg : postAggs) { final Set<String> dependencies = postAgg.getDependentFields(); final Set<String> missing = Sets.difference(dependencies, combinedOutputNames); Preconditions.checkArgument( missing.isEmpty(), "Missing fields [%s] for postAggregator [%s]", missing, postAgg.getName() ); Preconditions.checkArgument(combinedOutputNames.add(postAgg.getName()), "[%s] already defined", postAgg.getName()); decorated.add(postAgg.decorate(aggsFactoryMap)); } return decorated; } return postAggs; }</code><technical_language>otherOutputNames broad. Docs useful understand this method</technical_language>

Target:
public static List<PostAggregator> prepareAggregations( List<String> otherOutputNames, List<AggregatorFactory> aggFactories, List<PostAggregator> postAggs ) { Preconditions.checkNotNull(otherOutputNames, "otherOutputNames cannot be null"); Preconditions.checkNotNull(aggFactories, "aggregations cannot be null"); final Set<String> combinedOutputNames = new HashSet<>(); combinedOutputNames.addAll(otherOutputNames); final Map<String, AggregatorFactory> aggsFactoryMap = new HashMap<>(); for (AggregatorFactory aggFactory : aggFactories) { Preconditions.checkArgument( combinedOutputNames.add(aggFactory.getName()), "[%s] already defined", aggFactory.getName() ); aggsFactoryMap.put(aggFactory.getName(), aggFactory); } if (postAggs != null && !postAggs.isEmpty()) { List<PostAggregator> decorated = Lists.newArrayListWithExpectedSize(postAggs.size()); for (final PostAggregator postAgg : postAggs) { final Set<String> dependencies = postAgg.getDependentFields(); final Set<String> missing = Sets.difference(dependencies, combinedOutputNames); Preconditions.checkArgument( missing.isEmpty(), "Missing fields [%s] for postAggregator [%s]", missing, postAgg.getName() ); Preconditions.checkArgument( combinedOutputNames.add(postAgg.getName()), "[%s] already defined", postAgg.getName() ); decorated.add(postAgg.decorate(aggsFactoryMap)); } return decorated; } return postAggs; }
Source:
<code>public boolean equals(Object obj) { <START> return HttpServerModule.class.equals(obj.getClass()); <END> }</code><technical_language>getClass().equals(obj.getClass())? nit: contract for equals check for obj null avoid NPE</technical_language>

Target:
public boolean equals(Object obj) { return getClass().equals(obj.getClass()); }
Source:
<code>public void testGroupExistence() throws Exception { UsersInitServlet servlet = new UsersInitServlet(); servlet.doGet(context.request(), context.response()); <START> LOG.info(context.response().getOutputAsString()); <END> JsonObject json = new JsonParser().parse(context.response().getOutputAsString()).getAsJsonObject(); JsonObject options = json.get("options").getAsJsonObject(); JsonArray groups = options.get("groups").getAsJsonArray(); assertEquals(2,groups.size()); JSONAssert.assertEquals("[allusers, users]", groups.toString(),false); }</code><technical_language>LOG</technical_language>

Target:
public void testGroupExistence() throws Exception { UsersInitServlet servlet = new UsersInitServlet(); servlet.doGet(context.request(), context.response()); JsonObject json = new JsonParser().parse(context.response().getOutputAsString()).getAsJsonObject(); JsonObject options = json.get("options").getAsJsonObject(); JsonArray groups = options.get("groups").getAsJsonArray(); assertEquals(2,groups.size()); JSONAssert.assertEquals("[allusers, users]", groups.toString(),false); }
Source:
<code>private List<Branch> getCommitBranches(RevCommit commit, ListMode mode) throws GitAPIException { List<Branch> branchList = new ArrayList<Branch>(); List<Ref> branches = getGit().branchList() .setListMode(mode) .setContains(commit.getName()) .call(); <START> for (int i = 0; i < branches.size(); i++) { <END> branchList.add(createDto(Branch.class).withName(branches.get(i).getName())); } return branchList; }</code><technical_language>do fori loop instead of foreach? BTW I stream API</technical_language>

Target:
private List<Branch> getCommitBranches(RevCommit commit, ListMode mode) throws GitAPIException { List<Branch> branchList = new ArrayList<Branch>(); List<Ref> branches = getGit().branchList() .setListMode(mode) .setContains(commit.getName()) .call(); branches.forEach(ref->branchList.add(createDto(Branch.class).withName(ref.getName()))); return branchList; }
Source:
<code>@Override public Expression implement(RexToLixTranslator translator, Expression inputEnumerable, RexCall call, PhysType inputPhysType, PhysType outputPhysType) { Expression intervalExpression = translator.translate(call.getOperands().get(2)); Expression intervalExpression2 = translator.translate(call.getOperands().get(3)); <START> RexCall descriptor = (RexCall) call.getOperands().get(1); <END> List<Expression> translatedOperands = new ArrayList<>(); Expression wmColIndexExpr = Expressions.constant(((RexInputRef) descriptor.getOperands().get(0)).getIndex()); translatedOperands.add(wmColIndexExpr); translatedOperands.add(intervalExpression); translatedOperands.add(intervalExpression2); return Expressions.call( BuiltInMethod.HOPPING.method, Expressions.list( Expressions.call(inputEnumerable, BuiltInMethod.ENUMERABLE_ENUMERATOR.method), translatedOperands.get(0), translatedOperands.get(1), translatedOperands.get(2))); }</code><technical_language>Give intervalExpression more meaningful name. e.g. windowSize slidingInterval</technical_language>

Target:
@Override public Expression implement(RexToLixTranslator translator, Expression inputEnumerable, RexCall call, PhysType inputPhysType, PhysType outputPhysType) { Expression slidingInterval = translator.translate(call.getOperands().get(1)); Expression windowSize = translator.translate(call.getOperands().get(2)); RexCall descriptor = (RexCall) call.getOperands().get(0); List<Expression> translatedOperands = new ArrayList<>(); Expression wmColIndexExpr = Expressions.constant(((RexInputRef) descriptor.getOperands().get(0)).getIndex()); translatedOperands.add(wmColIndexExpr); translatedOperands.add(slidingInterval); translatedOperands.add(windowSize); return Expressions.call( BuiltInMethod.HOPPING.method, Expressions.list( Expressions.call(inputEnumerable, BuiltInMethod.ENUMERABLE_ENUMERATOR.method), translatedOperands.get(0), translatedOperands.get(1), translatedOperands.get(2))); }
Source:
<code>public Construct exec(Target target, Environment environment, Construct... args) throws ConfigRuntimeException { MCPlayer player = environment.getEnv(CommandHelperEnvironment.class).GetPlayer(); MCWorld world = null; if(player != null) { world = player.getWorld(); } MCLocation loc = ObjectGenerator.GetGenerator().location(args[0], world, target); double temp; temp = loc.getBlock().getTemperature(); <START> return new CDouble(temp, target); <END> }</code><technical_language>In this case, combine 3 lines "return new CDouble(loc.getBlock().getTemperature(), target);</technical_language>

Target:
public Construct exec(Target target, Environment environment, Construct... args) throws ConfigRuntimeException { MCPlayer player = environment.getEnv(CommandHelperEnvironment.class).GetPlayer(); MCWorld world = null; if(player != null) { world = player.getWorld(); } MCLocation loc = ObjectGenerator.GetGenerator().location(args[0], world, target); return new CDouble(loc.getBlock().getTemperature(), target); }
Source:
<code>public void testListProperty() { testWithAllMappers(new Runnable() { @Override public void run() { TestModel model = new TestModel(); List<String> numbers = Arrays.asList("0", "1", "2", "3"); model.setSomeList(numbers); database.persist(model); model = database.fetch(TestModel.class, model.getRowId(), TestModel.PROPERTIES); assertEquals(numbers, model.getSomeList()); <START> assertEquals(numbers, model.getSomeList()); <END> } }); }</code><technical_language>Is check cache</technical_language>

Target:
public void testListProperty() { testWithAllMappers(new Runnable() { @Override public void run() { TestModel model = new TestModel(); List<String> numbers = Arrays.asList("0", "1", "2", "3"); model.setSomeList(numbers); database.persist(model); model = database.fetch(TestModel.class, model.getRowId(), TestModel.PROPERTIES); int currentFromJSONCount = currentMapper.fromJSONCount; assertFalse(model.hasTransitory(transitoryKeyForProperty(TestModel.SOME_LIST))); assertEquals(numbers, model.getSomeList()); assertEquals(currentFromJSONCount + 1, currentMapper.fromJSONCount); assertTrue(model.hasTransitory(transitoryKeyForProperty(TestModel.SOME_LIST))); assertEquals(numbers, model.getSomeList()); assertEquals(currentFromJSONCount + 1, currentMapper.fromJSONCount); } }); }
Source:
<code>public void addStorage( IAEItemStack option ) { if( this.isStackNull( option ) ) { return; } final IAEItemStack st = this.getItemRecord( option.getItem() ).get( option ); if( st != null ) { st.incStackSize( option.getStackSize() ); return; } <START> final IAEItemStack opt = (IAEItemStack) option.copy(); <END> this.putItemRecord( opt ); }</code><technical_language>agreed, type do StackType anymore</technical_language>

Target:
public void addStorage( IAEItemStack option ) { if( option == null ) { return; } final IAEItemStack st = this.getItemRecord( option.getItem() ).get( option ); if( st != null ) { st.incStackSize( option.getStackSize() ); return; } final IAEItemStack opt = option.copy(); this.putItemRecord( opt ); }
Source:
<code>public void githubProfileScraperOrgTest() { String profile = "fossasia"; String shortDescription = "Open Technologies in Asia"; String userName = "fossasia"; String userId = "6295529"; String location = "Singapore"; String specialLink = " <LINK_0>"; SusiThought response = GithubProfileScraper.scrapeGithub(profile); JSONObject fetchedProfile = (JSONObject)response.getData().get(0); assertTrue(fetchedProfile.has("short_description")); assertThat(fetchedProfile.getString("short_description"), is(shortDescription)); assertTrue(fetchedProfile.has("user_name")); assertThat(fetchedProfile.getString("user_name"), is(userName)); assertTrue(fetchedProfile.has("user_id")); assertThat(fetchedProfile.getString("user_id"), is(userId)); assertTrue(fetchedProfile.has("location")); assertThat(fetchedProfile.getString("location"), is(location)); <START> assertTrue(fetchedProfile.has("special_link")); <END> }</code><technical_language>hey , nice job!!! please assertEquals for strings assertThat, message for strings</technical_language>

Target:
public void githubProfileScraperOrgTest() { String profile = "fossasia"; String shortDescription = "Open Technologies in Asia"; String userName = "fossasia"; String userId = "6295529"; String location = "Singapore"; String specialLink = "<LINK_0>"; SusiThought response = GithubProfileScraper.scrapeGithub(profile); JSONObject fetchedProfile = (JSONObject)response.getData().get(0); assertEquals(fetchedProfile.getString("short_description"), shortDescription); assertEquals(fetchedProfile.getString("user_name"), userName); assertEquals(fetchedProfile.getString("user_id"), userId); assertEquals(fetchedProfile.getString("location"), location); assertEquals(fetchedProfile.getString("special_link"), specialLink); }
Source:
<code>public KeyStore getTrustStore() throws Exception{ if(tenantId != MultitenantConstants.SUPER_TENANT_ID) throw new CarbonException("Permission denied for accessing trust store"); KeyStore trustStore = null; ServerConfiguration serverConfiguration = ServerConfiguration.getInstance(); String file = new File(serverConfiguration .getFirstProperty(RegistryResources.SecurityManagement.SERVER_TRUSTSTORE_FILE)) .getAbsolutePath(); KeyStore store = KeyStore.getInstance(serverConfiguration .getFirstProperty(RegistryResources.SecurityManagement.SERVER_TRUSTSTORE_TYPE)); String password = serverConfiguration .getFirstProperty(RegistryResources.SecurityManagement.SERVER_TRUSTSTORE_PASSWORD); FileInputStream in = null; try { in = new FileInputStream(file); store.load(in, password.toCharArray()); trustStore = store; } catch (Exception e) { <START> e.printStackTrace(); <END> } finally { if (in != null) { in.close(); } } return trustStore; }</code><technical_language>Remove e.printStackTrace, throw exception log it</technical_language>

Target:
public KeyStore getTrustStore() throws Exception { if(tenantId != MultitenantConstants.SUPER_TENANT_ID) throw new CarbonException("Permission denied for accessing trust store"); KeyStore trustStore = null; ServerConfiguration serverConfiguration = ServerConfiguration.getInstance(); String file = new File(serverConfiguration .getFirstProperty(RegistryResources.SecurityManagement.SERVER_TRUSTSTORE_FILE)) .getAbsolutePath(); KeyStore store = KeyStore.getInstance(serverConfiguration .getFirstProperty(RegistryResources.SecurityManagement.SERVER_TRUSTSTORE_TYPE)); String password = serverConfiguration .getFirstProperty(RegistryResources.SecurityManagement.SERVER_TRUSTSTORE_PASSWORD); FileInputStream in = null; try { in = new FileInputStream(file); store.load(in, password.toCharArray()); trustStore = store; } catch (Exception e) { throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { throw e; } } } return trustStore; }
Source:
<code>public HiveMetastoreClient createMetastoreClient() { List<HostAndPort> metastores = new ArrayList<>(addresses); Collections.shuffle(metastores.subList(1, metastores.size())); TException lastException = null; <START> for (HostAndPort metastore : metastores) { <END> try { HiveMetastoreClient hiveMetastoreClient = clientFactory.create(metastore); if (!isNullOrEmpty(hiveUserName)) { hiveMetastoreClient.setUGI(hiveUserName, new ArrayList<String>()); } return hiveMetastoreClient; } catch (TException e) { lastException = e; } } if (!isNullOrEmpty(hiveUserName)) { throw new PrestoException(HIVE_METASTORE_ERROR, format("Failed connecting to Hive metastore: %s , HiveUserName is %s ", addresses, hiveUserName), lastException); } throw new PrestoException(HIVE_METASTORE_ERROR, "Failed connecting to Hive metastore: " + addresses, lastException); }</code><technical_language>If get a TException a TTransportException setUGI call, is a permanent error (metastore allow user). Do want try next metastore in case, abort immediately</technical_language>

Target:
public HiveMetastoreClient createMetastoreClient() { List<HostAndPort> metastores = new ArrayList<>(addresses); Collections.shuffle(metastores.subList(1, metastores.size())); TException lastException = null; for (HostAndPort metastore : metastores) { try { HiveMetastoreClient hiveMetastoreClient = clientFactory.create(metastore); if (!isNullOrEmpty(metastoreUsername)) { hiveMetastoreClient.setUGI(metastoreUsername); } return hiveMetastoreClient; } catch (TException e) { lastException = e; } } throw new PrestoException(HIVE_METASTORE_ERROR, "Failed connecting to Hive metastore: " + addresses, lastException); }
Source:
<code>public RHSHistory getHistory(String lhs) { MRUSet rhsCache= (MRUSet) fLHSCache.get(lhs); if (rhsCache != null) { int count= rhsCache.size(); LinkedHashMap history= new LinkedHashMap((int) (count / 0.75)); int rank= 1; for (Iterator it= rhsCache.iterator(); it.hasNext(); rank++) { String type= (String) it.next(); <START> history.put(type, Integer.valueOf(rank)); <END> } return new RHSHistory(history); } return EMPTY_HISTORY; }</code><technical_language>autoboxing</technical_language>

Target:
public RHSHistory getHistory(String lhs) { MRUSet rhsCache= (MRUSet) fLHSCache.get(lhs); if (rhsCache != null) { int count= rhsCache.size(); LinkedHashMap history= new LinkedHashMap((int) (count / 0.75)); int rank= 1; for (Iterator it= rhsCache.iterator(); it.hasNext(); rank++) { String type= (String) it.next(); history.put(type, rank); } return new RHSHistory(history); } return EMPTY_HISTORY; }
Source:
<code>public Response intercept(final Chain chain) throws IOException { final Response response = chain.proceed(chain.request()); final Version appLatestVersion; { final String appLatestVersionString = response.header(HEADER_APP_LATEST_VERSION); if (appLatestVersionString == null) { appLatestVersion = null; } else { try { appLatestVersion = new Version(appLatestVersionString); } catch (ParseException e) { <START> logger.error(e); <END> return response; } } } final Date lastSupportedDate = DateUtil.convertToDate( response.header(HEADER_APP_VERSION_LAST_SUPPORTED_DATE)); final boolean isUnsupported = response.code() == HttpStatus.UPGRADE_REQUIRED; NewVersionAvailableEvent.post(appLatestVersion, lastSupportedDate, isUnsupported); return response; }</code><technical_language>log this error crashlytics, is broken. pass true 2nd parameter</technical_language>

Target:
public Response intercept(final Chain chain) throws IOException { final Response response = chain.proceed(chain.request()); final Version appLatestVersion; { final String appLatestVersionString = response.header(HEADER_APP_LATEST_VERSION); if (appLatestVersionString == null) { appLatestVersion = null; } else { try { appLatestVersion = new Version(appLatestVersionString); } catch (ParseException e) { logger.error(e, true); return response; } } } final Date lastSupportedDate = DateUtil.convertToDate( response.header(HEADER_APP_VERSION_LAST_SUPPORTED_DATE)); final boolean isUnsupported = response.code() == HttpStatus.UPGRADE_REQUIRED; NewVersionAvailableEvent.post(appLatestVersion, lastSupportedDate, isUnsupported); return response; }
Source:
<code>private InputStream openStream(Path path, long start) throws IOException { try { return retry() .maxAttempts(maxAttempts) .exponentialBackoff(BACKOFF_MIN_SLEEP, maxBackoffTime, maxRetryTime, 2.0) .stopOn(InterruptedException.class, UnrecoverableS3OperationException.class) .onRetry(STATS::newGetObjectRetry) .run("getS3Object", () -> { try { GetObjectRequest request = new GetObjectRequest(host, keyFromPath(path)).withRange(start); return s3.getObject(request).getObjectContent(); } catch (RuntimeException e) { STATS.newGetObjectError(); if (e instanceof AmazonS3Exception) { switch (((AmazonS3Exception) e).getStatusCode()) { case SC_REQUESTED_RANGE_NOT_SATISFIABLE: return new ByteArrayInputStream(new byte[0]); case SC_FORBIDDEN: ListObjectsV2Result result = s3.listObjectsV2(host, keyFromPath(path)); <START> boolean isGlacierObject = result.getObjectSummaries().stream() <END> .anyMatch(summary -> summary.getStorageClass().equals(StorageClass.Glacier.toString())); if (isGlacierObject) { return new ByteArrayInputStream(new byte[0]); } case SC_NOT_FOUND: case SC_BAD_REQUEST: throw new UnrecoverableS3OperationException(path, e); } } throw e; } }); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (Exception e) { throwIfInstanceOf(e, IOException.class); throwIfUnchecked(e); throw new RuntimeException(e); } }</code><technical_language>do this filtering in listPrefix()? information there</technical_language>

Target:
private InputStream openStream(Path path, long start) throws IOException { try { return retry() .maxAttempts(maxAttempts) .exponentialBackoff(BACKOFF_MIN_SLEEP, maxBackoffTime, maxRetryTime, 2.0) .stopOn(InterruptedException.class, UnrecoverableS3OperationException.class) .onRetry(STATS::newGetObjectRetry) .run("getS3Object", () -> { try { GetObjectRequest request = new GetObjectRequest(host, keyFromPath(path)).withRange(start); return s3.getObject(request).getObjectContent(); } catch (RuntimeException e) { STATS.newGetObjectError(); if (e instanceof AmazonS3Exception) { switch (((AmazonS3Exception) e).getStatusCode()) { case SC_REQUESTED_RANGE_NOT_SATISFIABLE: return new ByteArrayInputStream(new byte[0]); case SC_FORBIDDEN: case SC_NOT_FOUND: case SC_BAD_REQUEST: throw new UnrecoverableS3OperationException(path, e); } } throw e; } }); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (Exception e) { throwIfInstanceOf(e, IOException.class); throwIfUnchecked(e); throw new RuntimeException(e); } }
Source:
<code><START> public static Class<?> getStackClass1() { <END> return getStackClass2(); }</code><technical_language>This implemented (not tested): StackTraceElement[] stackTrace = getThreadStackTrace(Thread.currentThread()); return Class.forName(stackTrace[2].getClassName()); Embedded native code faster</technical_language>

Target:
public static Class<?> getStackClass1() throws ClassNotFoundException { return getStackClass2(); }
Source:
<code>private String setParameter(HttpMessage msg, NameValuePair originalPair, String value) { <START> String contentType = msg.getRequestHeader().getHeader(HttpHeader.CONTENT_TYPE); <END> String boundary = getBoundary(contentType); StringBuilder newBodyBuilder = new StringBuilder(msg.getRequestBody().toString()); int idx = originalPair.getPosition() -1; MultipartFormParameter mpPart = multiPartParams.get(idx); if (LOGGER.isDebugEnabled()) { LOGGER.debug("i: " + idx + " pos: " + originalPair.getPosition() + " S: " + mpPart.getStart() + " E: " + mpPart.getEnd()); } if (idx == originalPair.getPosition()-1) { newBodyBuilder.replace(mpPart.getStart(), mpPart.getEnd(), value); } String newBody = newBodyBuilder.toString(); msg.getRequestBody().setBody(newBody); return newBody; }</code><technical_language>removed (no longer needed), for statement</technical_language>

Target:
private String setParameter(HttpMessage msg, NameValuePair originalPair, String value) { StringBuilder newBodyBuilder = new StringBuilder(msg.getRequestBody().toString()); int idx = originalPair.getPosition() -1; MultipartFormParameter mpPart = multiPartParams.get(idx); if (LOGGER.isDebugEnabled()) { LOGGER.debug("i: " + idx + " pos: " + originalPair.getPosition() + " S: " + mpPart.getStart() + " E: " + mpPart.getEnd()); } newBodyBuilder.replace(mpPart.getStart(), mpPart.getEnd(), value); String newBody = newBodyBuilder.toString(); msg.getRequestBody().setBody(newBody); return newBody; }
Source:
<code>protected Object execute(final RebaseOperation rebase) throws ExecutionException { String jobname = getJobName(rebase); final Repository repository = rebase.getRepository(); final RebaseCommand.Operation operation = rebase.getOperation(); JobUtil.scheduleUserJob(rebase, jobname, JobFamilies.REBASE, new JobChangeAdapter() { @Override public void done(IJobChangeEvent cevent) { IStatus result = cevent.getJob().getResult(); if (operation == Operation.BEGIN && result.getSeverity() == IStatus.ERROR) { if (!repository.getRepositoryState().equals( RepositoryState.SAFE)) { try { new RebaseOperation(repository, Operation.ABORT).execute(null); } catch (CoreException e) { Activator <START> .error(UIText.AbstractRebaseCommandHandler_CleanUpFailed, <END> e); } } } if (result.getSeverity() == IStatus.CANCEL) Display.getDefault().asyncExec(new Runnable() { public void run() { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow() .getShell(); MessageDialog.openInformation(shell, dialogTitle, dialogMessage); } }); else if (result.isOK()) RebaseResultDialog.show(rebase.getResult(), repository); } }); return null; }</code><technical_language>show exception is root of problem -> multistatus this done in RebaseHelper</technical_language>

Target:
protected Object execute(final RebaseOperation rebase) throws ExecutionException { final Repository repository = rebase.getRepository(); final RebaseCommand.Operation operation = rebase.getOperation(); JobUtil.scheduleUserJob(rebase, jobname, JobFamilies.REBASE, new JobChangeAdapter() { @Override public void aboutToRun(IJobChangeEvent event) { if (operation == Operation.BEGIN && !repository.getRepositoryState().equals( RepositoryState.SAFE)) { throw new IllegalStateException( "Can't start rebase if repository state isn't SAFE"); } super.aboutToRun(event); } @Override public void done(IJobChangeEvent cevent) { IStatus result = cevent.getJob().getResult(); if (operation == Operation.BEGIN && result.getSeverity() == IStatus.ERROR) { if (!repository.getRepositoryState().equals( RepositoryState.SAFE)) { RuntimeException e = new RuntimeException( result.getException()); try { new RebaseOperation(repository, Operation.ABORT).execute(null); throw e; } catch (CoreException e1) { IStatus multiStatus = createMultiStatus(result.getException(), e1); CoreException multiStatusCoreException = new CoreException( multiStatus); throw new RuntimeException( multiStatusCoreException); } } } if (result.getSeverity() == IStatus.CANCEL) Display.getDefault().asyncExec(new Runnable() { public void run() { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow() .getShell(); MessageDialog.openInformation(shell, dialogTitle, dialogMessage); } }); else if (result.isOK()) RebaseResultDialog.show(rebase.getResult(), repository); } }); return null; }
Source:
<code>public String getDescriptionUsage() { StringBuilder sb = new StringBuilder(); sb.append("<form>Use a template to publish a document or diff the document against a different version.<br/>"); sb.append("Select Parameters<br/>"); sb.append("<li>Select Update Paragraph Numbers if authorized to update them</li>"); sb.append("<li>Choose whether or not you want the UUIDs published</li>"); <START> sb.append("<li>Select the Document Link format(s)</li>"); <END> sb.append("<li>Choose an artifact type to exclude</li>"); sb.append("<li>Select Master or Master/Slave (for SRS) template. Only use non-recursive templates</li>"); sb.append("<li>Drag &amp; Drop the IS Artifacts into the box</li>"); sb.append("<li>Decide to Publish as Diff and select WAS branch as desired</li>"); sb.append("<br/>Click the play button at the top right or in the Execute section.</form>"); return sb.toString(); }</code><technical_language>Change "Choose artifact types exclude"</technical_language>

Target:
public String getDescriptionUsage() { StringBuilder sb = new StringBuilder(); sb.append("<form>Use a template to publish a document or diff the document against a different version.<br/>"); sb.append("Select Parameters<br/>"); sb.append("<li>Select Update Paragraph Numbers if authorized to update them</li>"); sb.append("<li>Choose whether or not you want the UUIDs published</li>"); sb.append("<li>Select the Document Link format(s)</li>"); sb.append("<li>Choose artifact type(s) to exclude</li>"); sb.append("<li>Select Master or Master/Slave (for SRS) template. Only use non-recursive templates</li>"); sb.append("<li>Drag &amp; Drop the IS Artifacts into the box</li>"); sb.append("<li>Decide to Publish as Diff and select WAS branch as desired</li>"); sb.append("<br/>Click the play button at the top right or in the Execute section.</form>"); return sb.toString(); }
Source:
<code>public Map<String, String> getExtraEnvParams() { String envParams = config.get(CONFIG_EXTRA_ENV_PARAMS); if (envParams == null) { logger.info("getExtraEnvParams: No extra env params"); return null; } Map<String, String> extraEnvParamsMap = new HashMap<String, String>(); String[] pairs = envParams.split(","); logger.info("getExtraEnvParams: Extra cass params. From config :" +envParams); <START> if ( pairs.length > 0) { <END> for (int i = 0; i < pairs.length; i++) { String[] pair = pairs[i].split("="); if (pair.length > 1) { String priamKey = pair[0]; String cassKey = pair[1]; String cassVal = config.get(priamKey); logger.info("getExtraEnvParams: Start-up/ env params: Priamkey[" + priamKey + "], CassStartupKey[" + cassKey + "], Val[" + cassVal + "]"); if(!StringUtils.isBlank(cassKey) && !StringUtils.isBlank(cassVal)) { extraEnvParamsMap.put(cassKey, cassVal); } } } } return extraEnvParamsMap; }</code><technical_language>This check is redundant for-loop below</technical_language>

Target:
public Map<String, String> getExtraEnvParams() { String envParams = config.get(CONFIG_EXTRA_ENV_PARAMS); if (envParams == null) { logger.info("getExtraEnvParams: No extra env params"); return null; } Map<String, String> extraEnvParamsMap = new HashMap<String, String>(); String[] pairs = envParams.split(","); logger.info("getExtraEnvParams: Extra cass params. From config :" +envParams); for (int i = 0; i < pairs.length; i++) { String[] pair = pairs[i].split("="); if (pair.length > 1) { String priamKey = pair[0]; String cassKey = pair[1]; String cassVal = config.get(priamKey); logger.info("getExtraEnvParams: Start-up/ env params: Priamkey[" + priamKey + "], CassStartupKey[" + cassKey + "], Val[" + cassVal + "]"); if(!StringUtils.isBlank(cassKey) && !StringUtils.isBlank(cassVal)) { extraEnvParamsMap.put(cassKey, cassVal); } } } return extraEnvParamsMap; }
Source:
<code>protected List<T> peekInternal(String queue, Double min, Double max, int offset, int count) { List<T> jobInfos = Lists.newArrayList(); try (Handle handle = rdbi.open()) { Set<Tuple> tupleSet = handle.jedis().zrangeByScoreWithScores(queue, min, max, offset, count); for (Tuple tuple : tupleSet) { <START> jobInfos.add(newJobInfo(tuple.getElement(), tuple.getScore())); <END> } return jobInfos; } }</code><technical_language>creaeJobInfo</technical_language>

Target:
protected List<T> peekInternal(String queue, Double min, Double max, int offset, int count) { List<T> jobInfos = Lists.newArrayList(); try (Handle handle = rdbi.open()) { Set<Tuple> tupleSet = handle.jedis().zrangeByScoreWithScores(queue, min, max, offset, count); for (Tuple tuple : tupleSet) { jobInfos.add(createJobInfo(tuple.getElement(), tuple.getScore())); } return jobInfos; } }