auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Parser loadParser(Header header) { ParserInfo parserInfo = client.getParserInfo(header.getDeviceId(), header.getVersion()); InputStream parserJar = client.getParserJar(parserInfo.getParserId()); String jarPath = String.format("%s%s%s-%s.jar", localParserJarPath, File.pathSeparator, header.getDeviceId(), header.getVersion()); try { IOUtils.copy(parserJar, new FileOutputStream(new File(jarPath))); } catch (IOException e) { throw new RuntimeException(e); } try { if (!ReflectionHelper.isJarInClassPath(jarPath) && !ReflectionHelper.isClassLoaded(parserInfo.getClassName())) { ReflectionHelper.loadJarAndAllItsClasses(jarPath); } return ReflectionHelper.newInstance(parserInfo.getClassName()); } catch (IOException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); <START> } catch (InstantiationException e) { <END> throw new RuntimeException(e); } }</code><technical_language>multi catch in of catch blocks line - cleaner. simply wrapping checked exception in a runtime exception, want simply catch Exception, rethrow RuntimeException. Please read here. <LINK_0></technical_language>

Target:
private Parser loadParser(Header header) { ParserInfo parserInfo = client.getParserInfo(header.getDeviceId(), header.getVersion()); InputStream parserJar = client.getParserJar(parserInfo.getParserId()); String jarPath = String.format("%s%s%s-%s.jar", localParserJarPath, File.pathSeparator, header.getDeviceId(), header.getVersion()); try { IOUtils.copy(parserJar, new FileOutputStream(new File(jarPath))); if (!ReflectionHelper.isJarInClassPath(jarPath) && !ReflectionHelper.isClassLoaded(parserInfo.getClassName())) { ReflectionHelper.loadJarAndAllItsClasses(jarPath); } return ReflectionHelper.newInstance(parserInfo.getClassName()); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>protected boolean isConnWithSameDetailsExists(StorageServerConnections connection) { List<StorageServerConnections> connections = null; if (connection.getstorage_type().isFileDomain()) { String connectionField = connection.getconnection(); connections = getStorageConnDao().getAllForStorage(connectionField); } else { connections = getStorageConnDao().getAllForConnection(connection); } if (connections.size() > 1 <START> || (connections.size() == 1 && !connections.get(0).getid().equalsIgnoreCase(connection.getid()))) { <END> return true; } else { return false; } }</code><technical_language>is equalsIgnoreCase equals? Also, this if statenebt is redundant: if (booleanStatement) { return true; } else { return false; } do "return booleanStatement"</technical_language>

Target:
protected boolean isConnWithSameDetailsExists(StorageServerConnections connection) { List<StorageServerConnections> connections = null; if (connection.getstorage_type().isFileDomain()) { String connectionField = connection.getconnection(); connections = getStorageConnDao().getAllForStorage(connectionField); } else { connections = getStorageConnDao().getAllForConnection(connection); } boolean isDuplicateConnExists = (connections.size() > 1 || (connections.size() == 1 && !connections.get(0).getid().equalsIgnoreCase(connection.getid()))); return isDuplicateConnExists; }
Source:
<code>public void open() throws InvalidInterfaceException, InterfaceInUseException, OperationNotSupportedException, InvalidConfigurationException { try { portIdentifier = CommPortIdentifier.getPortIdentifier(port); } catch (NoSuchPortException e) { throw new InvalidInterfaceException("No such port: " + port); } try { serialPort = (RXTXPort)portIdentifier.open(PORT_ALIAS + " " + port, receiveTimeout); connectionOpen = true; if (parameters == null) parameters = new SerialPortParameters(baudRate, DEFAULT_DATA_BITS, DEFAULT_STOP_BITS, DEFAULT_PARITY, DEFAULT_FLOW_CONTROL); serialPort.setSerialPortParams(baudRate, parameters.dataBits, parameters.stopBits, parameters.parity); serialPort.setFlowControlMode(parameters.flowControl); serialPort.enableReceiveTimeout(receiveTimeout); portIdentifier.addPortOwnershipListener(this); inputStream = serialPort.getInputStream(); outputStream = serialPort.getOutputStream(); serialPort.notifyOnDataAvailable(true); serialPort.addEventListener(this); } catch (PortInUseException e) { <START> throw new InterfaceInUseException("Port in use: " + port); <END> } catch (UnsupportedCommOperationException e) { throw new OperationNotSupportedException(e.getMessage()); } catch (TooManyListenersException e) { throw new InvalidConfigurationException(e.getMessage()); } }</code><technical_language>I change message "Port '" + port + "' is in other application(s)"</technical_language>

Target:
public void open() throws InterfaceInUseException, InvalidConfigurationException, InvalidInterfaceException { try { portIdentifier = CommPortIdentifier.getPortIdentifier(port); } catch (NoSuchPortException e) { throw new InvalidInterfaceException("No such port: " + port, e); } try { serialPort = (RXTXPort)portIdentifier.open(PORT_ALIAS + " " + port, receiveTimeout); connectionOpen = true; if (parameters == null) parameters = new SerialPortParameters(baudRate, DEFAULT_DATA_BITS, DEFAULT_STOP_BITS, DEFAULT_PARITY, DEFAULT_FLOW_CONTROL); serialPort.setSerialPortParams(baudRate, parameters.dataBits, parameters.stopBits, parameters.parity); serialPort.setFlowControlMode(parameters.flowControl); serialPort.enableReceiveTimeout(receiveTimeout); portIdentifier.addPortOwnershipListener(this); inputStream = serialPort.getInputStream(); outputStream = serialPort.getOutputStream(); serialPort.notifyOnDataAvailable(true); serialPort.addEventListener(this); } catch (PortInUseException e) { throw new InterfaceInUseException("Port " + port + " is already in use by other application(s)", e); } catch (UnsupportedCommOperationException e) { throw new InvalidConfigurationException(e.getMessage(), e); } catch (TooManyListenersException e) { throw new InvalidConfigurationException(e.getMessage(), e); } }
Source:
<code>LobbyGameTableModel(final Map<GUID, GameDescription> gameList, final boolean isAdmin) { this.isAdmin = isAdmin; <START> gameListModel = new GameListModel(); <END> for (final Map.Entry<GUID, GameDescription> entry : gameList.entrySet()) { updateGame(entry.getKey(), entry.getValue()); } }</code><technical_language>This field initialized in-line</technical_language>

Target:
LobbyGameTableModel(final Map<GUID, GameDescription> gameList, final boolean isAdmin) { this.isAdmin = isAdmin; gameListModel = new GameListModel(); for (final Map.Entry<GUID, GameDescription> entry : gameList.entrySet()) { gameUpdated(entry.getKey(), entry.getValue()); } }
Source:
<code>protected Map<String, String> createPortAllocationRuntimeProperties(Port port) { Map<String, String> runtimeProperties = new HashMap<>(); runtimeProperties.put("vnic_id", port.getId()); String providerType = getProvider().getType().name(); runtimeProperties.put("provider_type", providerType); if (port.getSecurityGroups() != null && !port.getSecurityGroups().isEmpty()) { runtimeProperties.put("security_groups", StringUtils.join(port.getSecurityGroups(), ',')); } String pluginType = getProvider().getAdditionalProperties().getPluginType(); <START> if (pluginType==null) { <END> pluginType = ""; } runtimeProperties.put("plugin_type", pluginType); return runtimeProperties; }</code><technical_language>pls project's formatter, spaces == : if (pluginType == null) {...} skip using: runtimeProperties.put("plugin_type", StringUtils.defaultString(getProvider().getAdditionalProperties().getPluginType())); String pluginType = StringUtils.defaultString(getProvider().getAdditionalProperties().getPluginType()); runtimeProperties.put("plugin_type", pluginType);</technical_language>

Target:
protected Map<String, String> createPortAllocationRuntimeProperties(Port port) { Map<String, String> runtimeProperties = new HashMap<>(); runtimeProperties.put("vnic_id", port.getId()); String providerType = getProvider().getType().name(); runtimeProperties.put("provider_type", providerType); if (port.getSecurityGroups() != null && !port.getSecurityGroups().isEmpty()) { runtimeProperties.put("security_groups", StringUtils.join(port.getSecurityGroups(), ',')); } runtimeProperties.put("plugin_type", StringUtils.defaultString( getProvider().getAdditionalProperties().getPluginType())); return runtimeProperties; }
Source:
<code>private synchronized void postPushUnregister(BroadcastReceiver pushReceiver, final ClientManager clientMgr, final boolean showLoginPage, final String refreshToken, final String clientId, final String loginServer, final Account account, Activity frontActivity) { if (!loggedOut) { try { context.unregisterReceiver(pushReceiver); } catch (Exception e) { <START> logger.log(SalesforceLogger.Level.ERROR, TAG, "Exception occurred while unregistering", e); <END> } removeAccount(clientMgr, showLoginPage, refreshToken, clientId, loginServer, account, frontActivity); } }</code><technical_language>java import static SalesforceLogger.Level.*; write java logger.log(ERROR, TAG, ...) introduce warn / info / error / debug methods logger</technical_language>

Target:
private synchronized void postPushUnregister(BroadcastReceiver pushReceiver, final ClientManager clientMgr, final boolean showLoginPage, final String refreshToken, final String clientId, final String loginServer, final Account account, Activity frontActivity) { if (!loggedOut) { try { context.unregisterReceiver(pushReceiver); } catch (Exception e) { SalesforceSDKLogger.e(TAG, "Exception occurred while unregistering", e); } removeAccount(clientMgr, showLoginPage, refreshToken, clientId, loginServer, account, frontActivity); } }
Source:
<code>public ConsumerDTO setCapabilities(Set<CapabilityDTO> capabilities) { <START> this.capabilities = capabilities; <END> return this; }</code><technical_language>Encapsulation</technical_language>

Target:
public ConsumerDTO setCapabilities(Set<CapabilityDTO> capabilities) { if (capabilities != null) { if (this.capabilities == null) { this.capabilities = new HashSet<CapabilityDTO>(); } else { this.capabilities.clear(); } for (CapabilityDTO dto : capabilities) { if (dto == null || StringUtils.isEmpty(dto.getName())) { throw new IllegalArgumentException("null or imcomplete consumer capability"); } this.capabilities.add(new CapabilityDTO(dto)); } } else { this.capabilities = null; } return this; }
Source:
<code>public <T> T generateValue() { <START> return (T) this.getNext(); <END> }</code><technical_language>This is delegating getNext. put getNext code here, generate logic</technical_language>

Target:
public <T> T generateValue() { if(this.nextValueIndex >= this.dataset.length) { this.nextValueIndex = 0; } Object nextValue = this.dataset[this.nextValueIndex]; this.nextValueIndex ++; return (T)nextValue; }
Source:
<code>public static Map<String, Long> getAllCycles(final ZephyrRestClient restClient, final long projectId, final long versionId) { final Map<String, Long> cycles = new HashMap<String, Long>(); final String url = String.format(URL_GET_CYCLES, restClient.getUrl(), projectId,versionId); <START> final HttpResponse response = restClient.get(url); <END> final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { final HttpEntity entity = response.getEntity(); String string = null; try { string = EntityUtils.toString(entity); } catch (ParseException | IOException e) { ZephyrPlugin.log(e); } final JsonObject projObj = new JsonParser().parse(string).getAsJsonObject(); for (int i = 0; i < projObj.size(); i++) { final Set<String> keys = projObj.keySet(); for (final String key : keys) { if (!key.trim().equals("recordsCount")) { final JsonObject cycleObject = projObj.get(key).getAsJsonObject(); final String cycleName = cycleObject.get("name").getAsString(); final long id = Long.parseLong(key); cycles.put(cycleName, id); } } } } else { ZephyrPlugin.log("Unexpected response status: " + statusCode); } return cycles; }</code><technical_language>Resource leak</technical_language>

Target:
public static Map<String, Long> getAllCycles(final ZephyrRestClient restClient, final long projectId, final long versionId) { final Map<String, Long> cycles = new HashMap<String, Long>(); final String url = String.format(URL_GET_CYCLES, restClient.getUrl(), projectId, versionId); try (final CloseableHttpResponse response = restClient.get(url)) { final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { final HttpEntity entity = response.getEntity(); String string = null; try { string = EntityUtils.toString(entity); } catch (ParseException | IOException e) { throw new IllegalArgumentException( String.format("Bad response entity upon receipt of cycles <%s>", url), e); } final JsonObject projObj = new JsonParser().parse(string).getAsJsonObject(); for (int i = 0; i < projObj.size(); i++) { final Set<String> keys = projObj.keySet(); for (final String key : keys) { if (!key.trim().equals("recordsCount")) { final JsonObject cycleObject = projObj.get(key).getAsJsonObject(); final String cycleName = cycleObject.get("name").getAsString(); final long id = Long.parseLong(key); cycles.put(cycleName, id); } } } } else { throw new IllegalArgumentException( String.format("Unexpected response status <%s> upon receipt of cycles <%s>", statusCode, url)); } } catch (IOException e) { throw new IllegalArgumentException(e); } return cycles; }
Source:
<code>public void testSTXY() throws Exception { assertQuery("select ST_X(ST_GeometryFromText('Point (1 2)'))", "select 1.0"); assertQuery("select ST_Y(ST_GeometryFromText('Point (1 2)'))", "select 2.0"); assertQueryFails("select ST_Y(ST_GeometryFromText('Polygon ((2 0, 2 1, 3 1))'))", "ST_Y only applies to Point. Input type is: Polygon"); <START> assertQueryFails("select ST_Y(ST_GeometryFromText('POINT EMPTY'))", "This operation should not be performed on an empty geometry."); <END> }</code><technical_language>spec, ST_Y of empty point return null</technical_language>

Target:
public void testSTXY() throws Exception { assertFunction("ST_Y(ST_GeometryFromText('POINT EMPTY'))", DOUBLE, null); assertFunction("ST_X(ST_GeometryFromText('POINT (1 2)'))", DOUBLE, 1.0); assertFunction("ST_Y(ST_GeometryFromText('POINT (1 2)'))", DOUBLE, 2.0); assertInvalidFunction("ST_Y(ST_GeometryFromText('POLYGON ((2 0, 2 1, 3 1))'))", "ST_Y only applies to POINT. Input type is: POLYGON"); }
Source:
<code>BundleContext getContext() { final Bundle cxfBundle = FrameworkUtil.getBundle(SecurityJavaSubjectFilter.class); <START> if (cxfBundle != null) { <END> return cxfBundle.getBundleContext(); } return null; }</code><technical_language>Annotate method @Nullable</technical_language>

Target:
protected BundleContext getContext() { final Bundle cxfBundle = FrameworkUtil.getBundle(SecurityJavaSubjectFilter.class); if (cxfBundle != null) { return cxfBundle.getBundleContext(); } return null; }
Source:
<code><START> public void setUp() throws Exception { <END> logged = false; appContext = E4Application.createDefaultContext(); appContext.set(IWorkbench.PRESENTATION_URI_ARG, PartRenderingEngine.engineURI); final Display d = Display.getDefault(); appContext.set(Realm.class, DisplayRealm.getRealm(d)); appContext.set(UISynchronize.class, new UISynchronize() { @Override public void syncExec(Runnable runnable) { d.syncExec(runnable); } @Override public void asyncExec(Runnable runnable) { d.asyncExec(runnable); } }); LogReaderService logReaderService = appContext.get(LogReaderService.class); logReaderService.addLogListener(listener); ems = appContext.get(EModelService.class); }</code><technical_language>I "throws Exception" is unnecessary</technical_language>

Target:
public void setUp() { logged = false; appContext = E4Application.createDefaultContext(); appContext.set(IWorkbench.PRESENTATION_URI_ARG, PartRenderingEngine.engineURI); final Display d = Display.getDefault(); appContext.set(Realm.class, DisplayRealm.getRealm(d)); appContext.set(UISynchronize.class, new UISynchronize() { @Override public void syncExec(Runnable runnable) { d.syncExec(runnable); } @Override public void asyncExec(Runnable runnable) { d.asyncExec(runnable); } }); LogReaderService logReaderService = appContext.get(LogReaderService.class); logReaderService.addLogListener(listener); ems = appContext.get(EModelService.class); }
Source:
<code>public void prepareRun(StageSubmitterContext context) throws Exception { super.prepareRun(context); context.record( <START> TransformLineageRecorderUtils.oneToOneIn(TransformLineageRecorderUtils.getFields(context.getInputSchema()), <END> "decode", "Decode the input fields based on expected decoder.")); }</code><technical_language>This is similar Compressor</technical_language>

Target:
public void prepareRun(StageSubmitterContext context) throws Exception { super.prepareRun(context); parseConfiguration(config.decode, context.getFailureCollector()); List<String> inFields = TransformLineageRecorderUtils.getFields(context.getInputSchema()); List<String> outFields = TransformLineageRecorderUtils.getFields(context.getOutputSchema()); List<String> identityFields = outFields.stream() .filter(field -> !decodeMap.containsKey(field) || decodeMap.get(field) == DecoderType.NONE) .collect(Collectors.toList()); List<String> processedFields = new ArrayList<>(outFields); processedFields.removeAll(identityFields); List<String> droppedFields = new ArrayList<>(inFields); droppedFields.removeAll(outFields); List<FieldOperation> output = new ArrayList<>(); output.addAll(TransformLineageRecorderUtils.generateOneToOnes(processedFields, "decode", "Decoded the input fields based on expected decoder.")); output.addAll(TransformLineageRecorderUtils.generateDrops(droppedFields)); output.addAll(TransformLineageRecorderUtils.generateOneToOnes(identityFields, "identity", TransformLineageRecorderUtils.IDENTITY_TRANSFORM_DESCRIPTION)); context.record(output); }
Source:
<code>private int newCapacity(int minCapacity) { int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity <= 0) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { return Math.max(DEFAULT_CAPACITY, minCapacity); } if (minCapacity < 0) { <START> throw new OutOfMemoryError(); <END> } return minCapacity; } return (newCapacity - MAX_ARRAY_SIZE <= 0) ? newCapacity : hugeCapacity(minCapacity); }</code><technical_language>this error type, this is expected thrown JVM >Thrown Java Virtual Machine allocate object is out of memory</technical_language>

Target:
private int newCapacity(int minCapacity) { int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity <= 0) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { return Math.max(DEFAULT_CAPACITY, minCapacity); } if (minCapacity < 0) { throw new RuntimeException("capacity overflow!"); } return minCapacity; } return (newCapacity - MAX_ARRAY_SIZE <= 0) ? newCapacity : hugeCapacity(minCapacity); }
Source:
<code>public void onComplete(Result result) { final long requestTime = System.currentTimeMillis() - start; try { emitter.emit( QueryMetricUtil.makeQueryTimeMetric(jsonMapper, query, req.getRemoteAddr()) <START> .build("request/time", requestTime) <END> ); requestLogger.log( new RequestLogLine( new DateTime(), req.getRemoteAddr(), query, new QueryStats( ImmutableMap.<String, Object>of( "request/time", requestTime, "success", true ) ) ) ); } catch (Exception e) { log.error(e, "Unable to log query [%s]!", query); } super.onComplete(result); }</code><technical_language>this "query/time" in line method name</technical_language>

Target:
public void onComplete(Result result) { final long requestTime = System.currentTimeMillis() - start; try { emitter.emit( DruidMetrics.makeQueryTimeMetric(jsonMapper, query, req.getRemoteAddr()) .build("query/time", requestTime) ); requestLogger.log( new RequestLogLine( new DateTime(), req.getRemoteAddr(), query, new QueryStats( ImmutableMap.<String, Object>of( "query/time", requestTime, "success", true ) ) ) ); } catch (Exception e) { log.error(e, "Unable to log query [%s]!", query); } super.onComplete(result); }
Source:
<code>private void mapBuildToDeploymentConfig(IBuild build) { String imageRef = imageRef(build, project); Collection<IDeploymentConfig> deploymentConfigs = imageRefToDeployConfigs.get(imageRef); <START> if(imageRefToDeployConfigs.containsKey(imageRef) && deploymentConfigs != null) { <END> for (IDeploymentConfig dc : deploymentConfigs) { createRelation(build, dc); } } }</code><technical_language>imageRefToDeployConfigs.containsKey(imageRef) is redundant</technical_language>

Target:
private void mapBuildToDeploymentConfig(IBuild build) { String imageRef = imageRef(build, project); Collection<IDeploymentConfig> deploymentConfigs = imageRefToDeployConfigs.get(imageRef); if(deploymentConfigs != null) { deploymentConfigs.forEach(dc->createRelation(build, dc)); } }
Source:
<code>private void resetConnectionMoveFeedbackToDefault() { Point newSourceRefPoint = getConnection().getSourceAnchor().getReferencePoint(); getConnection().translateToRelative(newSourceRefPoint); Point newTargetRefPoint = getConnection().getTargetAnchor().getReferencePoint(); getConnection().translateToRelative(newTargetRefPoint); List<Point> points = Lists.newArrayList(); points.add(newSourceRefPoint); points.add(newTargetRefPoint); changeRoutingConstraint(points, newSourceRefPoint, newTargetRefPoint); <START> <END> if (originalAnchor != null) { getConnection().setRoutingConstraint(originalConstraint); originalAnchor = null; } originalConstraint = null; }</code><technical_language>Uneeded spaces</technical_language>

Target:
private void resetConnectionMoveFeedbackToDefault() { Point newSourceRefPoint = getConnection().getSourceAnchor().getReferencePoint(); getConnection().translateToRelative(newSourceRefPoint); Point newTargetRefPoint = getConnection().getTargetAnchor().getReferencePoint(); getConnection().translateToRelative(newTargetRefPoint); List<Point> points = Lists.newArrayList(); points.add(newSourceRefPoint); points.add(newTargetRefPoint); changeRoutingConstraint(points, newSourceRefPoint, newTargetRefPoint); }
Source:
<code>public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; boolean keepAlive = HttpUtil.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); <START> if (keepAlive) { <END> ctx.write(response); } else { response.headers().set(CONNECTION, CLOSE); ctx.write(response).addListener(ChannelFutureListener.CLOSE); } } }</code><technical_language>@kachayev question... this assuming talking HTTP/1.1 ? I for 1.0 need add keep-alive imho</technical_language>

Target:
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; boolean keepAlive = HttpUtil.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); if (keepAlive && req.protocolVersion().equals(HttpVersion.HTTP_1_0)) { response.headers().set(CONNECTION, KEEP_ALIVE); } else { response.headers().set(CONNECTION, CLOSE); } ChannelFuture f = ctx.write(response); if (!keepAlive) { f.addListener(ChannelFutureListener.CLOSE); } } }
Source:
<code>public void validateAttributeIds(final BindingResult errors, final List<String> attributeIds) { if (attributeIds == null) { return; } <START> for (final String id: attributeIds) { <END> final Attribute attribute = this.germplasmDataManager.getAttributeById(Integer.valueOf(id)); if (attribute == null) { errors.reject("attribute.invalid", ""); return; } } }</code><technical_language>Instead of a for, implement a search set of ids compare size of collections</technical_language>

Target:
public void validateAttributeIds(final BindingResult errors, final List<String> attributeIds) { if (attributeIds == null || attributeIds.isEmpty()) { return; } final List<Integer> ids = attributeIds.stream().map(attributeId -> Integer.valueOf(attributeId)).distinct().collect(Collectors.toList()); final List<Attribute> attributes = this.germplasmDataManager.getAttributeByIds(ids); if (attributes.size() != ids.size()) { errors.reject("attribute.invalid", ""); return; } }
Source:
<code>public EvaluationResult evaluate(IEvaluationContext context) throws CoreException { Object root = context.getDefaultVariable(); if (root instanceof File) { return EvaluationResult.valueOf( new File((File)root, this.path).isDirectory() ); } else if (root instanceof IContainer) { return EvaluationResult.valueOf( ((IContainer)root).getFolder(new Path(this.path)).exists() ); } else if (root instanceof IAdaptable) { <START> IContainer container = ((IAdaptable)root).getAdapter(IContainer.class); <END> return EvaluationResult.valueOf( container.getFolder(new Path(this.path)).exists() ); } return EvaluationResult.FALSE; }</code><technical_language>Adapters.adapt</technical_language>

Target:
public EvaluationResult evaluate(IEvaluationContext context) throws CoreException { Object root = context.getDefaultVariable(); if (root instanceof File) { return EvaluationResult.valueOf( new File((File)root, this.path).isDirectory() ); } else { IContainer container = Adapters.adapt(root, IContainer.class); return EvaluationResult.valueOf( container.getFolder(new Path(this.path)).exists() ); } }
Source:
<code>private boolean addService(Microservice service) { Map<String, MicroservicesRegistryImpl> microservicesRegistries = org.wso2.msf4j.internal.DataHolder.getInstance().getMicroservicesRegistries(); if (microservicesRegistries.isEmpty()) { log.error("Microservice deployment failed. Microservices Registry doesn't exist to register microservice."); return false; } <START> microservicesRegistries.values().forEach(registry -> registry.addService(service)); <END> log.info("Microservice deployed successfully"); return true; }</code><technical_language>need a mechanism microservices get exposed ports. this implementation, services get exposed ports. is ok for create Issue address in future</technical_language>

Target:
private boolean addService(Microservice service) { Map<String, MicroservicesRegistryImpl> microservicesRegistries = org.wso2.msf4j.internal.DataHolder.getInstance().getMicroservicesRegistries(); if (microservicesRegistries.isEmpty()) { log.error("Microservice deployment failed. Microservices Registry doesn't exist to register microservice."); return false; } microservicesRegistries.values().forEach(registry -> registry.addService(service)); log.info("Microservice deployed successfully", service.getClass().getName()); return true; }
Source:
<code>public void setupMockElide() { HashMapDataStore inMemoryStore = new HashMapDataStore(AsyncQuery.class.getPackage()); Map<String, Class<? extends Check>> checkMappings = new HashMap<>(); elide = new Elide( new ElideSettingsBuilder(inMemoryStore) .withEntityDictionary(new EntityDictionary(checkMappings)) .build()); asyncQueryDao = mock(DefaultAsyncQueryDAO.class); <START> queryObj1 = mock(AsyncQuery.class); <END> queryObj2 = mock(AsyncQuery.class); queryObj3 = mock(AsyncQuery.class); testUser = mock(User.class); AsyncExecutorService.init(elide, 5, 60, asyncQueryDao); service = AsyncExecutorService.getInstance(); asyncQueryUpdateThread = mock(AsyncQueryUpdateThread.class); }</code><technical_language>is reason mocks global - created in test function</technical_language>

Target:
public void setupMockElide() { HashMapDataStore inMemoryStore = new HashMapDataStore(AsyncQuery.class.getPackage()); Map<String, Class<? extends Check>> checkMappings = new HashMap<>(); elide = new Elide( new ElideSettingsBuilder(inMemoryStore) .withEntityDictionary(new EntityDictionary(checkMappings)) .build()); asyncQueryDao = mock(DefaultAsyncQueryDAO.class); testUser = mock(User.class); AsyncExecutorService.init(elide, 5, 60, asyncQueryDao); service = AsyncExecutorService.getInstance(); asyncQueryUpdateThread = mock(AsyncQueryUpdateThread.class); }
Source:
<code>protected Command getOpenCommand(Request request) { EditPart targetEditPart = getTargetEditPart(request); if (targetEditPart instanceof IGraphicalEditPart) { IGraphicalEditPart editPart = (IGraphicalEditPart) targetEditPart; View view = editPart.getNotationView(); if (view != null) { EObject element = <START> ViewUtil.resolveSemanticElement(view); if (element instanceof DRepresentationDescriptor) { DRepresentationDescriptor descriptor = (DRepresentationDescriptor) element; EditPartViewer viewer = editPart.getViewer(); IEditorPart editor = (IEditorPart) ((DiagramEditDomain) viewer.getEditDomain()).getDiagramEditorPart(); Session session = ((SessionEditorInput) editor.getEditorInput()).getSession(); return new ICommandProxy(new GMFCommandWrapper(session.getTransactionalEditingDomain(), new NavigateToCommand(session, descriptor.getRepresentation()))); } <END> } } return null; }</code><technical_language>simplify this with: Optional<Session> optionalSession = Session.of(element); if (element instanceof DRepresentationDescriptor && optionalSession.isPresent()) { DRepresentationDescriptor descriptor = (DRepresentationDescriptor) element; Session session = optionalSession.get(); return new ICommandProxy(new GMFCommandWrapper(session.getTransactionalEditingDomain(), new NavigateToCommand(session, descriptor.getRepresentation()))); }</technical_language>

Target:
protected Command getOpenCommand(Request request) { EditPart targetEditPart = getTargetEditPart(request); if (targetEditPart instanceof IGraphicalEditPart) { IGraphicalEditPart editPart = (IGraphicalEditPart) targetEditPart; View view = editPart.getNotationView(); if (view != null) { EObject element = ViewUtil.resolveSemanticElement(view); if (element instanceof DRepresentationDescriptor) { DRepresentationDescriptor descriptor = (DRepresentationDescriptor) element; Optional<Session> sessionOption = Session.of(descriptor); if (sessionOption.isPresent()) { Session session = sessionOption.get(); return new ICommandProxy(new GMFCommandWrapper(session.getTransactionalEditingDomain(), new NavigateToCommand(session, descriptor.getRepresentation()))); } } } } return null; }
Source:
<code>public Header getLabel() { <START> return (Header)label; <END> }</code><technical_language>(Header) getLabel instead</technical_language>

Target:
public Header getLabel() { return (Header) super.getLabel(); }
Source:
<code>private void checkField(final CertifiedProductSearchDetails product, final Object field, final String errorField) { if (field instanceof Long) { Long fieldCasted = (Long) field; if (fieldCasted.toString().length() > getMaxLength("maxLength." + errorField)) { <START> CertifiedProductSearchDetails productCasted = (CertifiedProductSearchDetails) product; <END> productCasted.getErrorMessages().add(msgUtil.getMessage("listing." + errorField + ".maxlength", String.valueOf(getMaxLength("maxLength." + errorField)), fieldCasted)); } } else if (field instanceof String) { String fieldCasted = (String) field; if (fieldCasted.length() > getMaxLength("maxLength." + errorField)) { CertifiedProductSearchDetails productCasted = (CertifiedProductSearchDetails) product; productCasted.getErrorMessages().add(msgUtil.getMessage("listing." + errorField + ".maxlength", String.valueOf(getMaxLength("maxLength." + errorField)), fieldCasted)); } } }</code><technical_language>I this new code, wondering cast CertifiedProductSearchDetails is done passed-in "product" is of type? clean this a bit</technical_language>

Target:
private void checkField(final CertifiedProductSearchDetails product, final Object field, final String errorField) { if (field instanceof Long) { Long fieldCasted = (Long) field; if (fieldCasted.toString().length() > getMaxLength("maxLength." + errorField)) { product.getErrorMessages().add(msgUtil.getMessage("listing." + errorField + ".maxlength", String.valueOf(getMaxLength("maxLength." + errorField)), fieldCasted)); } } else if (field instanceof String) { String fieldCasted = (String) field; if (fieldCasted.length() > getMaxLength("maxLength." + errorField)) { product.getErrorMessages().add(msgUtil.getMessage("listing." + errorField + ".maxlength", String.valueOf(getMaxLength("maxLength." + errorField)), fieldCasted)); } } }
Source:
<code>public Mono<Response<AnalyzeSentimentResultCollection>> analyzeSentimentBatch( <START> Iterable<TextDocumentInput> documents, AnalyzeSentimentOptions options) { <END> try { inputDocumentsValidation(documents); return withContext(context -> getAnalyzedSentimentResponse(documents, options == null ? false : options.isIncludeOpinionMining(), options == null ? null : options.getRequestOptions(), context)); } catch (RuntimeException ex) { return monoError(logger, ex); } }</code><technical_language>This a breaking change, ok that</technical_language>

Target:
public Mono<Response<AnalyzeSentimentResultCollection>> analyzeSentimentBatch( Iterable<TextDocumentInput> documents, AnalyzeSentimentOptions options) { try { inputDocumentsValidation(documents); return withContext(context -> getAnalyzedSentimentResponse(documents, options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } }
Source:
<code><START> @Override public String toString() <END> { return "MetaData{metadata=" + metadata + '}'; }</code><technical_language>XWiki codestyle</technical_language>

Target:
public String toString() { return "MetaData{metadata=" + metadata + '}'; }
Source:
<code>public static <T> NotifyingFuture<Void> andThen(final NotifyingFuture<T> future, final Runnable after, final ExecutorService executorService) { final NotifyingFutureImpl<Void> result = new NotifyingFutureImpl<>(); final CountDownLatch countDownLatch = new CountDownLatch(1); Future afterFuture = executorService.submit(new Runnable() { @Override public void run() { try { countDownLatch.await(); future.get(); after.run(); result.notifyDone(null); } catch (InterruptedException e) { future.cancel(true); Thread.currentThread().interrupt(); } catch (Exception e) { result.notifyException(e); } } }); result.setFuture(afterFuture); FutureListener<T> listener = new FutureListener<T>() { @Override public void futureDone(Future<T> future) { countDownLatch.countDown(); } }; <START> if (future.isDone()) { <END> listener.futureDone(future); } else { future.attachListener(listener); } return result; }</code><technical_language>this lead a race condition? safer attach listener. I expect attachListener this check for you</technical_language>

Target:
public static <T> NotifyingFuture<Void> andThen(final NotifyingFuture<T> future, final Runnable after, final ExecutorService executorService) { final NotifyingFutureImpl<Void> result = new NotifyingFutureImpl<>(); final CountDownLatch countDownLatch = new CountDownLatch(1); Future afterFuture = executorService.submit(new Runnable() { @Override public void run() { try { countDownLatch.await(); future.get(); after.run(); result.notifyDone(null); } catch (InterruptedException e) { future.cancel(true); Thread.currentThread().interrupt(); } catch (Exception e) { result.notifyException(e); } } }); result.setFuture(afterFuture); FutureListener<T> listener = new FutureListener<T>() { @Override public void futureDone(Future<T> future) { countDownLatch.countDown(); } }; future.attachListener(listener); return result; }
Source:
<code>public boolean doMonitor(ServiceEmitter emitter) { final ServiceMetricEvent.Builder builder = new ServiceMetricEvent.Builder(); MonitorUtils.addDimensionsToBuilder( builder, dimensions ); <START> emitter.emit(builder.build("jetty/numConns", activeConnections.get())); <END> return true; }</code><technical_language>this is a query metric I metric "query/jetty/numOpenConnections"</technical_language>

Target:
public boolean doMonitor(ServiceEmitter emitter) { final ServiceMetricEvent.Builder builder = new ServiceMetricEvent.Builder(); MonitorUtils.addDimensionsToBuilder( builder, dimensions ); emitter.emit(builder.build("jetty/numOpenConnections", activeConnections.get())); return true; }
Source:
<code>public TextView getDayOfMonthTextView() { if (dayOfMonthTextView == null) { <START> throw new IllegalStateException( <END> "You have to setDayMonthOfView in your custom DayViewAdapter." ); } return dayOfMonthTextView; }</code><technical_language>nit: throw new IllegalStateException( "You setDayMonthOfView in custom DayViewAdapter.");</technical_language>

Target:
public TextView getDayOfMonthTextView() { if (dayOfMonthTextView == null) { throw new IllegalStateException( "You have to setDayOfMonthTextView in your custom DayViewAdapter." ); } return dayOfMonthTextView; }
Source:
<code>public CompletableFuture<Object> executeClientCommand(ExecuteCommandParams params) { <START> return executeCliendCommandTransmitter.executeClientCommand(params); <END> }</code><technical_language>This is a place recognize specific commands transform file:///projects uri's</technical_language>

Target:
public CompletableFuture<Object> executeClientCommand(ExecuteCommandParams params) { return executeCliendCommandTransmitter.executeClientCommand(convertParams(params)); }
Source:
<code>public SettableFuture schedule(SourceScheduler scheduler) { checkState(initialScheduled); List<Lifespan> recentlyCompletedDriverGroups; synchronized (this) { recentlyCompletedDriverGroups = ImmutableList.copyOf(this.recentlyCompletedDriverGroups); this.recentlyCompletedDriverGroups.clear(); newDriverGroupReady = SettableFuture.create(); } for (Lifespan driverGroup : recentlyCompletedDriverGroups) { if (!driverGroups.hasNext()) { break; } int driverGroupId = driverGroups.nextInt(); checkState(!bucketNodeMap.getAssignedNode(driverGroupId).isPresent()); <START> Node nodeForCompletedDriverGroup = bucketNodeMap.getAssignedNode(driverGroup.getId()).get(); <END> bucketNodeMap.assignOrChangeBucketToNode(driverGroupId, nodeForCompletedDriverGroup); scheduler.startLifespan(Lifespan.driverGroup(driverGroupId), partitionHandles.get(driverGroupId)); } if (!driverGroups.hasNext()) { scheduler.noMoreLifespans(); } return newDriverGroupReady; }</code><technical_language>bucketNodeMap.getAssignedNode(driverGroup.getId()).orThrow(IllegalStateException::new)</technical_language>

Target:
public SettableFuture schedule(SourceScheduler scheduler) { checkState(initialScheduled); List<Lifespan> recentlyCompletedDriverGroups; synchronized (this) { recentlyCompletedDriverGroups = ImmutableList.copyOf(this.recentlyCompletedDriverGroups); this.recentlyCompletedDriverGroups.clear(); newDriverGroupReady = SettableFuture.create(); } for (Lifespan driverGroup : recentlyCompletedDriverGroups) { if (!driverGroups.hasNext()) { break; } int driverGroupId = driverGroups.nextInt(); Node nodeForCompletedDriverGroup = bucketNodeMap.getAssignedNode(driverGroup.getId()).orElseThrow(IllegalStateException::new); bucketNodeMap.assignBucketToNode(driverGroupId, nodeForCompletedDriverGroup); scheduler.startLifespan(Lifespan.driverGroup(driverGroupId), partitionHandles.get(driverGroupId)); } if (!driverGroups.hasNext()) { scheduler.noMoreLifespans(); } return newDriverGroupReady; }
Source:
<code>private void stopVms() { List<VM> vmsInPool = DbFacade.getInstance().getVmDao().getAllForVmPool(getVmPoolId()); for (VM vm : vmsInPool) { if (!vm.isDown()) { CommandCoordinatorUtil.executeAsyncCommand( VdcActionType.StopVm, withRootCommandInfo(new StopVmParameters(vm.getId(), StopVmTypeEnum.NORMAL), getActionType()), <START> cloneContextAndDetachFromParent()); <END> } } }</code><technical_language>is async part for stop VM right? do need command-coordinator here</technical_language>

Target:
private boolean stopVms() { for (VM vm : getVmsInPool()) { if (!vm.isDown()) { VdcReturnValueBase result = runInternalAction( VdcActionType.StopVm, withRootCommandInfo(new StopVmParameters(vm.getId(), StopVmTypeEnum.NORMAL), getActionType()), cloneContextAndDetachFromParent()); if (!result.getSucceeded()) { return false; } } } }
Source:
<code>private Dictionary<String, Object> copyConfigProperties( Dictionary<String, Object> properties, String factoryPid) { Dictionary<String, Object> copiedProperties = new Hashtable<>(); ObjectClassDefinition objectClassDefinition = getObjectClassDefinition(factoryPid); if (objectClassDefinition == null) { <START> return copiedProperties; <END> } Stream.of(objectClassDefinition) .map(ocd -> ocd.getAttributeDefinitions(ObjectClassDefinition.ALL)) .flatMap(Arrays::stream) .map(AttributeDefinition::getID) .filter(id -> properties.get(id) != null) .forEach(id -> copiedProperties.put(id, properties.get(id))); return copiedProperties; }</code><technical_language>returning empty map of properties? If this happens, a system internal error? throwing exception</technical_language>

Target:
private Dictionary<String, Object> copyConfigProperties( Dictionary<String, Object> properties, String factoryPid) { final Dictionary<String, Object> copiedProperties = new Hashtable<>(); ObjectClassDefinition objectClassDefinition = getObjectClassDefinition(factoryPid); if (objectClassDefinition == null) { LOGGER.debug( "ObjectClassDefinition not found for factoryPid: {}. Unable to copy properties.", factoryPid); throw new IllegalStateException( "ObjectClassDefinition not found for factoryPid: " + factoryPid); } Stream.of(objectClassDefinition) .map(ocd -> ocd.getAttributeDefinitions(ObjectClassDefinition.ALL)) .flatMap(Arrays::stream) .map(AttributeDefinition::getID) .forEach(id -> copyIfDefined(id, properties, copiedProperties)); copyIfDefined( RegistryConstants.CONFIGURATION_REGISTRY_ID_PROPERTY, properties, copiedProperties); return copiedProperties; }
Source:
<code>public void resourceOffers(final SchedulerDriver driver, final List<Offer> offers) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("> resourceOffers(driver : {}, offers : {})", driver, protoToString(offers)); } <START> configuration.getSeedManager().syncSeeds(clock.now().getMillis()); <END> for (final Offer offer : offers) { final Marker marker = MarkerFactory.getMarker("offerId:" + offer.getId().getValue() + ",hostname:" + offer.getHostname()); final boolean offerUsed = evaluateOffer(driver, marker, offer); if (!offerUsed) { LOGGER.trace(marker, "Declining Offer: {}", offer.getId().getValue()); driver.declineOffer(offer.getId()); } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("< resourceOffers(driver : {}, offers : {})", driver, protoToString(offers)); } }</code><technical_language>Correct, want offer cycle control impacted need of seed manager refresh info</technical_language>

Target:
public void resourceOffers(final SchedulerDriver driver, final List<Offer> offers) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("> resourceOffers(driver : {}, offers : {})", driver, protoToString(offers)); } for (final Offer offer : offers) { final Marker marker = MarkerFactory.getMarker("offerId:" + offer.getId().getValue() + ",hostname:" + offer.getHostname()); final boolean offerUsed = evaluateOffer(driver, marker, offer); if (!offerUsed) { LOGGER.trace(marker, "Declining Offer: {}", offer.getId().getValue()); driver.declineOffer(offer.getId()); } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("< resourceOffers(driver : {}, offers : {})", driver, protoToString(offers)); } }
Source:
<code><START> public void setUp() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, IOException{ <END> virusInputStream = setupInputStream(ATTACHMENT_TEST_FILE_PATH + File.separator + VIRUS_FILE_NAME); goodInputStream = setupInputStream(ATTACHMENT_TEST_FILE_PATH + File.separator + GOOD_FILE_NAME); noteVirus = setupMockNote(String.valueOf(new Guid())); attachmentService = new CuAttachmentServiceImpl(); attachmentService.setKualiConfigurationService(buildMockConfigurationService()); attachmentService.setAttachmentDao(buildMockAttachmentDao()); attachmentService.setNoteService(buildMockNoteService()); attachmentService.setAntiVirusService(buildMockAntiVirusService()); attachment = new Attachment(); attachment.setObjectId(String.valueOf(new Guid())); attachment.setAttachmentIdentifier(attachment.getObjectId()); Note noteGood = setupMockNote(String.valueOf(new Guid())); attachment.setNote(noteGood); createAttachmentFile(noteGood, GOOD_FILE_NAME); createAttachmentFile(noteVirus, VIRUS_FILE_NAME); }</code><technical_language>Missing space opening curly brace</technical_language>

Target:
public void setUp() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, IOException { virusInputStream = setupInputStream(ATTACHMENT_TEST_FILE_PATH + File.separator + VIRUS_FILE_NAME); goodInputStream = setupInputStream(ATTACHMENT_TEST_FILE_PATH + File.separator + GOOD_FILE_NAME); errorInputStream = setupInputStream(ATTACHMENT_TEST_FILE_PATH + File.separator + ERROR_FILE_NAME); noteVirus = setupMockNote(String.valueOf(new Guid())); attachmentService = new CuAttachmentServiceImpl(); attachmentService.setKualiConfigurationService(buildMockConfigurationService()); attachmentService.setAttachmentDao(buildMockAttachmentDao()); attachmentService.setNoteService(buildMockNoteService()); attachmentService.setAntiVirusService(buildMockAntiVirusService()); attachment = new Attachment(); attachment.setObjectId(String.valueOf(new Guid())); attachment.setAttachmentIdentifier(attachment.getObjectId()); Note noteGood = setupMockNote(String.valueOf(new Guid())); attachment.setNote(noteGood); createAttachmentFile(noteGood, GOOD_FILE_NAME); createAttachmentFile(noteVirus, VIRUS_FILE_NAME); }
Source:
<code>public void write_record_bulk() { final RecordStorage<I> storage = getStorage(); final int bulkSize = 5; final Map<I, EntityRecordWithStorageFields> initial = new HashMap<>(bulkSize); for (int i = 0; i < bulkSize; i++) { final I id = newId(); final EntityRecord record = newStorageRecord(id); initial.put(id, new EntityRecordWithStorageFields(record)); } storage.write(initial); final Collection<EntityRecord> actual = newLinkedList( storage.readMultiple(initial.keySet()) ); final Collection<EntityRecord> expected = <START> Collections2.transform(initial.values(), <END> new Function<EntityRecordWithStorageFields, EntityRecord>() { @Override public EntityRecord apply(@Nullable EntityRecordWithStorageFields record) { assertNotNull(record); return record.getRecord(); } }); assertEquals(expected.size(), actual.size()); assertTrue(actual.containsAll(expected)); close(storage); }</code><technical_language>please 100 symbols wide in tests well</technical_language>

Target:
public void write_record_bulk() { final RecordStorage<I> storage = getStorage(); final int bulkSize = 5; final Map<I, EntityRecordWithColumns> initial = new HashMap<>(bulkSize); for (int i = 0; i < bulkSize; i++) { final I id = newId(); final EntityRecord record = newStorageRecord(id); initial.put(id, EntityRecordWithColumns.of(record)); } storage.write(initial); final Collection<EntityRecord> actual = newLinkedList( storage.readMultiple(initial.keySet()) ); final Collection<EntityRecord> expected = Collections2.transform(initial.values(), RECORD_EXTRACTOR_FUNCTION); assertEquals(expected.size(), actual.size()); assertTrue(actual.containsAll(expected)); close(storage); }
Source:
<code>public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Parameter)) return false; Parameter parameter = (Parameter) o; <START> return Objects.equals(key, parameter.key) && <END> Objects.equals(value, parameter.value); }</code><technical_language>equals key</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Parameter)) return false; Parameter parameter = (Parameter) o; return Objects.equals(key, parameter.key); }