auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void setUp() throws Exception{ classInstance = new urn_perun_user_facility_attribute_def_virt_defaultUnixGID(); session = mock(PerunSessionImpl.class, RETURNS_DEEP_STUBS); attrDef = session.getPerunBl().getAttributesManagerBl().getAttributeDefinition(session, AttributesManager.NS_USER_FACILITY_ATTR_VIRT + "defaultUnixGID"); dDefaultUnixGid = new Attribute(); gidNamespace = "test"; <START> groupNameNamespace = "test"; <END> prefferedUnixGroupName = new Attribute(); allowedResource = new ArrayList<>(); memberByUser = new ArrayList<>(); assignedGroupsToResource = new ArrayList<>(); groupMembers = new ArrayList<>(); basicDefaultGID = new Attribute(); facility = new Facility(1, "testFacility"); user = new User(1, "name", "surname", "middlename", "title", "title"); prefferedUnixGroupNameSelectedValueGID = new Attribute(attrDef); resource = new Resource(1, "testName", "desc", 1); member = new Member(1, 1); group = new Group("name", "desc"); allowedResource.add(resource); memberByUser.add(member); assignedGroupsToResource.add(group); groupMembers.add(member); resourceGroupName = "test1"; groupGroupName = "test2"; resourceUnixGID = 1; groupUnixGID = 2; }</code><technical_language>Try namespace names. name hide some bugs</technical_language>

Target:
public void setUp() throws Exception{ classInstance = new urn_perun_user_facility_attribute_def_virt_defaultUnixGID(); session = mock(PerunSessionImpl.class, RETURNS_DEEP_STUBS); attrDef = session.getPerunBl().getAttributesManagerBl().getAttributeDefinition(session, AttributesManager.NS_USER_FACILITY_ATTR_VIRT + "defaultUnixGID"); dDefaultUnixGid = new Attribute(); gidNamespace = "test1"; groupNameNamespace = "test2"; prefferedUnixGroupName = new Attribute(); allowedResource = new ArrayList<>(); memberByUser = new ArrayList<>(); assignedGroupsToResource = new ArrayList<>(); groupMembers = new ArrayList<>(); basicDefaultGID = new Attribute(); facility = new Facility(1, "testFacility"); user = new User(1, "name", "surname", "middlename", "title", "title"); prefferedUnixGroupNameSelectedValueGID = new Attribute(attrDef); resource = new Resource(1, "testName", "desc", 1); member = new Member(1, 1); group = new Group("name", "desc"); allowedResource.add(resource); memberByUser.add(member); assignedGroupsToResource.add(group); groupMembers.add(member); resourceGroupName = "test1"; groupGroupName = "test2"; resourceUnixGID = 1; groupUnixGID = 2; }
Source:
<code>public static Boolean extractHook(IHopper dest) { TileEntity tileEntity = dest.getWorld().getTileEntity(new BlockPos(dest.getXPos(), dest.getYPos() + 1, dest.getZPos())); if (tileEntity == null || !tileEntity.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.DOWN)) return null; IItemHandler handler = tileEntity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.DOWN); for (int i = 0; i < handler.getSlots(); i++) { ItemStack extractItem = handler.extractItem(i, 1, true); if (extractItem != null) { for (int j = 0; j < dest.getSizeInventory(); j++) { ItemStack destStack = dest.getStackInSlot(j); <START> if (destStack == null || destStack.stackSize < destStack.getMaxStackSize() && destStack.getMaxStackSize() < dest.getInventoryStackLimit() && ItemHandlerHelper.canItemStacksStack(extractItem, destStack)) <END> { extractItem = handler.extractItem(i, 1, false); if (destStack == null) dest.setInventorySlotContents(j, extractItem); else { destStack.stackSize++; dest.setInventorySlotContents(j, destStack); } dest.markDirty(); return true; } } } } return false; }</code><technical_language>stackSize getMaxStackSize. items a max stack of 64, constant. Stick in a inventory allows... 5 this logic item able added all</technical_language>

Target:
public static Boolean extractHook(IHopper dest) { TileEntity tileEntity = dest.getWorld().getTileEntity(new BlockPos(dest.getXPos(), dest.getYPos() + 1, dest.getZPos())); if (tileEntity == null || !tileEntity.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.DOWN)) return null; IItemHandler handler = tileEntity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.DOWN); for (int i = 0; i < handler.getSlots(); i++) { ItemStack extractItem = handler.extractItem(i, 1, true); if (extractItem != null) { for (int j = 0; j < dest.getSizeInventory(); j++) { ItemStack destStack = dest.getStackInSlot(j); if (destStack == null || destStack.stackSize < destStack.getMaxStackSize() && destStack.stackSize < dest.getInventoryStackLimit() && ItemHandlerHelper.canItemStacksStack(extractItem, destStack)) { extractItem = handler.extractItem(i, 1, false); if (destStack == null) dest.setInventorySlotContents(j, extractItem); else { destStack.stackSize++; dest.setInventorySlotContents(j, destStack); } dest.markDirty(); return true; } } } } return false; }
Source:
<code><START> public ParseOsImages(Json json) { <END> super(json, TypeLiteral.get(OsImages.class)); }</code><technical_language>Remove public modifier</technical_language>

Target:
ParseOsImages(Json json) { super(json, TypeLiteral.get(OsImages.class)); }
Source:
<code>public void isActiveReturnFalseWhenBeforeTimeInFuture() { int currentTime = Time.currentTime(); int futureTime = currentTime + 1; JsonWebToken jsonWebToken = new JsonWebToken(); jsonWebToken.notBefore(futureTime); <START> assertFalse(jsonWebToken.isActive()); <END> }</code><technical_language>If I understand correctly, line 70 "jsonWebToken.isActive()" is executed, system time increased time lines 66-70 executed "Time.currentTime()" called "jsonWebToken.isActive()" return 1 of of "currentTime" variable. If this happen, test fail IMO. changed fragile? Instead of 1 interval, 10 seconds intervals something</technical_language>

Target:
public void isActiveReturnFalseWhenBeforeTimeInFuture() { int currentTime = Time.currentTime(); int futureTime = currentTime + 10; JsonWebToken jsonWebToken = new JsonWebToken(); jsonWebToken.notBefore(futureTime); assertFalse(jsonWebToken.isActive()); }
Source:
<code>public void close() { StandardException se = null; for (OperationContext ctx : activeContexts) { try { ctx.getOperation().close(); } catch (StandardException e) { se = e; LOG.error("Exception while closing operation", e); } <START> } <END> for (Future<Pair<OperationContext, Iterator<ExecRow>>> future : futures) { future.cancel(true); } if (se != null) Exceptions.throwAsRuntime(se); }</code><technical_language>close currentOperationContext too? code in loadBatch(), removed activeContexts, in activeContexts close() is called</technical_language>

Target:
public void close() { StandardException se = null; for (OperationContext ctx : allContexts) { try { ctx.getOperation().close(); } catch (StandardException e) { se = e; LOG.error("Exception while closing operation", e); } } for (Future<Pair<OperationContext, Iterator<ExecRow>>> future : futures) { future.cancel(true); } if (se != null) Exceptions.throwAsRuntime(se); }
Source:
<code>private static Method getDispatcherMethod(String dispatcherMethodName, Class<? extends Message> contextClass) { try { <START> return ProcessManagerRepository.class.getMethod(dispatcherMethodName, Message.class, contextClass); <END> } catch (NoSuchMethodException e) { throw propagate(e); } }</code><technical_language>Extract result variable</technical_language>

Target:
private static Method getDispatcherMethod(String dispatcherMethodName, Class<? extends Message> contextClass) { try { final Method method = ProcessManagerRepository.class.getMethod(dispatcherMethodName, Message.class, contextClass); return method; } catch (NoSuchMethodException e) { throw propagate(e); } }
Source:
<code>public URL findResource(String name) { URL url = super.findResource(name); final Channel channel = channel(); if(url!=null || channel == null || !channel.isRemoteClassLoadingAllowed()) return url; try { if(resourceMap.containsKey(name)) { URLish f = resourceMap.get(name); if(f==null) return null; URL u = f.toURL(); if (u!=null) return u; } <START> if (TESTING_RESOURCE_LOAD != null) TESTING_RESOURCE_LOAD.run(); <END> long startTime = System.nanoTime(); ResourceFile r = proxy.getResource2(name); ResourceImageRef image=null; if (r!=null) image=r.image; channel.resourceLoadingTime.addAndGet(System.nanoTime()-startTime); channel.resourceLoadingCount.incrementAndGet(); if(image==null) { resourceMap.put(name,null); return null; } URLish res = image.resolveURL(channel, name).get(); resourceMap.put(name,res); return res.toURL(); } catch (IOException e) { throw new Error("Unable to load resource "+name,e); } catch (InterruptedException e) { throw new Error("Unable to load resource "+name,e); } catch (ExecutionException e) { throw new Error("Unable to load resource "+name,e); } }</code><technical_language>nit: I prefer form <LINK_0></technical_language>

Target:
public URL findResource(String name) { URL url = super.findResource(name); final Channel channel = channel(); if (url != null || channel == null || !channel.isRemoteClassLoadingAllowed()) { return url; } try { if (resourceMap.containsKey(name)) { URLish f = resourceMap.get(name); if (f == null) { return null; } URL u = f.toURL(); if (u != null) { return u; } } if (TESTING_RESOURCE_LOAD != null) { TESTING_RESOURCE_LOAD.run(); } long startTime = System.nanoTime(); ResourceFile r = proxy.getResource2(name); ResourceImageRef image = null; if (r != null) { image = r.image; } channel.resourceLoadingTime.addAndGet(System.nanoTime() - startTime); channel.resourceLoadingCount.incrementAndGet(); if (image == null) { resourceMap.put(name, null); return null; } URLish res = image.resolveURL(channel, name).get(); resourceMap.put(name, res); return res.toURL(); } catch (IOException | InterruptedException | ExecutionException e) { throw new Error("Unable to load resource " + name, e); } }
Source:
<code><START> private static final String quoteValue(String value) { <END> return "\"" + value + "\""; }</code><technical_language>I final removed. IDEA resource: private methods meaningfully overridden, declaring final is redundant</technical_language>

Target:
private static String quoteValue(String value) { return "\"" + value + "\""; }
Source:
<code>public SelectorNodeMetric(MetricRegistry registry, String hostname, int port) { <START> sendCount = registry.counter(MetricRegistry.name(Selector.class, hostname + "-" + port + "-RequestCount")); <END> bytesSentLatency = registry.histogram(MetricRegistry.name(Selector.class, hostname + "-" + port + "- BytesSentLatencyInMs")); bytesReceivedLatency = registry.histogram(MetricRegistry.name(Selector.class, hostname + "-" + port + "- BytesReceivedLatencyInMs")); bytesSentCount = registry.counter(MetricRegistry.name(Selector.class, hostname + "-" + port + "-BytesSentCount")); bytesReceivedCount = registry.counter(MetricRegistry.name(Selector.class, hostname + "-" + port + "-BytesReceivedCount")); }</code><technical_language>"-SendCount" for consistency</technical_language>

Target:
public SelectorNodeMetric(MetricRegistry registry, String hostname, int port) { sendCount = registry.counter(MetricRegistry.name(Selector.class, hostname + "-" + port + "-SendCount")); bytesSentLatency = registry.histogram(MetricRegistry.name(Selector.class, hostname + "-" + port + "- BytesSentLatencyInMs")); bytesReceivedLatency = registry.histogram(MetricRegistry.name(Selector.class, hostname + "-" + port + "- BytesReceivedLatencyInMs")); bytesSentCount = registry.counter(MetricRegistry.name(Selector.class, hostname + "-" + port + "-BytesSentCount")); bytesReceivedCount = registry.counter(MetricRegistry.name(Selector.class, hostname + "-" + port + "-BytesReceivedCount")); }
Source:
<code>public <T> String buildHtml(T model) { if (model == null) { return null; } try { Context context = Context.newBuilder(model).resolver(resolvers).build(); return template.apply(context); } catch (IOException e) { <START> LOGGER.warn("Failed to apply model to {}{}", htmlTemplate, TEMPLATE_SUFFIX, e); <END> } return null; }</code><technical_language>warn is right level for this. IOException is result of administrator fix</technical_language>

Target:
public <T> String buildHtml(T model) { if (model == null || template == null) { return null; } try { Context context = Context.newBuilder(model).resolver(resolvers).build(); return template.apply(context); } catch (IOException e) { LOGGER.warn("Failed to apply model to {}{}", htmlTemplate, TEMPLATE_SUFFIX, e); } return null; }
Source:
<code>public void testNoTimeout() throws Exception { Ignite ignite = ignite(0); IgniteFuture fut = null; for (int i = 0; i < 10000; i++) { fut = ignite.compute().runAsync(new IgniteRunnable() { <START> @Override <END> public void run() { } }); } fut.get(); }</code><technical_language>@Override line</technical_language>

Target:
public void testNoTimeout() throws Exception { Ignite ignite = ignite(0); IgniteFuture fut = null; for (int i = 0; i < 10000; i++) { fut = ignite.compute().runAsync(new IgniteRunnable() { @Override public void run() { } }); } fut.get(); assertTrue(true); }
Source:
<code>Name getTypeName() { <START> String typeName = "Null"; <END> if (shpFiles != null) { typeName = shpFiles.getTypeName(); } else { typeName = "Null"; } return new NameImpl(namespaceURI, typeName); }</code><technical_language>this happen</technical_language>

Target:
Name getTypeName() { String typeName = "Null"; if (shpFiles != null) { typeName = shpFiles.getTypeName(); } return new NameImpl(namespaceURI, typeName); }
Source:
<code>public void testCreateObjectFromFullModuleNamesWithException() throws Exception { final Method method = factory.getClass().getDeclaredMethod( "createObjectFromFullModuleNames", String.class, Set.class); method.setAccessible(true); final String name = "FooCheck"; final String barFullName = BASE_PACKAGE + ".packageobjectfactory.bar" + PACKAGE_SEPARATOR + name; final String fooFullName = BASE_PACKAGE + ".packageobjectfactory.foo" + PACKAGE_SEPARATOR + name; final Set<String> fullModuleNames = new HashSet<>(Arrays.asList(barFullName, fooFullName)); try { method.invoke(factory, name, fullModuleNames); fail("Exception is expected"); } catch (InvocationTargetException ex) { final String optionalNames = fullModuleNames.stream() <START> .reduce((fullNames, fullName) -> fullNames + STRING_SEPARATOR + fullName).get(); <END> final LocalizedMessage exceptionMessage = new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, AMBIGUOUS_MODULE_NAME_EXCEPTION_MESSAGE, new String[] {name, optionalNames}, null, getClass(), null); assertEquals(exceptionMessage.getMessage(), ex.getTargetException().getMessage()); } }</code><technical_language>please concatenation of string, show text main code in view test code</technical_language>

Target:
public void testCreateObjectFromFullModuleNamesWithException() throws Exception { final String barPackage = BASE_PACKAGE + ".packageobjectfactory.bar"; final String fooPackage = BASE_PACKAGE + ".packageobjectfactory.foo"; final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); final PackageObjectFactory objectFactory = new PackageObjectFactory( new LinkedHashSet<>(Arrays.asList(barPackage, fooPackage)), classLoader); final String name = "FooCheck"; try { objectFactory.createModule(name); fail("Exception is expected"); } catch (CheckstyleException ex) { final String optionalNames = barPackage + PACKAGE_SEPARATOR + name + STRING_SEPARATOR + fooPackage + PACKAGE_SEPARATOR + name; final LocalizedMessage exceptionMessage = new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, AMBIGUOUS_MODULE_NAME_EXCEPTION_MESSAGE, new String[] {name, optionalNames}, null, getClass(), null); assertEquals(exceptionMessage.getMessage(), ex.getMessage()); } }
Source:
<code>private PhysicalOperation createRemoteSource(RemoteSourceNode node, LocalExecutionPlanContext context) { <START> if (node.isOrdered()) { <END> context.setDriverInstanceCount(1); } else if (!context.getDriverInstanceCount().isPresent()) { context.setDriverInstanceCount(getTaskConcurrency(session)); } OperatorFactory operatorFactory = new ExchangeOperatorFactory( context.getNextOperatorId(), node.getId(), context.getTaskExchangeClientManager(), new PagesSerdeFactory(blockEncodingSerde, isExchangeCompressionEnabled(session))); return new PhysicalOperation(operatorFactory, makeLayout(node), context, UNGROUPED_EXECUTION); }</code><technical_language>a bit surprised here, orderingScheme guaranteed if limit driver instance? another sort exchange? If case, this hurt queries' performance need a single remote source</technical_language>

Target:
private PhysicalOperation createRemoteSource(RemoteSourceNode node, LocalExecutionPlanContext context) { if (node.isEnsureSourceOrdering()) { context.setDriverInstanceCount(1); } else if (!context.getDriverInstanceCount().isPresent()) { context.setDriverInstanceCount(getTaskConcurrency(session)); } OperatorFactory operatorFactory = new ExchangeOperatorFactory( context.getNextOperatorId(), node.getId(), context.getTaskExchangeClientManager(), new PagesSerdeFactory(blockEncodingSerde, isExchangeCompressionEnabled(session))); return new PhysicalOperation(operatorFactory, makeLayout(node), context, UNGROUPED_EXECUTION); }
Source:
<code>private static String discoverLfsUrl(Repository db, String purpose, Map<String, String> additionalHeaders, String remoteUrl) { try { URIish u = new URIish(remoteUrl); if (u.getScheme() == null || SCHEME_SSH.equals(u.getScheme())) { Protocol.ExpiringAction action = getSshAuthentication( db, purpose, remoteUrl, u); additionalHeaders.putAll(action.header); return action.href; } else { return remoteUrl + Protocol.INFO_LFS_ENDPOINT; } } catch (Exception e) { <START> e.printStackTrace(); END> return null; } }</code><technical_language>Logger.error</technical_language>

Target:
private static String discoverLfsUrl(Repository db, String purpose, Map<String, String> additionalHeaders, String remoteUrl) { try { URIish u = new URIish(remoteUrl); if (u.getScheme() == null || SCHEME_SSH.equals(u.getScheme())) { Protocol.ExpiringAction action = getSshAuthentication( db, purpose, remoteUrl, u); additionalHeaders.putAll(action.header); return action.href; } else { return remoteUrl + Protocol.INFO_LFS_ENDPOINT; } } catch (Exception e) { log.error(LfsText.get().cannotDiscoverLfs, e); return null; } }
Source:
<code>public void testConcurrentMapMerge() { MetaData metaData = new MetaData(); Map<Object, Object> nestedMap = new HashMap<>(); metaData.addToTab("foo", "bar", nestedMap); nestedMap.put("whoops", null); <START> Map<String, Object> mergedMap = MetaData.merge(metaData, metaData).store; <END> assertFalse(mergedMap.containsKey("whoops")); }</code><technical_language>merge a metadata? weird read otherwise</technical_language>

Target:
public void testConcurrentMapMerge() { MetaData.merge(generateMetaData(), generateMetaData()); }
Source:
<code><START> public int getContentViewId() { <END> return R.layout.rsb_activity_step_switcher; }</code><technical_language>Nice have: @LayoutRes annotation</technical_language>

Target:
public @LayoutRes int getContentViewId() { return R.layout.rsb_activity_step_switcher; }
Source:
<code>private T waitForCompletionAndThrowIfUploadFailed() throws IOException { try { return uploadOperation.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); uploadOperation.cancel(true); IOException exception = new ClosedByInterruptException(); exception.addSuppressed(e); throw exception; } catch (ExecutionException e) { GoogleJsonResponseException exception = ApiErrorExtractor.getJsonResponseException(e.getCause()); <START> if (exception != null && exception.getStatusCode() == 412) { <END> throw (FileAlreadyExistsException) new FileAlreadyExistsException( String.format("Object %s already exists.", getResourceString())) .initCause(e.getCause()); } if (e.getCause() instanceof Error) { throw (Error) e.getCause(); } throw new IOException( String.format("Upload failed for '%s'", getResourceString()), e.getCause()); } }</code><technical_language>need create a new method in ApiErrorExtractor check this (see other methods in this class for example)</technical_language>

Target:
private T waitForCompletionAndThrowIfUploadFailed() throws IOException { try { return uploadOperation.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); uploadOperation.cancel(true); IOException exception = new ClosedByInterruptException(); exception.addSuppressed(e); throw exception; } catch (ExecutionException e) { if (e.getCause() instanceof Error) { throw (Error) e.getCause(); } throw new IOException( String.format("Upload failed for '%s'", getResourceString()), e.getCause()); } }
Source:
<code>ThwackingElement(final String chan, final int stId, final boolean verifiable, final boolean createSubscriber) { channel = chan; streamId = stId; verify = verifiable; <START> buffer = new ThreadLocal<UnsafeBuffer>() <END> { @Override protected UnsafeBuffer initialValue() { return new UnsafeBuffer(ByteBuffer.allocateDirect(DEFAULT_BUFFER_SIZE)); } }; isActive = new AtomicBoolean(false); lock = new ReentrantReadWriteLock(); msgCount = new AtomicInteger(0); if (createSubscriber) { msgHandler = new FragmentAssemblyAdapter(new Handler(this)::messageHandler); streamMap = new Int2ObjectHashMap<Long2ObjectHashMap<MessageStream>>(); } else { senderStream = new ThreadLocal<MessageStream>(); bytesSent = new ThreadLocal<Integer>(); previousSendFailed = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return false; } }; } }</code><technical_language>is a new Java8 technique for this now. ThreadLocal.withInitial(). a bit more readable</technical_language>

Target:
ThwackingElement(final String chan, final int stId, final boolean verifiable, final boolean createSubscriber) { channel = chan; streamId = stId; verify = verifiable; buffer = new ThreadLocal<UnsafeBuffer>().withInitial( () -> new UnsafeBuffer(ByteBuffer.allocateDirect(DEFAULT_BUFFER_SIZE))); isActive = new AtomicBoolean(false); lock = new ReentrantReadWriteLock(); msgCount = new AtomicInteger(0); if (createSubscriber) { msgHandler = new FragmentAssemblyAdapter(new Handler(this)::messageHandler); streamMap = new Int2ObjectHashMap<Long2ObjectHashMap<MessageStream>>(); } else { senderStream = new ThreadLocal<MessageStream>(); bytesSent = new ThreadLocal<Integer>(); previousSendFailed = new ThreadLocal<Boolean>().withInitial(() -> false); } }
Source:
<code>public CommentLinkInfo(Pattern pattern, String link) { <START> this.pattern = pattern; <END> this.link = checkNotNull(link); }</code><technical_language>checkNotNull(pattern), too</technical_language>

Target:
public CommentLinkInfo(Pattern pattern, String link) { this.pattern = checkNotNull(pattern); this.link = checkNotNull(link); }
Source:
<code>public String lookupName(int id) { <START> return null; <END> }</code><technical_language>nit: ll throw exception here, in order avoid silently calling this</technical_language>

Target:
public String lookupName(int id) { throw new UnsupportedOperationException("Map column doesn't support lookupName()"); }
Source:
<code>private void formatAndSetErrorMessage(String message) { <START> int urlIndex = message.indexOf(("http")); END> if (message != null && urlIndex != -1) { String beforeURL = message.substring(0, urlIndex); String url = message.substring(urlIndex); StringBuilder htmlPart = new StringBuilder(); htmlPart.append(beforeURL) .append("<a href=\"").append(url).append("\" target=\"_blank\">").append(url).append("</a>"); getView().setErrorMessage(htmlPart.toString(), true); } else { getView().setErrorMessage(message, false); } }</code><technical_language>parenthesis</technical_language>

Target:
private void formatAndSetErrorMessage(String message) { int urlIndex = message.indexOf(("http")); if (message != null && urlIndex != -1) { String beforeURL = message.substring(0, urlIndex); String url = message.substring(urlIndex); StringBuilder htmlPart = new StringBuilder(); htmlPart.append(beforeURL) .append("<a href=\"").append(url).append("\" target=\"_blank\">").append(url).append("</a>"); getView().setErrorMessageHtml(htmlPart.toString()); } else { getView().setErrorMessageHtml(message); } }
Source:
<code>void assertEqualsFloatWithDeltaWithUnequalValues() { AssertionFailedError e1 = expectThrows(AssertionFailedError.class, () -> assertEquals(0.5f, 0.2f, 0.2f)); assertMessageEndsWith(e1, "expected: <0.5> but was: <0.2>"); AssertionFailedError e2 = expectThrows(AssertionFailedError.class, () -> assertEquals(0.1f, 0.2f, 0.000001f)); assertMessageEndsWith(e2, "expected: <0.1> but was: <0.2>"); AssertionFailedError e3 = expectThrows(AssertionFailedError.class, () -> assertEquals(100.0f, 50.0f, 10.0f)); assertMessageEndsWith(e3, "expected: <100.0> but was: <50.0>"); AssertionFailedError e4 = expectThrows(AssertionFailedError.class, () -> assertEquals(-3.5f, -3.3f, -42.0f)); <START> assertMessageEndsWith(e4, "expected: <-3.5> but was: <-3.3>"); <END> AssertionFailedError e5 = expectThrows(AssertionFailedError.class, () -> assertEquals(+0.0f, -0.0f, -1.0f)); assertMessageEndsWith(e5, "expected: <0.0> but was: <-0.0>"); }</code><technical_language>wondering allow negative deltas. do think</technical_language>

Target:
void assertEqualsFloatWithDeltaWithUnequalValues() { AssertionFailedError e1 = expectThrows(AssertionFailedError.class, () -> assertEquals(0.5f, 0.2f, 0.2f)); assertMessageEndsWith(e1, "expected: <0.5> but was: <0.2>"); AssertionFailedError e2 = expectThrows(AssertionFailedError.class, () -> assertEquals(0.1f, 0.2f, 0.000001f)); assertMessageEndsWith(e2, "expected: <0.1> but was: <0.2>"); AssertionFailedError e3 = expectThrows(AssertionFailedError.class, () -> assertEquals(100.0f, 50.0f, 10.0f)); assertMessageEndsWith(e3, "expected: <100.0> but was: <50.0>"); AssertionFailedError e4 = expectThrows(AssertionFailedError.class, () -> assertEquals(-3.5f, -3.3f, 0.01f)); assertMessageEndsWith(e4, "expected: <-3.5> but was: <-3.3>"); AssertionFailedError e5 = expectThrows(AssertionFailedError.class, () -> assertEquals(+0.0f, -0.001f, .00001f)); assertMessageEndsWith(e5, "expected: <0.0> but was: <-0.001>"); }
Source:
<code>public long findFirstDate(long columnIndex, Date date) { if (date == null) { throw new IllegalArgumentException("null is not supported"); } <START> return nativeFindFirstTimestamp(nativePtr, columnIndex, date.getTime() / 1000); <END> }</code><technical_language>"/1000" I assume</technical_language>

Target:
public long findFirstDate(long columnIndex, Date date) { if (date == null) { throw new IllegalArgumentException("null is not supported"); } return nativeFindFirstTimestamp(nativePtr, columnIndex, date.getTime()); }
Source:
<code>private void refreshActionModeTitle() { MediaOverviewPageViewModel pageViewModel = ViewModelProviders.of(this).get(MediaOverviewPageViewModel.class); pageViewModel.updateActionModeTitle(adapter.getSelectedMediaCount(), adapter.getSelectedMediaTotalFileSize(), <START> detail, sorting, mediaType); <END> }</code><technical_language>alignment adapter detail aligned: method.call(a, b);</technical_language>

Target:
private void refreshActionModeTitle() { pageViewModel.updateActionModeTitle(adapter.getSelectedMediaCount(), adapter.getSelectedMediaTotalFileSize(), detail, sorting, mediaType); }
Source:
<code>protected Connection getDBConnection(final boolean autoCommit) throws IOException { Connection connection = null; <START> SERVICE_PROVIDER.getInstance(CommonMetrics.class).markDBConnection(); <END> final long startMs = System.currentTimeMillis(); try { connection = this.dataSource.getConnection(); connection.setAutoCommit(autoCommit); } catch (final Exception e) { DbUtils.closeQuietly(connection); throw new IOException("Error getting DB connection.", e); } SERVICE_PROVIDER.getInstance(CommonMetrics.class) .setDBConnectionTime(System.currentTimeMillis() - startMs); return connection; }</code><technical_language>Consider saving this reference in constructor? This class considered a dependency of this class</technical_language>

Target:
protected Connection getDBConnection(final boolean autoCommit) throws IOException { Connection connection = null; this.commonMetrics.markDBConnection(); final long startMs = System.currentTimeMillis(); try { connection = this.dataSource.getConnection(); connection.setAutoCommit(autoCommit); } catch (final Exception e) { DbUtils.closeQuietly(connection); throw new IOException("Error getting DB connection.", e); } this.commonMetrics.setDBConnectionTime(System.currentTimeMillis() - startMs); return connection; }
Source:
<code>public void loginUser(String email, String password, final LoginCallback callback) { Map<String, ?extends Object> params = ImmutableMap.of("email", email, "password", password); invokeStaticMethod("login", params, new Adapter.JsonObjectCallback() { @Override public void onError(Throwable t) { callback.onError(t); } @Override public void onSuccess(JSONObject response) { if (response == null) { callback.onSuccess(null); } else { callback.onSuccess( createModel(JsonUtil.fromJson(response))); <START> } <END> } }); }</code><technical_language>test response == null branch? I login returns error a valid access token, a null response</technical_language>

Target:
public void loginUser(String email, String password, final LoginCallback callback) { HashMap<String, Object> params = new HashMap<String, Object>(); params.put("email", email); params.put("password", password); invokeStaticMethod("login", params, new Adapter.JsonObjectCallback() { @Override public void onError(Throwable t) { callback.onError(t); } @Override public void onSuccess(JSONObject response) { RestAdapter radapter = (RestAdapter)getAdapter(); if ( accessTokenRepository == null ) { accessTokenRepository = radapter.createRepository(AccessTokenRepository.class); } AccessToken accessTokenModel = accessTokenRepository.createModel(JsonUtil.fromJson(response)); radapter.setAccessToken(accessTokenModel.getId()); callback.onSuccess(accessTokenModel); } }); }
Source:
<code>public static <E> BoundedCollection<E> unmodifiableBoundedCollection(Collection<? extends E> coll) { if (coll == null) { throw new NullPointerException("Collection must not be null."); } for (int i = 0; i < 1000; i++) { if (coll instanceof BoundedCollection) { break; } <START> if (coll instanceof org.apache.commons.collections4.collection.AbstractCollectionDecorator) { <END> coll = ((org.apache.commons.collections4.collection.AbstractCollectionDecorator<E>) coll).decorated(); } else if (coll instanceof org.apache.commons.collections4.collection.SynchronizedCollection) { coll = ((org.apache.commons.collections4.collection.SynchronizedCollection<E>) coll).decorated(); } } if (coll instanceof BoundedCollection == false) { throw new IllegalArgumentException("Collection is not a bounded collection."); } return new UnmodifiableBoundedCollection<>((BoundedCollection<E>) coll); }</code><technical_language>I do need fully qualified name here</technical_language>

Target:
public static <E> BoundedCollection<E> unmodifiableBoundedCollection(Collection<? extends E> coll) { if (coll == null) { throw new NullPointerException("Collection must not be null."); } for (int i = 0; i < 1000; i++) { if (coll instanceof BoundedCollection) { break; } if (coll instanceof AbstractCollectionDecorator) { coll = ((AbstractCollectionDecorator<E>) coll).decorated(); } else if (coll instanceof SynchronizedCollection) { coll = ((SynchronizedCollection<E>) coll).decorated(); } } if (coll instanceof BoundedCollection == false) { throw new IllegalArgumentException("Collection is not a bounded collection."); } return new UnmodifiableBoundedCollection<>((BoundedCollection<E>) coll); }
Source:
<code>void print(PrintWriter out) { seen.clear(); collisions.clear(); for (RelationModel r : rels) { for (ColumnModel c : r.getColumns()) { if (c.isNested()) { String type = getShortClassName(c); if (seen.contains(type)) { collisions.add(type); } else { seen.add(type); } } } } seen.clear(); for (RelationModel r : rels) { generateMessage(r.getPrimaryKey().getField(), out, true); } for (RelationModel r : rels) { generateMessage(r, out); } out.print("message Any" + schemaName + "PrimaryKey {\n"); for (RelationModel r : sortRelations(rels)) { ColumnModel pk = r.getPrimaryKey().getField(); out.print("\toptional " + getType(pk) + " " + r.getRelationName().toLowerCase() + " = " + r.getRelationID() + ";\n"); } <START> out.print("}\n"); <END> out.print("message Any" + schemaName + " {\n"); for (RelationModel r : sortRelations(rels)) { out.print("\toptional " + getMessageName(r) + " " + r.getRelationName().toLowerCase() + " = " + r.getRelationID() + ";\n"); } out.print("}\n"); }</code><technical_language>generated output, I want another \n here</technical_language>

Target:
void print(PrintWriter out) { seen.clear(); collisions.clear(); for (RelationModel r : rels) { for (ColumnModel c : r.getColumns()) { if (c.isNested()) { String type = getShortClassName(c); if (seen.contains(type)) { collisions.add(type); } else { seen.add(type); } } } } seen.clear(); for (RelationModel r : rels) { generateMessage(r.getPrimaryKey().getField(), out, true); } for (RelationModel r : rels) { generateMessage(r, out); } out.print("message Any" + schemaName + "PrimaryKey {\n"); for (RelationModel r : sortRelations(rels)) { ColumnModel pk = r.getPrimaryKey().getField(); out.print("\toptional " + getType(pk) + " " + r.getRelationName().toLowerCase() + " = " + r.getRelationID() + ";\n"); } out.print("}\n"); out.print("\n"); out.print("message Any" + schemaName + " {\n"); for (RelationModel r : sortRelations(rels)) { out.print("\toptional " + getMessageName(r) + " " + r.getRelationName().toLowerCase() + " = " + r.getRelationID() + ";\n"); } out.print("}\n"); }
Source:
<code>private void processProjection(ServiceNode serviceNode) { <START> List<Resolution> resolutions = LabelService.findResolutions(serviceNode); <END> if (serviceNode.getProjectedVars() == null && resolutions.size() > 0) { serviceNode.setProjectedVars(resolutions .stream() .map(r -> (IVariable<?>)r.target()) .collect(Collectors.toSet())); } }</code><technical_language>do in EmptyLabelServiceOptimizer - finding out projections</technical_language>

Target:
private void processProjection(ServiceNode serviceNode) { List<Resolution> resolutions = LabelService.findResolutions(serviceNode); if (serviceNode.getProjectedVars() == null && resolutions.size() > 0) { Set<IVariable<?>> inVars = new HashSet<>(); Set<IVariable<?>> outVars = new HashSet<>(); for (Resolution resolution: resolutions) { if (resolution.subject() instanceof IVariable) { inVars.add((IVariable<?>)resolution.subject()); } outVars.add(resolution.target()); } serviceNode.annotations().put(LabelService.LABEL_SERVICE_IN_VARS, inVars); serviceNode.annotations().put(LabelService.LABEL_SERVICE_OUT_VARS, outVars); HashSet<IVariable<?>> projectedVars = new HashSet<>(inVars); projectedVars.addAll(outVars); serviceNode.setProjectedVars(projectedVars); } }
Source:
<code>public FaultDomain(FaultDomainType type, String id) { <START> this.type = type; this.id = id; <END> }</code><technical_language>nan</technical_language>

Target:
public FaultDomain(FaultDomainType type, String id) { Preconditions.checkNotNull(type, "Fault domain type (ex:rack) cannot be null."); Preconditions.checkNotNull(id, "Fault domain ID (rack ID) cannot be null."); this.type = type; this.id = id; }
Source:
<code>public void process() { PerformanceMonitor.startActivity("rendering/copyDepth"); copyDepthMaterial.setFloat("zNear",activeCamera.getzNear(),true); <START> copyDepthMaterial.setFloat("zFar",activeCamera.getzFar(),true); <END> glViewport(0, 0, Display.getWidth(), Display.getHeight()); renderFullscreenQuad(); PerformanceMonitor.endActivity(); }</code><technical_language>I thought checkstyle inform spaces commas here. configure in IntelliJ</technical_language>

Target:
public void process() { PerformanceMonitor.startActivity("rendering/copyDepth"); renderFullscreenQuad(); PerformanceMonitor.endActivity(); }
Source:
<code>public void validate(final PreparedUpdate update, final UpdateContext updateContext) { final Subject subject = updateContext.getSubject(update); <START> if (subject.hasPrincipal(Principal.OVERRIDE_MAINTAINER) || subject.hasPrincipal(Principal.ALLOC_MAINTAINER)) { <END> return; } final RpslObject originalObject = update.getReferenceObject(); final RpslObject updatedObject = update.getUpdatedObject(); if (hasCountryChanged(originalObject, updatedObject, update.getAction())) { updateContext.addMessage(update, UpdateMessages.canOnlyBeChangedByRipeNCC(COUNTRY)); } }</code><technical_language>RS_MAINTAINER instead of ALLOC_MAINTAINER</technical_language>

Target:
public void validate(final PreparedUpdate update, final UpdateContext updateContext) { final Subject subject = updateContext.getSubject(update); if (subject.hasPrincipal(Principal.OVERRIDE_MAINTAINER) || subject.hasPrincipal(Principal.RS_MAINTAINER)) { return; } final RpslObject originalObject = update.getReferenceObject(); final RpslObject updatedObject = update.getUpdatedObject(); if (hasCountryChanged(originalObject, updatedObject, update.getAction())) { updateContext.addMessage(update, UpdateMessages.canOnlyBeChangedByRipeNCC(COUNTRY)); } }
Source:
<code>public CosmosQueryMethod(Method method, RepositoryMetadata metadata, ProjectionFactory factory) { super(method, metadata, factory); <START> this.method = method; <END> }</code><technical_language>delete field method, stringInQueryAnnotation instead</technical_language>

Target:
public CosmosQueryMethod(Method method, RepositoryMetadata metadata, ProjectionFactory factory) { super(method, metadata, factory); this.annotatedQueryValue = findAnnotatedQuery(method).orElse(null); }
Source:
<code>private String getDeviceIpAddressFromSessionProvider(final DlmsDevice dlmsDevice) throws ProtocolAdapterException, FunctionalException { final SessionProvider sessionProvider = this.sessionProviderService .getSessionProvider(dlmsDevice.getCommunicationProvider()); String deviceIpAddress = null; try { deviceIpAddress = sessionProvider.getIpAddress(dlmsDevice.getIccId()); if (deviceIpAddress != null) { return deviceIpAddress; } this.jasperWirelessSmsClient.sendWakeUpSMS(dlmsDevice.getIccId()); deviceIpAddress = this.pollForSession(sessionProvider, dlmsDevice); } catch (final SessionProviderException e) { LOGGER.error("IccId is probably not supported in this session provider", e); <START> throw new FunctionalException(FunctionalExceptionType.INVALID_ICCID, ComponentType.PROTOCOL_DLMS); <END> } if ((deviceIpAddress == null) || "".equals(deviceIpAddress)) { throw new ProtocolAdapterException("Session provider: " + dlmsDevice.getCommunicationProvider() + " did not return an IP address for device: " + dlmsDevice.getDeviceIdentification() + "and iccId: " + dlmsDevice.getIccId()); } return deviceIpAddress; }</code><technical_language>reason include original exception in new FunctionalException? provide message giving extra information helpful finding out more details wrong</technical_language>

Target:
private String getDeviceIpAddressFromSessionProvider(final DlmsDevice dlmsDevice) throws ProtocolAdapterException, FunctionalException { final SessionProvider sessionProvider = this.sessionProviderService .getSessionProvider(dlmsDevice.getCommunicationProvider()); String deviceIpAddress = null; try { deviceIpAddress = sessionProvider.getIpAddress(dlmsDevice.getIccId()); if (deviceIpAddress != null) { return deviceIpAddress; } this.jasperWirelessSmsClient.sendWakeUpSMS(dlmsDevice.getIccId()); deviceIpAddress = this.pollForSession(sessionProvider, dlmsDevice); } catch (final SessionProviderException e) { LOGGER.error("IccId is probably not supported in this session provider", e); throw new FunctionalException(FunctionalExceptionType.INVALID_ICCID, ComponentType.PROTOCOL_DLMS, e); } if ((deviceIpAddress == null) || "".equals(deviceIpAddress)) { throw new ProtocolAdapterException("Session provider: " + dlmsDevice.getCommunicationProvider() + " did not return an IP address for device: " + dlmsDevice.getDeviceIdentification() + "and iccId: " + dlmsDevice.getIccId()); } return deviceIpAddress; }
Source:
<code>public String toString() { <START> return "MachineLogMessageImpl{" + <END> "machine='" + machine + '\'' + ", content='" + content + '\'' + '}'; }</code><technical_language>avoid some concatenate starting "MachineLogMessageImpl{machine=''" MachineLogMessageImpl class.getName refactoring rename automatically toString</technical_language>

Target:
public String toString() { return "MachineLogMessageImpl{machineName='" + machineName + "', content='" + content + "'}"; }
Source:
<code>public Map<Object, Object> loadInitialData() { <START> Map<Object, Object> result = new HashedMap(); <END> int linesToCache = cacheContext.getValue(CacheManager.CacheContext.NUM_INIT_CACHED_LINES_ATTR); int lineCount = 0; for (Map.Entry entry : DummyBackupStore.backupMap.entrySet()) { if (linesToCache > 0 && lineCount >= linesToCache) { break; } result.put(entry.getKey(), DummyBackupStore.backupMap.get(entry.getKey())); lineCount++; } return result; }</code><technical_language>standard HashMap</technical_language>

Target:
public Map<Object, Object> loadInitialData() { Map<Object, Object> result = new HashMap(); int linesToCache = cacheContext.getValue(CacheManager.CacheContext.NUM_INIT_CACHED_LINES_ATTR); int lineCount = 0; for (Map.Entry entry : DummyBackupStore.backupMap.entrySet()) { if (linesToCache > 0 && lineCount >= linesToCache) { break; } result.put(entry.getKey(), DummyBackupStore.backupMap.get(entry.getKey())); lineCount++; } return result; }
Source:
<code>public void givenSubtypeOfGenericType_thenPamCorrectly() throws Exception { DomainInfo domainInfo = DomainInfo.create(org.neo4j.ogm.metadata.schema.generics.Person.class.getPackage().getName()); schema = new DomainInfoSchemaBuilder(domainInfo).build(); Node person = schema.findNode("Person"); Map<String, Relationship> relationships = person.relationships(); Relationship organisations = relationships.get("organisations"); assertThat(organisations).isNotNull(); assertThat(organisations.type()).isEqualTo("FOUNDED"); assertThat(organisations.direction(person)).isEqualTo(OUTGOING); assertThat(organisations.other(person)).isEqualTo(schema.findNode("Organisation")); <START> <END> Node entity = schema.findNode("Entity"); assertThat(entity.label()).isEqualTo("Entity"); Node company = schema.findNode("Company"); assertThat(company).as("Abstract non annotated classes should be ignored").isNull(); }</code><technical_language>Move separate test case? This for generic version of Founded extends Associated<Person, Organisation></technical_language>

Target:
public void givenSubtypeOfGenericType_thenPamCorrectly() throws Exception { DomainInfo domainInfo = DomainInfo.create(org.neo4j.ogm.metadata.schema.generics.Person.class.getPackage().getName()); schema = new DomainInfoSchemaBuilder(domainInfo).build(); Node person = schema.findNode("Person"); Map<String, Relationship> relationships = person.relationships(); Relationship organisations = relationships.get("organisations"); assertThat(organisations).isNotNull(); assertThat(organisations.type()).isEqualTo("FOUNDED"); assertThat(organisations.direction(person)).isEqualTo(OUTGOING); assertThat(organisations.other(person)).isEqualTo(schema.findNode("Organisation")); }
Source:
<code>public void postProcess() { uniqueID = UUID.randomUUID().toString(); if (hasMissingAttributes()) { int failuresCount = 0; int skippedCount = 0; int errorsCount = 0; Double totalTime = 0.0; <START> for (TestCaseModel test : testcase) { <END> if (test.getOverallStatus().equals(Constants.FAILED)) { failuresCount++; } else if (test.getOverallStatus().equals(Constants.ERRORED)) { errorsCount++; } else if (test.getOverallStatus().equals(Constants.SKIPPED)) { skippedCount++; } totalTime += Double.parseDouble(test.getTime()); } if (failures == null) failures = Integer.toString(failuresCount); if (skipped == null) skipped = Integer.toString(skippedCount); if (tests == null) tests = Integer.toString(testcase.size()); if (time == null) time = Double.toString(totalTime); if (errors == null) errors = Integer.toString(errorsCount); System.out.println("LOL\n"); } if (Integer.parseInt(failures) > 0 || Integer.parseInt(errors) > 0) { overallStatus = Constants.FAILED; } else { overallStatus = Constants.PASSED; } }</code><technical_language>a empty line for ? separate stuff :D</technical_language>

Target:
public void postProcess() { uniqueID = UUID.randomUUID().toString(); if (hasMissingAttributes()) { int failuresCount = 0; int skippedCount = 0; int errorsCount = 0; Double totalTime = 0.0; for (TestCaseModel test : testcase) { if (test.getOverallStatus().equals(Constants.FAILED)) { failuresCount++; } else if (test.getOverallStatus().equals(Constants.ERRORED)) { errorsCount++; } else if (test.getOverallStatus().equals(Constants.SKIPPED)) { skippedCount++; } totalTime += Double.parseDouble(test.getTime()); } if (failures == null) { failures = Integer.toString(failuresCount); } if (skipped == null) { skipped = Integer.toString(skippedCount); } if (tests == null) { tests = Integer.toString(testcase.size()); } if (time == null) { time = Double.toString(totalTime); } if (errors == null) { errors = Integer.toString(errorsCount); } } if (Integer.parseInt(failures) > 0 || Integer.parseInt(errors) > 0) { overallStatus = Constants.FAILED; } else { overallStatus = Constants.PASSED; } }
Source:
<code>public void setUp() throws Exception { super.setUp(); dao = dbFacade.getEngineBackupLogDao(); existingEngineBackupLog = dao.getLastSuccessfulEngineBackup(DB_NAME); newEntity = new EngineBackupLog(); <START> newEntity.setDbName("asd"); <END> newEntity.setOutputMessage("asd"); newEntity.setDoneAt(new Date()); newEntity.setPassed(true); }</code><technical_language>RandomUtils.nextString(20) instead</technical_language>

Target:
public void setUp() throws Exception { super.setUp(); dao = dbFacade.getEngineBackupLogDao(); existingEngineBackupLog = dao.getLastSuccessfulEngineBackup(DB_NAME); newEntity = new EngineBackupLog(); newEntity.setDbName(RandomUtils.instance().nextString(20)); newEntity.setOutputMessage(RandomUtils.instance().nextString(20)); newEntity.setDoneAt(new Date()); newEntity.setPassed(true); }
Source:
<code>public void testGetValidityInfoForNonHtmlField_unsanitizedInput_returnErrorString() { String unsanitizedInput = "Invalid unsanitized input <>\"/'&"; String testFieldName = "Inconsequential test field name"; String actual = validator.getValidityInfoForNonHtmlField(testFieldName, unsanitizedInput); assertEquals("Invalid unsanitized input should return error string", "The provided Inconsequential test field name is not acceptable to TEAMMATES as it " <START> + "cannot contain the following special html characters in brackets: (&lt; &gt; \" " <END> + "&#x2f; &#39; &amp;)", actual); }</code><technical_language>Replace \" &quot; too</technical_language>

Target:
public void testGetValidityInfoForNonHtmlField_unsanitizedInput_returnErrorString() { String unsanitizedInput = "Invalid unsanitized input <>\"/'&"; String testFieldName = "Inconsequential test field name"; String actual = validator.getValidityInfoForNonHtmlField(testFieldName, unsanitizedInput); assertEquals("Invalid unsanitized input should return error string", "The provided Inconsequential test field name is not acceptable to TEAMMATES as it " + "cannot contain the following special html characters in brackets: (&lt; &gt; &quot; " + "&#x2f; &#39; &amp;)", actual); }
Source:
<code>public void setSupertype(TypeName typeName) { if (supertype.isPresent()) { throw new IllegalStateException("Supertype already set to " + writeToString(supertype.get())); } <START> checkArgument(!anonymous, "Anonymous classes cannot declare supertypes"); <END> supertype = Optional.of(typeName); }</code><technical_language>checkState</technical_language>

Target:
public void setSupertype(TypeName typeName) { if (supertype.isPresent()) { throw new IllegalStateException("Supertype already set to " + writeToString(supertype.get())); } supertype = Optional.of(typeName); }