auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void adjustDesiredPosition(SolGame game) { List<SolObject> objects = game.getObjMan().getObjs(); for (SolObject object : objects) { if (object instanceof Asteroid) { Asteroid asteroid = (Asteroid) object; Vector2 fromPosition = asteroid.getPosition(); Vector2 distanceVector = SolMath.distVec(fromPosition, position); float distance = SolMath.hypotenuse(distanceVector.x, distanceVector.y); if (distance <= asteroid.getSize() && distance <= size) { if (asteroid.getSize() > size) { distanceVector.scl((asteroid.getSize() + .5f) / distance); } else { distanceVector.scl((size + .5f) / distance); } position = fromPosition.cpy().add(distanceVector); <START> SolMath.free(SolMath.distVec(fromPosition, position)); <END> } SolMath.free(distanceVector); } } }</code><technical_language>whaaaat This line sense me. Care explain it</technical_language>

Target:
private void adjustDesiredPosition(SolGame game) { List<SolObject> objects = game.getObjMan().getObjs(); for (SolObject object : objects) { if (object instanceof Asteroid) { Asteroid asteroid = (Asteroid) object; Vector2 asteroidPosition = asteroid.getPosition(); Vector2 distanceFromAsteroid = SolMath.distVec(asteroidPosition, position); float distance = SolMath.hypotenuse(distanceFromAsteroid.x, distanceFromAsteroid.y); if (distance <= asteroid.getSize() && distance <= size) { if (asteroid.getSize() > size) { distanceFromAsteroid.scl((asteroid.getSize() + .5f) / distance); } else { distanceFromAsteroid.scl((size + .5f) / distance); } position = asteroidPosition.add(distanceFromAsteroid); } SolMath.free(distanceFromAsteroid); } } }
Source:
<code>private boolean removeService(Microservice service) { Map<String, MicroservicesRegistryImpl> microservicesRegistries = org.wso2.msf4j.internal.DataHolder.getInstance().getMicroservicesRegistries(); if (microservicesRegistries.isEmpty()) { log.error("Microservice removal failed. Microservices Registry doesn't exist to register microservice."); return false; } microservicesRegistries.values().forEach(registry -> { registry.removeService(service.getClass() .getAnnotation(Path.class).value()); registry.preDestroyService(service); }); <START> log.info("Microservice undeployed successfully"); <END> return true; }</code><technical_language>Include microservice classname path in log message</technical_language>

Target:
private boolean removeService(Microservice service) { Map<String, MicroservicesRegistryImpl> microservicesRegistries = org.wso2.msf4j.internal.DataHolder.getInstance().getMicroservicesRegistries(); if (microservicesRegistries.isEmpty()) { log.error("Microservice removal failed. Microservices Registry doesn't exist to register microservice."); return false; } microservicesRegistries.values().forEach(registry -> { registry.removeService(service.getClass() .getAnnotation(Path.class).value()); registry.preDestroyService(service); }); log.info("Microservice undeployed successfully", service.getClass().getName()); return true; }
Source:
<code>public List<GlusterServerService> getByServerIdAndServiceType(Guid serverId, ServiceType serviceType) { MapSqlParameterSource paramSource = getCustomMapSqlParameterSource(); paramSource.addValue("server_id", serverId); <START> paramSource.addValue("servive_type", serviceType); <END> return getCallsHandler().executeReadList("GetGlusterServerServicesByServerIdAndServiceType", serviceRowMapper, paramSource); }</code><technical_language>Typo here. service_type</technical_language>

Target:
public List<GlusterServerService> getByServerIdAndServiceType(Guid serverId, ServiceType serviceType) { MapSqlParameterSource paramSource = getCustomMapSqlParameterSource(); paramSource.addValue("server_id", serverId); paramSource.addValue("service_type", EnumUtils.nameOrNull(serviceType)); return getCallsHandler().executeReadList("GetGlusterServerServicesByServerIdAndServiceType", serviceRowMapper, paramSource); }
Source:
<code>public void initializeTaskToolbox() throws S3ServiceException { if (taskToolbox == null) { final RestS3Service s3Client = new RestS3Service( new AWSCredentials( props.getProperty("com.metamx.aws.accessKey"), <START> props.getProperty("com.metamx.aws.secretKey") <END> ) ); final SegmentPusher segmentPusher = new S3SegmentPusher( s3Client, configFactory.build(S3SegmentPusherConfig.class), jsonMapper ); taskToolbox = new TaskToolbox(coordinatorConfig, emitter, s3Client, segmentPusher, jsonMapper); } }</code><technical_language>revert changes PropUtils? PropUtils provide a meaningful exception properties set, generates NPE</technical_language>

Target:
public void initializeTaskToolbox() throws S3ServiceException { if (taskToolbox == null) { final RestS3Service s3Client = new RestS3Service( new AWSCredentials( PropUtils.getProperty(props, "com.metamx.aws.accessKey"), PropUtils.getProperty(props, "com.metamx.aws.secretKey") ) ); final SegmentPusher segmentPusher = new S3SegmentPusher( s3Client, configFactory.build(S3SegmentPusherConfig.class), jsonMapper ); taskToolbox = new TaskToolbox(coordinatorConfig, emitter, s3Client, segmentPusher, jsonMapper); } }
Source:
<code>private boolean useInSetQueryClause(List<RexNode> disjunctions) { <START> Set<String> leftFieldNameSet = new HashSet<>(); <END> return disjunctions.stream().allMatch(node -> { if (node.getKind() != SqlKind.EQUALS) { return false; } RexCall call = (RexCall) node; final RexNode left = call.operands.get(0); final RexNode right = call.operands.get(1); if (right.getKind() != SqlKind.LITERAL) { return false; } String name = getLeftNodeFieldName(left); if (name == null) { return false; } leftFieldNameSet.add(name); if (leftFieldNameSet.size() != 1) { return false; } return true; }); }</code><technical_language>Is avoid "global" variable (leftFieldNameSet) ? "state" in lambda. Is necessary</technical_language>

Target:
private boolean useInSetQueryClause(List<RexNode> disjunctions) { if (disjunctions.size() == 0) { return false; } return disjunctions.stream().allMatch(node -> { if (node.getKind() != SqlKind.EQUALS) { return false; } RexCall call = (RexCall) node; final RexNode left = call.operands.get(0); final RexNode right = call.operands.get(1); if (right.getKind() != SqlKind.LITERAL) { return false; } String name = getLeftNodeFieldName(left); if (name == null) { return false; } return true; }); }
Source:
<code>public void mcFooterIsPresentOnENwiki() { MixedContentFooter MCFooter = new MixedContentFooter(driver); <START> MCFooter.openWikiMainPage().scrollToFooter(); <END> Assertion.assertTrue(MCFooter.isMcfooterPresent()); }</code><technical_language>@qaga .scrollToFooter() method is intended scroll global footer, MCF. Depending screen resolution test is executed (and jenkins ;) test is doing, test fali. IMO write a method .scrollToMixContentFooter() other tests instead of .scrollToFooter</technical_language>

Target:
public void mcFooterIsPresentOnENwiki() { MixedContentFooter mcFooter = new MixedContentFooter(); mcFooter.openWikiMainPage().scrollToMCFooter(); Assertion.assertTrue(mcFooter.isMCFooterPresent()); }
Source:
<code>private boolean parseSwitchs(String[] args, int i) throws Exception { boolean result = false; if (checkSwitch(args, NO_USER_AGENT, i)) { HttpSender.setUserAgent(""); Constant.setEyeCatcher(""); result = true; } else if (checkSwitch(args, SP, i)) { Constant.setSP(true); result = true; } else if (checkSwitch(args, CMD, i)) { setDaemon(false); setGUI(false); } else if (checkSwitch(args, DAEMON, i)) { setDaemon(true); setGUI(false); } else if (checkSwitch(args, LOWMEM, i)) { setLowMem(true); } else if (checkSwitch(args, EXPERIMENTALDB, i)) { setExperimentalDb(true); } else if (checkSwitch(args, HELP, i)) { result = true; setGUI(false); } else if (checkSwitch(args, HELP2, i)) { result = true; setGUI(false); } else if (checkSwitch(args, VERSION, i)) { reportVersion = true; setDaemon(false); setGUI(false); <START> } if (checkSwitch(args, NOSTDOUT, i)) { <END> noStdOutLog = true; } return result; }</code><technical_language>Shouldnt this 'else if'? If layouts wrong ;)</technical_language>

Target:
private boolean parseSwitchs(String[] args, int i) throws Exception { boolean result = false; if (checkSwitch(args, NO_USER_AGENT, i)) { HttpSender.setUserAgent(""); Constant.setEyeCatcher(""); result = true; } else if (checkSwitch(args, SP, i)) { Constant.setSP(true); result = true; } else if (checkSwitch(args, CMD, i)) { setDaemon(false); setGUI(false); } else if (checkSwitch(args, DAEMON, i)) { setDaemon(true); setGUI(false); } else if (checkSwitch(args, LOWMEM, i)) { setLowMem(true); } else if (checkSwitch(args, EXPERIMENTALDB, i)) { setExperimentalDb(true); } else if (checkSwitch(args, HELP, i)) { result = true; setGUI(false); } else if (checkSwitch(args, HELP2, i)) { result = true; setGUI(false); } else if (checkSwitch(args, VERSION, i)) { reportVersion = true; setDaemon(false); setGUI(false); } else if (checkSwitch(args, NOSTDOUT, i)) { noStdOutLog = true; } return result; }
Source:
<code>protected LoadingCache<Credentials, String> provideTokenCache(Function<Credentials, String> getToken) { <START> return CacheBuilder.newBuilder().expireAfterWrite(30, TimeUnit.MINUTES).build(CacheLoader.from(getToken)); <END> }</code><technical_language>Expire a bit earlier, e.g. 29min? risk (small is) of expired token is avoided</technical_language>

Target:
protected LoadingCache<Credentials, String> provideTokenCache(Function<Credentials, String> getToken) { return CacheBuilder.newBuilder().expireAfterWrite(29, TimeUnit.MINUTES).build(CacheLoader.from(getToken)); }
Source:
<code>private HttpPipeline createPipeline() { if (pipeline != null) { return pipeline; } final Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; final List<HttpPipelinePolicy> httpPolicies = new ArrayList<>(); final String clientName = properties.getOrDefault("name", "UnknownName"); final String clientVersion = properties.getOrDefault("version", "UnknownVersion"); <START> final String applicationId = CoreUtils.validateApplicationId(httpLogOptions, clientOptions, new IllegalStateException("applicationId should be same in httpLogOptions and clientOptions.")); <END> httpPolicies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); httpPolicies.add(new ServiceBusTokenCredentialHttpPolicy(tokenCredential)); httpPolicies.add(new AddHeadersFromContextPolicy()); HttpPolicyProviders.addBeforeRetryPolicies(httpPolicies); httpPolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); httpPolicies.addAll(userPolicies); httpPolicies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPolicyProviders.addAfterRetryPolicies(httpPolicies); return new HttpPipelineBuilder() .policies(httpPolicies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); }</code><technical_language>I need do this. deprecate HttpLogOptions one, precedence clientOptions (so clientOptions is set)</technical_language>

Target:
private HttpPipeline createPipeline() { if (pipeline != null) { return pipeline; } final Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; final List<HttpPipelinePolicy> httpPolicies = new ArrayList<>(); final String clientName = properties.getOrDefault("name", "UnknownName"); final String clientVersion = properties.getOrDefault("version", "UnknownVersion"); String logApplicationId = null; if (httpLogOptions != null) { logApplicationId = httpLogOptions.getApplicationId(); } String clientApplicationId = null; if (clientOptions != null && clientOptions.getApplicationId() != null) { clientApplicationId = clientOptions.getApplicationId(); } if (logApplicationId != null && clientApplicationId != null && !logApplicationId.equalsIgnoreCase(clientApplicationId)) { throw logger.logExceptionAsError(new IllegalStateException( "'httpLogOptions.getApplicationId() and clientOptions.getApplicationId()' cannot be different.")); } final String applicationId = clientApplicationId != null ? clientApplicationId : logApplicationId; httpPolicies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); httpPolicies.add(new ServiceBusTokenCredentialHttpPolicy(tokenCredential)); httpPolicies.add(new AddHeadersFromContextPolicy()); HttpPolicyProviders.addBeforeRetryPolicies(httpPolicies); httpPolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); httpPolicies.addAll(userPolicies); httpPolicies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPolicyProviders.addAfterRetryPolicies(httpPolicies); return new HttpPipelineBuilder() .policies(httpPolicies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); }
Source:
<code>public static LogLevel fromString(String logLevelVal) { <START> if (logLevelVal == null) { <END> return null; } return LOG_LEVEL_STRING_MAPPER.get(logLevelVal.toLowerCase(Locale.ROOT)); }</code><technical_language>A null arg instead throw IllegalArgumentExcpetion unexpected/invalid input</technical_language>

Target:
public static LogLevel fromString(String logLevelVal) { if (logLevelVal == null) { return LogLevel.NOT_SET; } String caseInsensitiveLogLevel = logLevelVal.toLowerCase(Locale.ROOT); if (!LOG_LEVEL_STRING_MAPPER.containsKey(caseInsensitiveLogLevel)) { throw new IllegalArgumentException("We currently do not support the log level you set. LogLevel: " + logLevelVal); } return LOG_LEVEL_STRING_MAPPER.get(caseInsensitiveLogLevel); }
Source:
<code>public void onReceivedClientCertRequest (WebView view, final ClientCertRequest request){ Logger.v(TAG + "onReceivedClientCertRequest", "onReceivedClientCertRequest"); KeyChain.choosePrivateKeyAlias(AuthenticationActivity.this, new KeyChainAliasCallback() { @Override public void alias(String alias) { try { final X509Certificate[] certChain = KeyChain.getCertificateChain( getApplicationContext(), alias); final PrivateKey privateKey = KeyChain.getPrivateKey(mCallingContext, alias); request.proceed(privateKey, certChain); } catch (KeyChainException e) { Log.e(TAG, "KeyChain exception", e); } catch (InterruptedException e) { <START> Log.e(TAG, "KeyChain exception", e); <END> } } }, request.getKeyTypes(), request.getPrincipals(), request.getHost(), request.getPort(), null); }</code><technical_language>Interrupted exception instead of KeyChain exception</technical_language>

Target:
public void onReceivedClientCertRequest (WebView view, final ClientCertRequest request){ Logger.v(TAG + "onReceivedClientCertRequest", "onReceivedClientCertRequest"); KeyChain.choosePrivateKeyAlias(AuthenticationActivity.this, new KeyChainAliasCallback() { @Override public void alias(String alias) { try { final X509Certificate[] certChain = KeyChain.getCertificateChain( getApplicationContext(), alias); final PrivateKey privateKey = KeyChain.getPrivateKey(mCallingContext, alias); request.proceed(privateKey, certChain); } catch (KeyChainException e) { Log.e(TAG, "KeyChain exception", e); } catch (InterruptedException e) { Log.e(TAG, "InterruptedException exception", e); } } }, request.getKeyTypes(), request.getPrincipals(), request.getHost(), request.getPort(), null); }
Source:
<code>public boolean isDeletable() { <START> return printerId == UNSAVED_ID; <END> }</code><technical_language>deletable if saved</technical_language>

Target:
public boolean isDeletable() { return printerId != UNSAVED_ID; }
Source:
<code>public QueryRequest createQueryRequest(String localSource, FilterBuilder filterBuilder) { List<SortBy> sortBys = sorts .stream() .filter( s -> StringUtils.isNotEmpty(s.getAttribute()) && StringUtils.isNotEmpty(s.getDirection())) .map(s -> parseSort(s.getAttribute(), s.getDirection())) .collect(Collectors.toList()); if (sortBys.isEmpty()) { sortBys.add(new SortByImpl(Result.TEMPORAL, DEFAULT_SORT_ORDER)); } Query query = new QueryImpl(createFilter(filterBuilder), start, count, sortBys.get(0), true, timeout); String source = parseSrc(localSource); QueryRequest queryRequest; if (CACHE_SOURCE.equals(source)) { queryRequest = new QueryRequestImpl(query, true); queryRequest.getProperties().put("mode", "cache"); } else { queryRequest = new QueryRequestImpl(query, Collections.singleton(source)); queryRequest.getProperties().put("mode", "update"); } if (excludeUnnecessaryAttributes) { queryRequest .getProperties() .put("excludeAttributes", Sets.newHashSet(Metacard.METADATA, "lux")); } if (sortBys.size() > 1) { queryRequest .getProperties() <START> .put("additional.sorts.bys", sortBys.subList(1, sortBys.size()).toArray(new SortBy[0])); <END> } return queryRequest; }</code><technical_language>is reasonable (and be) places this leverage a single constant</technical_language>

Target:
public QueryRequest createQueryRequest(String localSource, FilterBuilder filterBuilder) { List<SortBy> sortBys = sorts .stream() .filter( s -> StringUtils.isNotEmpty(s.getAttribute()) && StringUtils.isNotEmpty(s.getDirection())) .map(s -> parseSort(s.getAttribute(), s.getDirection())) .collect(Collectors.toList()); if (sortBys.isEmpty()) { sortBys.add(new SortByImpl(Result.TEMPORAL, DEFAULT_SORT_ORDER)); } Query query = new QueryImpl(createFilter(filterBuilder), start, count, sortBys.get(0), true, timeout); String source = parseSrc(localSource); QueryRequest queryRequest; if (CACHE_SOURCE.equals(source)) { queryRequest = new QueryRequestImpl(query, true); queryRequest.getProperties().put("mode", "cache"); } else { queryRequest = new QueryRequestImpl(query, Collections.singleton(source)); queryRequest.getProperties().put("mode", "update"); } if (excludeUnnecessaryAttributes) { queryRequest .getProperties() .put("excludeAttributes", Sets.newHashSet(Metacard.METADATA, "lux")); } if (sortBys.size() > 1) { queryRequest .getProperties() .put(ADDITIONAL_SORT_BYS, sortBys.subList(1, sortBys.size()).toArray(new SortBy[0])); } return queryRequest; }
Source:
<code>public void testFull() throws Exception { <START> Command c = new Command(IO.getJavaExecutablePath("java") + " -Dx=\"foo bar\" -version"); <END> assertThat(c.getArguments()).containsExactly(IO.getJavaExecutablePath("java"), "-Dx=\"foo bar\"", "-version"); assertThat(c.execute(System.out, System.err)).isZero(); }</code><technical_language>I realized this fail if absolute path string contains a space full string is parsed spaces (This is full command string). for this test method, need revert prior state (using simple java command) delete final assert execute method. confirmed execution works in testSimple this method confirms full argument parsing, avoid assert execute here</technical_language>

Target:
public void testFull() throws Exception { Command c = new Command("app -Dx=\"foo bar\" -version"); assertThat(c.getArguments()).containsExactly("app", "-Dx=\"foo bar\"", "-version"); c = new Command().full("app -Dx=\"foo bar\" -version"); assertThat(c.getArguments()).containsExactly("app", "-Dx=\"foo bar\"", "-version"); }
Source:
<code>protected static boolean indexLimitReached(Index index, Map<String, Object> existingIndexes) { if (index.indexType == IndexType.TEXT) { for (String name : existingIndexes.keySet()) { Map<String, Object> existingIndex = (Map<String, Object>) existingIndexes.get(name); String type = (String) existingIndex.get("type"); <START> if (IndexType.enumValue(type) == IndexType.TEXT && <END> !name.equalsIgnoreCase(index.indexName)) { logger.log(Level.SEVERE, String.format("The text index %s already exists. ", name) + "One text index per datastore permitted. " + String.format("Delete %s and recreate %s.", name, index.indexName)); return true; } } } return false; }</code><technical_language>I confused existingIndexes structure some sort of deserialised JSON! I listIndexesInDatabase similar methods return more self-describing data types, this include of Enum. This limit conversion enums strings database specific code in IndexManager</technical_language>

Target:
protected static boolean indexLimitReached(Index index, Map<String, Object> existingIndexes) { if (index.indexType == IndexType.TEXT) { for (String name : existingIndexes.keySet()) { Map<String, Object> existingIndex = (Map<String, Object>) existingIndexes.get(name); IndexType type = (IndexType) existingIndex.get("type"); if (type == IndexType.TEXT && !name.equalsIgnoreCase(index.indexName)) { logger.log(Level.SEVERE, String.format("The text index %s already exists. ", name) + "One text index per datastore permitted. " + String.format("Delete %s and recreate %s.", name, index.indexName)); return true; } } } return false; }
Source:
<code>public void waitForVoteCountChangeTimeLagToPass() { try { Thread.sleep(2000); } catch (InterruptedException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>added logError</technical_language>

Target:
public Post waitForVoteCountChangeTimeLagToPass() { try { Thread.sleep(2000); } catch (InterruptedException e) { PageObjectLogging.logError("waitForVoteCountChangeTimeLagToPass", e); } return this; }
Source:
<code>public void startElement(final String namespaceURI, final String localName, final String qName, final Attributes attrs) throws SAXException { if (enabled) { try { if (isCSS(localName, attrs)) { String sheet = attrs.getValue("", "href"); if (inHead) { stylesheetsInHead.add(sheet); } else { log.debug("Inlining stylesheet link found in BODY: '{}'", sheet); inlineSheet(namespaceURI, sheet); } } else { getContentHandler().startElement(namespaceURI, localName, qName, attrs); if (localName.equalsIgnoreCase(HEAD)) { inHead = true; } else if (localName.equalsIgnoreCase(BODY)) { <START> for (String sheet : stylesheetsInHead) { <END> log.debug("Inlining sheet found in HEAD: '{}'", sheet); inlineSheet(namespaceURI, sheet); } } } } catch (Exception e) { log.error("Exception in stylesheet inliner", e); throw new SAXException(e); } } else { getContentHandler().startElement(namespaceURI, localName, qName, attrs); } }</code><technical_language>more sense inline </head> tag</technical_language>

Target:
public void startElement(final String namespaceURI, final String localName, final String qName, final Attributes attrs) throws SAXException { try { if (SAXElementUtils.isCSS(localName, attrs)) { String sheet = attrs.getValue("", "href"); if (!afterHeadElement) { stylesheetsInHead.add(sheet); } else { log.debug("Inlining stylesheet link found in BODY: '{}'", sheet); inlineSheet(namespaceURI, sheet); } } else { getContentHandler().startElement(namespaceURI, localName, qName, attrs); } } catch (Exception e) { log.error("Exception in stylesheet inliner", e); throw new SAXException(e); } }
Source:
<code>public void undeploy(Object key) throws CarbonDeploymentException { if (!(key instanceof String)) { throw new CarbonDeploymentException("Error while Un Deploying : " + key + "is not a String value"); } logger.info("Undeploying : " + key); File fileToUndeploy; <START> if (key.equals("sample1.txt")) { <END> fileToUndeploy = new File(testDir + File.separator + key); } else if (key.equals("sample2.txt")) { fileToUndeploy = new File(testDir2 + File.separator + key); } else { throw new CarbonDeploymentException("Error while Un Deploying : " + key); } logger.info("File to undeploy : " + fileToUndeploy.getAbsolutePath()); try (FileInputStream fis = new FileInputStream(fileToUndeploy)) { int x = fis.available(); byte b[] = new byte[x]; fis.read(b); String content = new String(b); if (content.contains("sample1")) { sample1Deployed = false; } else if (content.contains("sample2")) { sample2Deployed = false; } } catch (IOException e) { throw new CarbonDeploymentException("Error while Un Deploying : " + key, e); } }</code><technical_language>turn-around equal check for avoiding NPEs ? For ex: "something".equals(string)</technical_language>

Target:
public void undeploy(Object key) throws CarbonDeploymentException { if (!(key instanceof String)) { throw new CarbonDeploymentException("Error while Un Deploying : " + key + "is not a String value"); } logger.info("Undeploying : " + key); File fileToUndeploy; if ("sample1.txt".equals(key)) { fileToUndeploy = new File(testDir + File.separator + key); } else if ("sample2.txt".equals(key)) { fileToUndeploy = new File(testDir2 + File.separator + key); } else { throw new CarbonDeploymentException("Error while Un Deploying : " + key); } logger.info("File to undeploy : " + fileToUndeploy.getAbsolutePath()); try (FileInputStream fis = new FileInputStream(fileToUndeploy)) { int x = fis.available(); byte b[] = new byte[x]; fis.read(b); String content = new String(b); if (content.contains("sample1")) { sample1Deployed = false; } else if (content.contains("sample2")) { sample2Deployed = false; } } catch (IOException e) { throw new CarbonDeploymentException("Error while Un Deploying : " + key, e); } }
Source:
<code>private TimeValue getTimeValue(JSONObject jsonTimeValue) throws JSONException { TimeValue result; String stringTime = jsonTimeValue.getString("time"); String[] substrings = stringTime.split("(?<!\\A)[\\-\\:TZ]"); <START> long year = Long.parseLong(substrings[0]); <END> byte month = Byte.parseByte(substrings[1]); byte day = Byte.parseByte(substrings[2]); byte hour = Byte.parseByte(substrings[3]); byte minute = Byte.parseByte(substrings[4]); byte second = Byte.parseByte(substrings[5]); byte precision = (byte) jsonTimeValue.getInt("precision"); int beforeTolerance = jsonTimeValue.getInt("before"); int afterTolerance = jsonTimeValue.getInt("after"); int timezoneOffset = jsonTimeValue.getInt("timezone"); String calendarModel = jsonTimeValue.getString("calendarmodel"); result = this.factory.getTimeValue(year, month, day, hour, minute, second, precision, beforeTolerance, afterTolerance, timezoneOffset, calendarModel); return result; }</code><technical_language>want catch NumberFormatExceptions transform suitable exceptions. try-catch-block enough, recover this error anyway</technical_language>

Target:
private TimeValue getTimeValue(JSONObject jsonTimeValue) throws JSONException { String stringTime = jsonTimeValue.getString("time"); String[] substrings = stringTime.split("(?<!\\A)[\\-\\:TZ]"); long year = Long.parseLong(substrings[0]); byte month = Byte.parseByte(substrings[1]); byte day = Byte.parseByte(substrings[2]); byte hour = Byte.parseByte(substrings[3]); byte minute = Byte.parseByte(substrings[4]); byte second = Byte.parseByte(substrings[5]); byte precision = (byte) jsonTimeValue.getInt("precision"); int beforeTolerance = jsonTimeValue.getInt("before"); int afterTolerance = jsonTimeValue.getInt("after"); int timezoneOffset = jsonTimeValue.getInt("timezone"); String calendarModel = jsonTimeValue.getString("calendarmodel"); return this.factory.getTimeValue(year, month, day, hour, minute, second, precision, beforeTolerance, afterTolerance, timezoneOffset, calendarModel); }
Source:
<code>public void startup() { initServerBootstrap(); ChannelFuture channelFuture; if (!Strings.isNullOrEmpty(configuration.getHost())) { channelFuture = serverBootstrap.bind(configuration.getHost(), configuration.getPort()); } else { channelFuture = serverBootstrap.bind(configuration.getPort()); } channelFuture.addListener(future -> { if (future.isSuccess()) { log.info("Restful Service started on port {}.", configuration.getPort()); } else { <START> log.error("", future.cause()); <END> } }); }</code><technical_language>Give more error info instead of empty more friendly</technical_language>

Target:
public void startup() { initServerBootstrap(); ChannelFuture channelFuture; if (!Strings.isNullOrEmpty(configuration.getHost())) { channelFuture = serverBootstrap.bind(configuration.getHost(), configuration.getPort()); } else { channelFuture = serverBootstrap.bind(configuration.getPort()); } channelFuture.addListener(future -> { if (future.isSuccess()) { log.info("Restful Service started on port {}.", configuration.getPort()); } else { log.error("Failed to start Restful Service.", future.cause()); } }); }
Source:
<code>public DeleteObjectsResult deleteObjects( DeleteObjectsRequest deleteObjectsRequest) throws AmazonClientException, AmazonServiceException { for (DeleteObjectsRequest.KeyVersion keyVersion : deleteObjectsRequest.getKeys()) { registerDeleteObject(keyVersion.getKey(), deleteObjectsRequest .getBucketName()); } <START> maybeFail(); <END> return super.deleteObjects(deleteObjectsRequest); }</code><technical_language>move failure point for loop</technical_language>

Target:
public DeleteObjectsResult deleteObjects(DeleteObjectsRequest deleteObjectsRequest) throws AmazonClientException, AmazonServiceException { maybeFail(); for (DeleteObjectsRequest.KeyVersion keyVersion : deleteObjectsRequest.getKeys()) { registerDeleteObject(keyVersion.getKey(), deleteObjectsRequest.getBucketName()); } return super.deleteObjects(deleteObjectsRequest); }
Source:
<code>public static Optional<ErrorType> fromByte(byte value) { switch (value) { case (byte) 0x00: <START> return Optional.of(Invalid); <END> case (byte) 0x01: return Optional.of(Timeout); case (byte) 0x02: return Optional.of(Cancelled); case (byte) 0x03: return Optional.of(Busy); case (byte) 0x04: return Optional.of(Declined); case (byte) 0x05: return Optional.of(UnexpectedError); case (byte) 0x06: return Optional.of(BadRequest); case (byte) 0x07: return Optional.of(NetworkError); case (byte) 0x08: return Optional.of(Unhealthy); case (byte) 0xff: return Optional.of(FatalProtocolError); default: return Optional.empty(); } }</code><technical_language>Optional is java 8, I base of logic</technical_language>

Target:
public static ErrorType fromByte(byte value) { switch (value) { case (byte) 0x00: return Invalid; case (byte) 0x01: return Timeout; case (byte) 0x02: return Cancelled; case (byte) 0x03: return Busy; case (byte) 0x04: return Declined; case (byte) 0x05: return UnexpectedError; case (byte) 0x06: return BadRequest; case (byte) 0x07: return NetworkError; case (byte) 0x08: return Unhealthy; case (byte) 0xff: return FatalProtocolError; default: return null; } }
Source:
<code><START> public HttpProtocolAwareExceptionTranslator(AtlasDbHttpProtocolHandler<E> httpProtocolHandler) { <END> this.httpProtocolHandler = httpProtocolHandler; }</code><technical_language>get this instantiate hk2 manually</technical_language>

Target:
HttpProtocolAwareExceptionTranslator(AtlasDbHttpProtocolHandler<E> httpProtocolHandler) { this.httpProtocolHandler = httpProtocolHandler; }
Source:
<code>public Repo<Master> call(long tid, Master environment) throws Exception { KeyExtent extent = new KeyExtent(tableInfo.tableId, null, null); MetadataTableUtil.addTablet(extent, tableInfo.dir, environment, tableInfo.timeType, environment.getMasterLock()); <START> if (tableInfo.props.containsKey(Property.TABLE_OFFLINE_OPTS + "create.initial.splits")) { <END> return new CreateInitialSplits(tableInfo); } else { return new FinishCreateTable(tableInfo); } }</code><technical_language>I cloned this branch play moving adding splits this class. I writing function. I this function work for 0 more splits. I realized while attempting this exercise is current code is dir for tablet is ideal (it work). dirFunction represents this TODO. java private void writeSplitsToMetadataTable(Table.ID tableId, SortedMap<Text> splits, Function<Text,Value> dirFunction, char timeType, ZooLock lock, BatchWriter bw) { Text prevSplit = null; for(Text split : Iterables.concat(splits, Collections.singleton(null))) { Mutation mut = new KeyExtent(tableId, split, prevSplit).getPrevRowUpdateMutation(); ServerColumnFamily.DIRECTORY_COLUMN.put(mut, dirFunction.apply(split)); ServerColumnFamily.TIME_COLUMN.put(mut, new Value(timeType+"0")); MetadataTableUtil.putLockID(lock, mut); prevSplit = split; bw.addMutation(mut); } } handle this is do following. * In ChooseDir FATE step, read in splits choose a dir for split. Write out a new file dirs. * In CreateDir FATE step, read file dirs create them. * In PopulateMetadata FATE step, read file dirs for creating rows in metadata table</technical_language>

Target:
public Repo<Master> call(long tid, Master environment) throws Exception { KeyExtent extent = new KeyExtent(tableInfo.tableId, null, null); MetadataTableUtil.addTablet(extent, tableInfo.defaultTabletDir, environment, tableInfo.timeType, environment.getMasterLock()); if (tableInfo.initialSplitSize > 0) { SortedSet<Text> splits = Utils .getSortedSetFromFile(environment.getInputStream(tableInfo.splitFile), true); SortedSet<Text> dirs = Utils .getSortedSetFromFile(environment.getInputStream(tableInfo.splitDirsFile), false); Map<Text,Text> splitDirMap = createSplitDirectoryMap(splits, dirs); try (BatchWriter bw = environment.getConnector().createBatchWriter("accumulo.metadata")) { writeSplitsToMetadataTable(tableInfo.tableId, splits, splitDirMap, tableInfo.timeType, environment.getMasterLock(), bw); } } return new FinishCreateTable(tableInfo); }
Source:
<code>@Override public String getAllowedSignatures(String name) { return "<ARRAY>[<INTEGER>]\n" + "<MAP>[<VALUE>]\n" + "<ROW>[<CHARACTER>|<INTEGER>]"; <START> } <END></code><technical_language>keyword</technical_language>

Target:
@Override public String getAllowedSignatures(String name) { return "<ARRAY>[<INTEGER>]\n" + "<MAP>[<ANY>]\n" + "<ROW>[<CHARACTER>|<INTEGER>]"; }
Source:
<code>Grid createBlankRow(final HostInterfaceLineModel lineModel) { Grid row = new Grid(1, 4); row.getColumnFormatter().setWidth(0, VLanPanel.CHECK_BOX_COLUMN_WIDTH); row.getColumnFormatter().setWidth(1, VLanPanel.NETWORK_NAME_COLUMN_WIDTH); row.getColumnFormatter().setWidth(2, VLanPanel.OUT_OF_SYNC_WIDTH); <START> row.getColumnFormatter().setWidth(3, VLanPanel.ADDRESS_COLUMN_WIDTH); <END> row.setWidth("100%"); row.setHeight("100%"); row.setWidget(0, 0, new Label()); Label networkName = new Label(lineModel.getNetworkName()); if (lineModel.getIsManagement()) { networkName.getElement().getStyle().setFontWeight(FontWeight.BOLD); networkName.setText("* " + lineModel.getNetworkName()); } row.setWidget(0, 1, networkName); VdsNetworkInterface iface = lineModel.getIsBonded()? lineModel.getInterface() : lineModel.getInterfaces().get(0).getInterface(); VdsNetworkInterface.NetworkImplementationDetails ifaceNetworkImpDetails = (iface != null) ? iface.getNetworkImplementationDetails() : null; boolean isSYnc = (ifaceNetworkImpDetails != null) ? ifaceNetworkImpDetails.isInSync() : true; row.setWidget(0, 2, getSyncPanel(isSYnc)); row.setWidget(0, 3, new Label(lineModel.getAddress())); return row; }</code><technical_language>This code duplication bother you? create a preceding patch extracting common logic createRow() createBlankRow() a separate method, change this once</technical_language>

Target:
Grid createBlankRow(final HostInterfaceLineModel lineModel) { VdsNetworkInterface iface = lineModel.getIsBonded() ? lineModel.getInterface() : lineModel.getInterfaces().get(0).getInterface(); return createVlanRowColumn(new Label(), lineModel.getIsManagement(), lineModel.getNetworkName(), createSyncPanel(iface.getNetworkImplementationDetails().isInSync()), new Label(lineModel.getAddress())); }
Source:
<code>public QuotaViolationException(MetricName metricName, double value, double bound) { <START> super(metricName + " violated quota."); <END> this.metricName = metricName; this.value = value; this.bound = bound; }</code><technical_language>I want string computation lazy, lose info. do overriding toString</technical_language>

Target:
public QuotaViolationException(MetricName metricName, double value, double bound) { this.metricName = metricName; this.value = value; this.bound = bound; }
Source:
<code>public void loadProvidedPropertyFile(String fileName, Properties topologyProperties) throws IOException { File file = new File(fileName); <START> FileInputStream fileInput = new FileInputStream(file); <END> topologyProperties.load(fileInput); fileInput.close(); }</code><technical_language>Instead of creating a File object another FileInputStream constructor accepts file name</technical_language>

Target:
public void loadProvidedPropertyFile(String fileName, Properties topologyProperties) throws IOException { FileInputStream fileInput = new FileInputStream(fileName); topologyProperties.load(fileInput); fileInput.close(); }
Source:
<code>public LowLevelHttpResponse execute() throws IOException { if (getStreamingContent() != null) { Preconditions.checkArgument( <START> request instanceof HttpEntityEnclosingRequest, <END> "Apache HTTP client does not support %s requests with content.", request.getRequestLine().getMethod()); ContentEntity entity = new ContentEntity(getContentLength(), getStreamingContent()); entity.setContentEncoding(getContentEncoding()); entity.setContentType(getContentType()); if (getContentLength() == -1) { entity.setChunked(true); } ((HttpEntityEnclosingRequest) request).setEntity(entity); } return new ApacheHttpResponse(request, httpClient.execute(request)); }</code><technical_language>request is argument here. This checkState</technical_language>

Target:
public LowLevelHttpResponse execute() throws IOException { if (getStreamingContent() != null) { Preconditions.checkState( request instanceof HttpEntityEnclosingRequest, "Apache HTTP client does not support %s requests with content.", request.getRequestLine().getMethod()); ContentEntity entity = new ContentEntity(getContentLength(), getStreamingContent()); entity.setContentEncoding(getContentEncoding()); entity.setContentType(getContentType()); if (getContentLength() == -1) { entity.setChunked(true); } ((HttpEntityEnclosingRequest) request).setEntity(entity); } return new ApacheHttpResponse(request, httpClient.execute(request)); }
Source:
<code>public void testInheritSubmit_OverridesAndDeniesOfRef() { <START> inherited.add(grant(SUBMIT, registered, "refs/*", 1, 1)); <END> local.add(grant(SUBMIT, registered, "refs/*", -1, -1)); local.add(grant(SUBMIT, registered, "refs/heads/*", -1, 1)); ProjectControl u = user(); assertFalse("can't submit", u.controlForRef("refs/foobar").canSubmit()); assertTrue("can submit", u.controlForRef("refs/heads/foobar").canSubmit()); }</code><technical_language>1 (The single form of grant)</technical_language>

Target:
public void testInheritSubmit_OverridesAndDeniesOfRef() { grant(false, SUBMIT, registered, "refs/*", 1); grant(true, SUBMIT, registered, "refs/*", 0); grant(true, SUBMIT, registered, "refs/heads/*", -1, 1); ProjectControl u = user(); assertFalse("can't submit", u.controlForRef("refs/foobar").canSubmit()); assertFalse("can't submit", u.controlForRef("refs/tags/foobar").canSubmit()); assertTrue("can submit", u.controlForRef("refs/heads/foobar").canSubmit()); }
Source:
<code>public static String getObaRegionName() { String regionName = null; ObaRegion region = Application.get().getCurrentRegion(); if (region != null && region.getName() != null) { regionName = region.getName(); } else if (Application.get().getCustomApiUrl() != null) { <START> MessageDigest digest; <END> try { digest = MessageDigest.getInstance("SHA-1"); digest.update(Application.get().getCustomApiUrl().getBytes()); regionName = Application.get().getString(R.string.analytics_label_custom_url) + ": " + Application.getHex(digest.digest()); } catch (Exception e) { regionName = Application.get().getString(R.string.analytics_label_custom_url); } } return regionName; }</code><technical_language>please move URL hash code method? I this easier read understand is happening</technical_language>

Target:
public static String getObaRegionName() { String regionName = null; ObaRegion region = Application.get().getCurrentRegion(); if (region != null && region.getName() != null) { regionName = region.getName(); } else if (Application.get().getCustomApiUrl() != null) { regionName = createHashCode(Application.get().getCustomApiUrl().getBytes()); } return regionName; }
Source:
<code>protected void addListener() { <START> HashSet<Class> filterAnnotations = new HashSet<>(Arrays.asList(CacheEntryCreated.class, <END> CacheEntryModified.class, CacheEntryRemoved.class, CacheEntryExpired.class)); n.addFilteredListener(cl, null, new ToStringConverter(), filterAnnotations); }</code><technical_language>Util.asSet instead</technical_language>

Target:
protected void addListener() { Set<Class> filterAnnotations = Util.<Class> asSet(CacheEntryCreated.class, CacheEntryModified.class, CacheEntryRemoved.class, CacheEntryExpired.class); n.addFilteredListener(cl, null, (key, oldValue, oldMetadata, newValue, newMetadata, eventType) -> "custom event for test (" + eventType.getType().name() + "," + key + "," + newValue + ")", filterAnnotations); }
Source:
<code>public void testCreateMeasurementRowsFromEnvironments() { final MeasurementVariable variable = MeasurementVariableTestDataInitializer.createMeasurementVariable(TermId.PLOT_CODE.getId(), TermId.PLOT_CODE.name(), null); variable.setDataTypeId(TermId.NUMERIC_VARIABLE.getId()); final Instance instance = new Instance(); <START> instance.setStockId(1); <END> instance.setExperimentId(12); instance.setInstanceId(1); final List<MeasurementRow> row = WorkbookUtil.createMeasurementRowsFromEnvironments(Arrays.asList(instance), Arrays.asList(variable), new ExpDesignParameterUi()); Assert.assertNotNull(row); Assert.assertEquals(instance.getExperimentId(), row.get(0).getExperimentId()); Assert.assertEquals(instance.getStockId(), row.get(0).getStockId()); }</code><technical_language>test values for stock, experiment instance IDs for assertion</technical_language>

Target:
public void testCreateMeasurementRowsFromEnvironments() { final MeasurementVariable variable = MeasurementVariableTestDataInitializer.createMeasurementVariable(TermId.PLOT_CODE.getId(), TermId.PLOT_CODE.name(), null); variable.setDataTypeId(TermId.NUMERIC_VARIABLE.getId()); final Instance instance = new Instance(); instance.setStockId(Long.parseLong(RandomStringUtils.randomNumeric(5))); instance.setExperimentId(Integer.parseInt(RandomStringUtils.randomNumeric(5))); instance.setInstanceId(Long.parseLong(RandomStringUtils.randomNumeric(5))); final List<MeasurementRow> row = WorkbookUtil.createMeasurementRowsFromEnvironments(Arrays.asList(instance), Arrays.asList(variable), new ExpDesignParameterUi()); Assert.assertNotNull(row); Assert.assertEquals(instance.getExperimentId(), row.get(0).getExperimentId()); Assert.assertEquals(instance.getStockId(), row.get(0).getStockId()); }
Source:
<code>private void initFloatPredicate() { if (floatPredicate != null) { return; } synchronized (initLock) { if (floatPredicate != null) { return; } final Float valueAsFloat = Floats.tryParse(value); if (valueAsFloat == null) { floatPredicate = DruidFloatPredicate.ALWAYS_FALSE; } else { <START> final int floatInts = Float.floatToIntBits(valueAsFloat); <END> floatPredicate = new DruidFloatPredicate() { @Override public boolean applyFloat(float input) { return Float.floatToIntBits(input) == floatInts; } }; } } }</code><technical_language>Suggested "floatBits" "valueBits"</technical_language>

Target:
private void initFloatPredicate() { if (floatPredicate != null) { return; } synchronized (initLock) { if (floatPredicate != null) { return; } final Float valueAsFloat = Floats.tryParse(value); if (valueAsFloat == null) { floatPredicate = DruidFloatPredicate.ALWAYS_FALSE; } else { final int floatBits = Float.floatToIntBits(valueAsFloat); floatPredicate = new DruidFloatPredicate() { @Override public boolean applyFloat(float input) { return Float.floatToIntBits(input) == floatBits; } }; } } }
Source:
<code>public String getXML() { StringBuffer retval = new StringBuffer(); if (!Const.isEmpty(m_yamlPath)) { retval.append("\n ").append( XMLHandler.addTagValue("yaml_path", m_yamlPath)); } if (!Const.isEmpty(directory)) { retval.append("\n ").append( XMLHandler.addTagValue("output_directory", directory)); } if (!Const.isEmpty(cassandraKeyspace)) { retval.append("\n ").append( XMLHandler.addTagValue("cassandra_keyspace", cassandraKeyspace)); } if (!Const.isEmpty(cassandraKeyspace)) { retval.append("\n ").append( XMLHandler.addTagValue("cassandra_keyspace", cassandraKeyspace)); } if (!Const.isEmpty(columnFamily)) { retval.append("\n ").append( XMLHandler.addTagValue("column_family", columnFamily)); } if (!Const.isEmpty(keyField)) { retval.append("\n ").append( XMLHandler.addTagValue("key_field", keyField)); } if (!Const.isEmpty(bufferSize)) { retval.append("\n ").append( XMLHandler.addTagValue("buffer_size_mb", bufferSize)); } <START> retval.append("\n ").append( END> XMLHandler.addTagValue("use_cql3", m_useCQL3)); return retval.toString(); }</code><technical_language>This method tested a unit test. this change update ttest (but I it). If does, update tests pass. If not, please create one</technical_language>

Target:
public String getXML() { StringBuffer retval = new StringBuffer(); if ( !Const.isEmpty( m_yamlPath ) ) { retval.append( "\n " ).append( XMLHandler.addTagValue( "yaml_path", m_yamlPath ) ); } if ( !Const.isEmpty( directory ) ) { retval.append( "\n " ).append( XMLHandler.addTagValue( "output_directory", directory ) ); } if ( !Const.isEmpty( cassandraKeyspace ) ) { retval.append( "\n " ).append( XMLHandler.addTagValue( "cassandra_keyspace", cassandraKeyspace ) ); } if ( !Const.isEmpty( columnFamily ) ) { retval.append( "\n " ).append( XMLHandler.addTagValue( "column_family", columnFamily ) ); } if ( !Const.isEmpty( keyField ) ) { retval.append( "\n " ).append( XMLHandler.addTagValue( "key_field", keyField ) ); } if ( !Const.isEmpty( bufferSize ) ) { retval.append( "\n " ).append( XMLHandler.addTagValue( "buffer_size_mb", bufferSize ) ); } retval.append( "\n " ).append( XMLHandler.addTagValue( "use_cql3", m_useCQL3 ) ); return retval.toString(); }
Source:
<code>void moveAllEventsTo (Synchronizer toReceiveTheEvents) { RunnableLock[] oldMessages; int oldMessageCount; synchronized (messageLock) { oldMessages = messages; oldMessageCount = messageCount; messageCount = 0; } <START> toReceiveTheEvents.addFirst(oldMessages, oldMessageCount); <END> }</code><technical_language>worries is oldMessages is left unprotected calls in theory modified</technical_language>

Target:
void moveAllEventsTo (Synchronizer toReceiveTheEvents) { RunnableLock[] oldMessages; int oldMessageCount; synchronized (messageLock) { oldMessages = messages; messages = null; oldMessageCount = messageCount; messageCount = 0; } toReceiveTheEvents.addFirst(oldMessages, oldMessageCount); }
Source:
<code><START> public void setShowIgnoreFilesButtons(boolean showButtons) { <END> showButtonsState = showButtons; this.breakToolbarFactory.setShowIgnoreFilesButtons(showButtons); mainBreakButtons.setShowIgnoreFilesButtons(showButtons); requestBreakButtons.setShowIgnoreFilesButtons(showButtons); responseBreakButtons.setShowIgnoreFilesButtons(showButtons); }</code><technical_language>add internal API for now</technical_language>

Target:
protected void setShowIgnoreFilesButtons(boolean showButtons) { this.breakToolbarFactory.setShowIgnoreFilesButtons(showButtons); mainBreakButtons.setShowIgnoreFilesButtons(showButtons); requestBreakButtons.setShowIgnoreFilesButtons(showButtons); responseBreakButtons.setShowIgnoreFilesButtons(showButtons); }