auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static void sortByProvider(boolean reverse, AboutData[] infos) { if (reverse) { reverse(infos); return; } Arrays.sort(infos, new Comparator<AboutData>() { Collator collator = Collator.getInstance(Locale.getDefault()); <START> public int compare(AboutData a, AboutData b) { <END> AboutData info1 = a; AboutData info2 = b; String provider1 = info1.getProviderName(); String provider2 = info2.getProviderName(); if (!provider1.equals(provider2)) { return collator.compare(provider1, provider2); } return collator.compare(info1.getName(), info2.getName()); } }); }</code><technical_language>remove info1/2 = a/b change compare(*) parameters info1 info2. applied other parameters</technical_language>

Target:
public static void sortByProvider(boolean reverse, AboutData[] infos) { if (reverse) { reverse(infos); return; } Arrays.sort(infos, new Comparator<AboutData>() { Collator collator = Collator.getInstance(Locale.getDefault()); public int compare(AboutData info1, AboutData info2) { String provider1 = info1.getProviderName(); String provider2 = info2.getProviderName(); if (!provider1.equals(provider2)) { return collator.compare(provider1, provider2); } return collator.compare(info1.getName(), info2.getName()); } }); }
Source:
<code>public Artifact copyWithParameterizedUri() { Artifact newArtifact = new Artifact(artifactCoordinates, uri); File repositoryFolder = new File("repository"); String newUriPath = getFormattedOutputDirectory(repositoryFolder, toArtifact(this)).getPath(); <START> try { <END> newArtifact.setUri(new URI(newUriPath)); } catch (URISyntaxException e) { } return newArtifact; }</code><technical_language>please throw a runtime exception</technical_language>

Target:
public Artifact copyWithParameterizedUri() { Artifact newArtifact = new Artifact(artifactCoordinates, uri); File repositoryFolder = new File("repository"); String newUriPath = getFormattedOutputDirectory(repositoryFolder, toArtifact(this)).getPath(); try { newArtifact.setUri(new URI(newUriPath)); } catch (URISyntaxException e) { throw new RuntimeException("Could not generate URI for resource, the given path is invalid: " + newUriPath, e); } return newArtifact; }
Source:
<code><START> public ArrayList<String> getAllObjects(String path) <END> { ArrayList<String> objects = new ArrayList<String>(); if (!path.substring(path.length() - 1).equals("/")) { path += "/"; } ListObjectsV2Result listing = client.listObjectsV2(new ListObjectsV2Request() .withBucketName(bucketName) .withPrefix(path)); for (S3ObjectSummary objectSummary : listing.getObjectSummaries()) { if (!objectSummary.getKey().equals(path)) { objects.add(objectSummary.getKey()); } } return objects; }</code><technical_language>List</technical_language>

Target:
private List<String> getAllObjects(String path) { ListObjectsV2Result listing = client.listObjectsV2(new ListObjectsV2Request() .withBucketName(bucketName) .withPrefix(ensureTrailingSlashPresent(path))); return listing.getObjectSummaries().stream() .map(S3ObjectSummary::getKey) .filter(key -> !key.equals(ensureTrailingSlashPresent(path))) .collect(Collectors.toList()); }
Source:
<code>public Task start(final ReusableMachineTemplate template, final List<? extends Startable> entities) { BasicExecutionContext ctx = BasicExecutionContext.getCurrentExecutionContext(); if (ctx==null) throw new IllegalStateException("Pool.start is only permitted within a task (effector)"); <START> final Task t[] = new Task[1]; <END> t[0] = ctx.submit(new Runnable() { public void run() { if (log.isDebugEnabled()) log.debug("Pool "+this+", task "+t[0]+" claiming a "+template); SshMachineLocation m = claim(template); if (log.isDebugEnabled()) log.debug("Pool "+this+", task "+t[0]+" got "+m+"; starting "+entities); for (Startable entity: entities) addTask( ((Entity)entity).invoke(Startable.START, MutableMap.of("locations", Arrays.asList(m))) ); } }); addTask(t[0]); return t[0]; }</code><technical_language>Recommend AtomicReference<Task>, Task[]. run() initialized of t[] synchronized/volatile</technical_language>

Target:
public Task start(final ReusableMachineTemplate template, final List<? extends Startable> entities) { BasicExecutionContext ctx = BasicExecutionContext.getCurrentExecutionContext(); if (ctx==null) throw new IllegalStateException("Pool.start is only permitted within a task (effector)"); final AtomicReference<Task> t = new AtomicReference<Task>(); synchronized (t) { t.set(ctx.submit(new Runnable() { public void run() { synchronized (t) { if (log.isDebugEnabled()) log.debug("Pool "+this+", task "+t.get()+" claiming a "+template); SshMachineLocation m = obtain(template); if (log.isDebugEnabled()) log.debug("Pool "+this+", task "+t.get()+" got "+m+"; starting "+entities); for (Startable entity: entities) addTask( ((Entity)entity).invoke(Startable.START, MutableMap.of("locations", Arrays.asList(m))) ); } } })); } addTask(t.get()); return t.get(); }
Source:
<code>public synchronized void done() { if (!isCanceled()) { for (IEnabledTarget <START> fAction : <END> fActions) { fAction.setEnabled(fEnabled); } } }</code><technical_language>rename action</technical_language>

Target:
public synchronized void done() { if (!isCanceled()) { for (IEnabledTarget action : fActions) { action.setEnabled(fEnabled); } } }
Source:
<code>public void test_update_by_query_returning_multiple_results() throws Exception { execute("create table test (id int primary key, x int, message string) clustered into 2 shards"); execute("insert into test values(1, 1, 'msg');"); execute("insert into test values(2, 1, 'msg');"); assertEquals(1, response.rowCount()); refresh(); <START> execute("update test set message='updated' where message='msg' and x > 0 returning message as message_renamed"); <END> assertThat((response.rowCount()), is(2L )); assertThat((response.cols()[0]), is("message_renamed")); assertThat(response.rows()[0][0], is("updated")); assertThat(response.rows()[1][0], is("updated")); }</code><technical_language>add _seq_no RETURNING clause here. is of cases want enable</technical_language>

Target:
public void test_update_by_query_returning_multiple_results() throws Exception { execute("create table test (id int primary key, x int, message string) clustered into 2 shards"); execute("insert into test values(1, 1, 'msg');"); execute("insert into test values(2, 1, 'msg');"); assertEquals(1, response.rowCount()); refresh(); execute("update test set message='updated' where message='msg' and x > 0 " + "returning _docid, _seq_no as seq, message as message_renamed"); assertThat((response.rowCount()), is(2L)); assertThat((response.cols()[0]), is("_docid")); assertThat((response.cols()[1]), is("seq")); assertThat((response.cols()[2]), is("message_renamed")); assertThat(response.rows()[0][0], is(0)); assertThat(response.rows()[0][1], is(2L)); assertThat(response.rows()[0][2], is("updated")); assertThat(response.rows()[1][0], is(1)); assertThat(response.rows()[1][1], is(3L)); assertThat(response.rows()[1][2], is("updated")); }
Source:
<code>public void testSimpleIntrospectionHandler() throws Exception { <START> final Injector injector = Initialization.makeInjectorWithModules( <END> GuiceInjectors.makeStartupInjector(), ImmutableList.of( new Module() { @Override public void configure(Binder binder) { JsonConfigProvider.bindInstance( binder, Key.get(DruidNode.class, Self.class), new DruidNode("test-inject", null, null, null, new ServerConfig()) ); } } ) ); final ObjectMapper mapper = injector.getInstance(Key.get(ObjectMapper.class, Json.class)); mapper.registerSubtypes(NamespaceLookupExtractorFactory.class); final String str = "{ \"type\": \"cachedNamespace\", \"extractionNamespace\": { \"type\": \"staticMap\", \"map\": {\"foo\":\"bar\"} }, \"firstCacheTimeout\":10000 }"; final LookupExtractorFactory lookupExtractorFactory = mapper.readValue(str, LookupExtractorFactory.class); Assert.assertTrue(lookupExtractorFactory.start()); try { final LookupIntrospectHandler handler = lookupExtractorFactory.getIntrospectHandler(); Assert.assertNotNull(handler); final Class<? extends LookupIntrospectHandler> clazz = handler.getClass(); Assert.assertNotNull(clazz.getMethod("getVersion").invoke(handler)); Assert.assertEquals(ImmutableSet.of("foo"), ((Response) clazz.getMethod("getKeys").invoke(handler)).getEntity()); Assert.assertEquals( ImmutableSet.of("bar"), ((Response) clazz.getMethod("getValues").invoke(handler)).getEntity() ); Assert.assertEquals( ImmutableMap.builder().put("foo", "bar").build(), ((Response) clazz.getMethod("getMap").invoke(handler)).getEntity() ); } finally { Assert.assertTrue(lookupExtractorFactory.close()); } }</code><technical_language>This change necessary</technical_language>

Target:
public void testSimpleIntrospectionHandler() throws Exception { final Injector injector = makeInjector(); final ObjectMapper mapper = injector.getInstance(Key.get(ObjectMapper.class, Json.class)); mapper.registerSubtypes(NamespaceLookupExtractorFactory.class); final String str = "{ \"type\": \"cachedNamespace\", \"extractionNamespace\": { \"type\": \"staticMap\", \"map\": {\"foo\":\"bar\"} }, \"firstCacheTimeout\":10000 }"; final LookupExtractorFactory lookupExtractorFactory = mapper.readValue(str, LookupExtractorFactory.class); Assert.assertTrue(lookupExtractorFactory.start()); try { final LookupIntrospectHandler handler = lookupExtractorFactory.getIntrospectHandler(); Assert.assertNotNull(handler); final Class<? extends LookupIntrospectHandler> clazz = handler.getClass(); Assert.assertNotNull(clazz.getMethod("getVersion").invoke(handler)); Assert.assertEquals(ImmutableSet.of("foo"), ((Response) clazz.getMethod("getKeys").invoke(handler)).getEntity()); Assert.assertEquals( ImmutableSet.of("bar"), ((Response) clazz.getMethod("getValues").invoke(handler)).getEntity() ); Assert.assertEquals( ImmutableMap.builder().put("foo", "bar").build(), ((Response) clazz.getMethod("getMap").invoke(handler)).getEntity() ); } finally { Assert.assertTrue(lookupExtractorFactory.close()); } }
Source:
<code>public Token nextToken() throws IOException { if (pushCount > 0) { pushCount--; return token; } else if (upcomingToken.type != Tokenizer.TT_ERROR) { token.assign(upcomingToken); upcomingToken.type = Tokenizer.TT_ERROR; return token; } else { token.init(); char[] chr = new char[1]; while (hasMore()) { read(chr, 1); int symbolIndex = lookupSymbol(chr[0]); if (symbolIndex != -1) { TokenizerToken workToken = token.type == Tokenizer.TT_TOKEN && token.text.length() > 0 ? upcomingToken : token; <START> TokenizerSymbol symbol = (symbols.get(symbolIndex)); <END> boolean hideSymbol = symbol.hidden; if (!hideSymbol) { workToken.init(); workToken.text.append(symbol.startText); workToken.type = Tokenizer.TT_SYMBOL; workToken.name = symbol.name; } if (symbol.tailText != null) { while (hasMore() && !compare(symbol.tailText.toCharArray(), 0)) { read(chr, 1); if (!hideSymbol) { workToken.text.append(chr); workToken.innerText.append(chr); } } if (!hideSymbol) { workToken.text.append(symbol.tailText); } workToken.type = Tokenizer.TT_BLOCK; } if (token.text.length() > 0) { break; } } else { token.text.append(chr); token.type = Tokenizer.TT_TOKEN; } } } return token; }</code><technical_language>Extra parentheses removed</technical_language>

Target:
public Token nextToken() throws IOException { if (pushCount > 0) { pushCount--; return token; } else if (upcomingToken.type != Tokenizer.TT_ERROR) { token.assign(upcomingToken); upcomingToken.type = Tokenizer.TT_ERROR; return token; } else { token.init(); char[] chr = new char[1]; while (hasMore()) { read(chr, 1); int symbolIndex = lookupSymbol(chr[0]); if (symbolIndex != -1) { TokenizerToken workToken = token.type == Tokenizer.TT_TOKEN && token.text.length() > 0 ? upcomingToken : token; TokenizerSymbol symbol = ((TokenizerSymbol) symbols.get(symbolIndex)); boolean hideSymbol = symbol.hidden; if (!hideSymbol) { workToken.init(); workToken.text.append(symbol.startText); workToken.type = Tokenizer.TT_SYMBOL; workToken.name = symbol.name; } if (symbol.tailText != null) { while (hasMore() && !compare(symbol.tailText.toCharArray(), 0)) { read(chr, 1); if (!hideSymbol) { workToken.text.append(chr); workToken.innerText.append(chr); } } if (!hideSymbol) { workToken.text.append(symbol.tailText); } workToken.type = Tokenizer.TT_BLOCK; } if (token.text.length() > 0) { break; } } else { token.text.append(chr); token.type = Tokenizer.TT_TOKEN; } } } return token; }
Source:
<code>public static Double lineLocatePoint(@SqlType(GEOMETRY_TYPE_NAME) Slice lineSlice, @SqlType(GEOMETRY_TYPE_NAME) Slice pointSlice) { if (lineSlice == null || pointSlice == null) { return null; } <START> <END> Geometry line = JtsGeometrySerde.deserialize(lineSlice); Geometry point = JtsGeometrySerde.deserialize(pointSlice); if (line.isEmpty() || point.isEmpty()) { return null; } GeometryType lineType = getForJtsGeometryType(line.getGeometryType()); if (lineType != LINE_STRING && lineType != MULTI_LINE_STRING) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("First argument to line_locate_point must be a LineString or a MultiLineString. Got: %s", line.getGeometryType())); } GeometryType pointType = getForJtsGeometryType(point.getGeometryType()); if (pointType != POINT) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Second argument to line_locate_point must be a Point. Got: %s", point.getGeometryType())); } return new LengthIndexedLine(line).indexOf(point.getCoordinate()); }</code><technical_language>test semantics in posgresql</technical_language>

Target:
public static Double lineLocatePoint(@SqlType(GEOMETRY_TYPE_NAME) Slice lineSlice, @SqlType(GEOMETRY_TYPE_NAME) Slice pointSlice) { Geometry line = JtsGeometrySerde.deserialize(lineSlice); Geometry point = JtsGeometrySerde.deserialize(pointSlice); if (line.isEmpty() || point.isEmpty()) { return null; } GeometryType lineType = getForJtsGeometryType(line.getGeometryType()); if (lineType != LINE_STRING && lineType != MULTI_LINE_STRING) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("First argument to line_locate_point must be a LineString or a MultiLineString. Got: %s", line.getGeometryType())); } GeometryType pointType = getForJtsGeometryType(point.getGeometryType()); if (pointType != POINT) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Second argument to line_locate_point must be a Point. Got: %s", point.getGeometryType())); } return new LengthIndexedLine(line).indexOf(point.getCoordinate()); }
Source:
<code>public DiffBuilder append(final String fieldName, final Object lhs, final Object rhs) { if (objectsTriviallyEqual) { return this; } if (lhs == rhs) { return this; } Object objectToTest; if (lhs != null) { objectToTest = lhs; } else { objectToTest = rhs; } if (objectToTest.getClass().isArray()) { if (objectToTest instanceof boolean[]) { return append(fieldName, (boolean[]) lhs, (boolean[]) rhs); } if (objectToTest instanceof byte[]) { return append(fieldName, (byte[]) lhs, (byte[]) rhs); } if (objectToTest instanceof char[]) { return append(fieldName, (char[]) lhs, (char[]) rhs); } if (objectToTest instanceof double[]) { return append(fieldName, (double[]) lhs, (double[]) rhs); } if (objectToTest instanceof float[]) { return append(fieldName, (float[]) lhs, (float[]) rhs); } if (objectToTest instanceof int[]) { return append(fieldName, (int[]) lhs, (int[]) rhs); } if (objectToTest instanceof long[]) { return append(fieldName, (long[]) lhs, (long[]) rhs); } if (objectToTest instanceof short[]) { return append(fieldName, (short[]) lhs, (short[]) rhs); } return append(fieldName, (Object[]) lhs, (Object[]) rhs); } <START> if (left != null ? left.equals(right) : right.equals(left)) { <END> return this; } diffs.add(new Diff<Object>(fieldName) { private static final long serialVersionUID = 1L; @Override public Object getLeft() { return lhs; } @Override public Object getRight() { return rhs; } }); return this; }</code><technical_language>left != null true, constructor prevents field initialized null. If case, proposed code throw NPE if left right null</technical_language>

Target:
public DiffBuilder append(final String fieldName, final Object lhs, final Object rhs) { if (objectsTriviallyEqual) { return this; } if (lhs == rhs) { return this; } Object objectToTest; if (lhs != null) { objectToTest = lhs; } else { objectToTest = rhs; } if (objectToTest.getClass().isArray()) { if (objectToTest instanceof boolean[]) { return append(fieldName, (boolean[]) lhs, (boolean[]) rhs); } if (objectToTest instanceof byte[]) { return append(fieldName, (byte[]) lhs, (byte[]) rhs); } if (objectToTest instanceof char[]) { return append(fieldName, (char[]) lhs, (char[]) rhs); } if (objectToTest instanceof double[]) { return append(fieldName, (double[]) lhs, (double[]) rhs); } if (objectToTest instanceof float[]) { return append(fieldName, (float[]) lhs, (float[]) rhs); } if (objectToTest instanceof int[]) { return append(fieldName, (int[]) lhs, (int[]) rhs); } if (objectToTest instanceof long[]) { return append(fieldName, (long[]) lhs, (long[]) rhs); } if (objectToTest instanceof short[]) { return append(fieldName, (short[]) lhs, (short[]) rhs); } return append(fieldName, (Object[]) lhs, (Object[]) rhs); } if (lhs != null ? lhs.equals(rhs) : rhs.equals(lhs)) { return this; } diffs.add(new Diff<Object>(fieldName) { private static final long serialVersionUID = 1L; @Override public Object getLeft() { return lhs; } @Override public Object getRight() { return rhs; } }); return this; }
Source:
<code>public boolean saveAnswer(FormIndex index, IAnswerData data) throws JavaRosaException { try { return formEntryController.saveAnswer(index, data, true); } catch (Exception e) { <START> Timber.w("Error saving answer of type %s with ref %s for index %s", <END> data.getClass().toString(), index.getReference(), index); throw new JavaRosaException(e); } }</code><technical_language>this need Timber.e</technical_language>

Target:
public boolean saveAnswer(FormIndex index, IAnswerData data) throws JavaRosaException { try { return formEntryController.saveAnswer(index, data, true); } catch (Exception e) { String dataType = data != null ? data.getClass().toString() : null; String ref = index != null ? index.getReference().toString() : null; Timber.w("Error saving answer of type %s with ref %s for index %s", dataType, ref, index); throw new JavaRosaException(e); } }
Source:
<code>public void set(final boolean s) { if (Gerrit.isSignedIn() && s != get()) { final ToggleStarRequest req = new ToggleStarRequest(); req.toggle(cache.getChangeId(), s); <START> com.google.gerrit.client.changes.Util.LIST_SVC.toggleStars(req, new GerritCallback<VoidResult>() { <END> public void onSuccess(final VoidResult result) { setStarred(s); fireEvent(new ValueChangeEvent<Boolean>(s){}); } }); } }</code><technical_language>nit: remove package name 'Util', needed Util is in this class</technical_language>

Target:
public void set(final boolean s) { if (Gerrit.isSignedIn() && s != get()) { final ToggleStarRequest req = new ToggleStarRequest(); req.toggle(cache.getChangeId(), s); Util.LIST_SVC.toggleStars(req, new GerritCallback<VoidResult>() { public void onSuccess(final VoidResult result) { setStarred(s); fireEvent(new ValueChangeEvent<Boolean>(s){}); } }); } }
Source:
<code>protected KeySpec engineGetKeySpec(SecretKey secretKey, Class<?> aClass) throws InvalidKeySpecException { if (secretKey == null) { throw new InvalidKeySpecException("Null SecretKey"); } <START> if (aClass == SecretKeySpec.class) { return (KeySpec) secretKey; <END> } else if (aClass == DESedeKeySpec.class) { try { return new DESedeKeySpec(secretKey.getEncoded()); } catch (InvalidKeyException e) { throw new InvalidKeySpecException(e); } } else { throw new InvalidKeySpecException("Unsupported KeySpec class: " + aClass.getName()); } }</code><technical_language>i follow this works. (maybe rusty :( )</technical_language>

Target:
protected KeySpec engineGetKeySpec(SecretKey secretKey, Class<?> aClass) throws InvalidKeySpecException { if (secretKey == null) { throw new InvalidKeySpecException("Null SecretKey"); } if (aClass == SecretKeySpec.class) { if (secretKey instanceof SecretKeySpec) { return (KeySpec) secretKey; } else { return new SecretKeySpec(secretKey.getEncoded(), "DESEDE"); } } else if (aClass == DESedeKeySpec.class) { try { return new DESedeKeySpec(secretKey.getEncoded()); } catch (InvalidKeyException e) { throw new InvalidKeySpecException(e); } } else { throw new InvalidKeySpecException("Unsupported KeySpec class: " + aClass); } }
Source:
<code>Bound(DoubleArray xValues, DoubleArray yValues, BoundCurveInterpolator interpolator) { <START> this.interpolator = (AbstractBoundCurveInterpolator) interpolator; <END> }</code><technical_language>Suggest adding ArgChecker.isTrue(interpolator instanceof AbstractBoundCurveInterpolator); get a error message</technical_language>

Target:
Bound(DoubleArray xValues, DoubleArray yValues, BoundCurveInterpolator interpolator) { ArgChecker.isTrue(interpolator instanceof AbstractBoundCurveInterpolator); this.interpolator = (AbstractBoundCurveInterpolator) interpolator; }
Source:
<code>public void execute(HttpRequest req, HttpResponse resp) throws IOException { Map<String, Object> args = json.toType(req.getContentString(), Json.MAP_TYPE); String file = (String) args.get("file"); File tempDir = session.getFileSystem().createTempDir("upload", "file"); Zip.unzip(file, tempDir); File[] allFiles = tempDir.listFiles(); Response response = new Response(session.getId()); if (allFiles == null || allFiles.length != 1) { response.setStatus(ErrorCodes.UNHANDLED_ERROR); response.setValue(new WebDriverException( "Expected there to be only 1 file. There were: " + (allFiles == null ? 0 : allFiles.length))); } else { <START> Path uploads_dir = Files.createDirectories(tempDir.toPath().getParent().resolve("remote_uploads")); <END> Path dest = uploads_dir.resolve(allFiles[0].getName()); if (Files.exists(dest)){ Path prevFileDir = session.getFileSystem().createTempDir("prevupload", "file").toPath(); Files.move(dest, prevFileDir.resolve(allFiles[0].getName())); } dest = Files.move(allFiles[0].toPath(), dest, REPLACE_EXISTING); response.setStatus(ErrorCodes.SUCCESS); response.setValue(dest.toAbsolutePath().toString()); } session.getDownstreamDialect().getResponseCodec().encode(() -> resp, response); }</code><technical_language>Nit: Java naming conventions CamelCase: uploadsDir instead of uploads_dir</technical_language>

Target:
public void execute(HttpRequest req, HttpResponse resp) throws IOException { Map<String, Object> args = json.toType(req.getContentString(), Json.MAP_TYPE); String file = (String) args.get("file"); File tempDir = session.getFileSystem().createTempDir("upload", "file"); Zip.unzip(file, tempDir); File[] allFiles = tempDir.listFiles(); Response response = new Response(session.getId()); if (allFiles == null || allFiles.length != 1) { response.setStatus(ErrorCodes.UNHANDLED_ERROR); response.setValue(new WebDriverException( "Expected there to be only 1 file. There were: " + (allFiles == null ? 0 : allFiles.length))); } else { Path uploadsDir = Files.createDirectories(tempDir.toPath().getParent().resolve("remote_uploads")); Path dest = uploadsDir.resolve(allFiles[0].getName()); if (Files.exists(dest)){ Path prevFileDir = session.getFileSystem().createTempDir("prevupload", "file").toPath(); Files.move(dest, prevFileDir.resolve(allFiles[0].getName())); } dest = Files.move(allFiles[0].toPath(), dest, REPLACE_EXISTING); response.setStatus(ErrorCodes.SUCCESS); response.setValue(dest.toAbsolutePath().toString()); } session.getDownstreamDialect().getResponseCodec().encode(() -> resp, response); }
Source:
<code>public FileUpdateWatcher(String fileName, FileUpdateCallback fileUpdateCb) throws IOException { File file = new File(fileName); if (!file.exists() || file.isDirectory()) { throw new IllegalArgumentException("script file doesn't exist"); } this.fileName = fileName; Path path = Paths.get(file.getParent()); this.callback = fileUpdateCb; watcher = path.getFileSystem().newWatchService(); path.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY); <START> final Executor executor = Executors.newSingleThreadExecutor(); <END> executor.execute(new FileWatcherThread()); LOG.info(" started watcher thread"); }</code><technical_language>create executor, shut down. Do need executor here, dealing a single Runnable</technical_language>

Target:
public FileUpdateWatcher(String fileName, FileUpdateCallback fileUpdateCb) throws IOException { File file = new File(fileName); if (!file.exists() || file.isDirectory()) { throw new IllegalArgumentException(String.format("file %s doesn't exist", fileName)); } this.fileName = fileName; Path path = Paths.get(file.getParent()); this.callback = fileUpdateCb; watcher = path.getFileSystem().newWatchService(); path.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY); Thread thread = new Thread(new FileWatcherThread()); thread.setName(String.format("fileUpdateWatcher-%s", file.getName())); thread.start(); LOG.info("started watcher thread for file : {}", file.getName()); }
Source:
<code>public void test_of_Currency() { CurrencyAmount test = CurrencyAmount.of(Currency.USD, A1); assertEquals(test.getCurrency(), Currency.USD); <START> assertEquals(test.getAmount(), A1, 0.0001d); <END> }</code><technical_language>Do need a tolerance here</technical_language>

Target:
public void test_of_Currency() { CurrencyAmount test = CurrencyAmount.of(Currency.USD, AMT1); assertEquals(test.getCurrency(), Currency.USD); assertEquals(test.getAmount(), AMT1, 0); }
Source:
<code>public static void updateDatabase(Connection dbConnection, String sqlStmt, Object... params) throws UserStoreException { try ( PreparedStatement prepStmt = dbConnection.prepareStatement(sqlStmt)) { if (params != null && params.length > 0) { for (int i = 0; i < params.length; i++) { Object param = params[i]; if (param == null) { prepStmt.setString(i + 1, null); } else if (param instanceof String) { prepStmt.setString(i + 1, (String) param); } else if (param instanceof Integer) { prepStmt.setInt(i + 1, (Integer) param); } else if (param instanceof Short) { prepStmt.setShort(i + 1, (Short) param); } else if (param instanceof Date) { Date date = (Date) param; Timestamp time = new Timestamp(date.getTime()); prepStmt.setTimestamp(i + 1, time); } } } prepStmt.executeUpdate(); } catch (SQLException e) { String errorMessage = "Using sql : " + sqlStmt + " " + e.getMessage(); if (log.isDebugEnabled()) { log.debug(errorMessage, e); } <START> throw new UserStoreException(errorMessage, e); <END> } }</code><technical_language>try-with-resource pattern automatically handles ResultSet PreparedStatement objects, Connection, "dbConnection" in this scope, needs closed "DatabaseUtil.closeAllConnections(dbConnection);"</technical_language>

Target:
public static void updateDatabase(Connection dbConnection, String sqlStmt, Object... params) throws UserStoreException { try ( PreparedStatement prepStmt = dbConnection.prepareStatement(sqlStmt)) { if (params != null && params.length > 0) { for (int i = 0; i < params.length; i++) { Object param = params[i]; if (param == null) { prepStmt.setString(i + 1, null); } else if (param instanceof String) { prepStmt.setString(i + 1, (String) param); } else if (param instanceof Integer) { prepStmt.setInt(i + 1, (Integer) param); } else if (param instanceof Short) { prepStmt.setShort(i + 1, (Short) param); } else if (param instanceof Date) { Date date = (Date) param; Timestamp time = new Timestamp(date.getTime()); prepStmt.setTimestamp(i + 1, time); } } } prepStmt.executeUpdate(); } catch (SQLException e) { String errorMessage = "Using sql : " + sqlStmt + " " + e.getMessage(); if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { close(dbConnection); } }
Source:
<code>private int getMaximumThumbnailWidthForEditor() { if (mMaxThumbWidth == 0) { <START> mMaxThumbWidth = org.wordpress.android.editor.MediaUtils.getMaximumThumbnailSizeForEditor(this); <END> } return mMaxThumbWidth; }</code><technical_language>I wondering, rename this class MediaUtils a prefixed name likeEditorMediaUtils, redundant org.wordpress.android.editor path, able a clearer distinction MediaUtils in this file. have: - import org.wordpress.android.util.MediaUtils; - import org.wordpress.android.util.WPMediaUtils; - org.wordpress.android.editor.MediaUtils in this line</technical_language>

Target:
private int getMaximumThumbnailWidthForEditor() { if (mMaxThumbWidth == 0) { mMaxThumbWidth = EditorMediaUtils.getMaximumThumbnailSizeForEditor(this); } return mMaxThumbWidth; }
Source:
<code>protected void handleGet(final HttpServletRequest req, final HttpServletResponse resp, final Session session) throws ServletException, IOException { <START> if(isAdmin(session.getUser())) { <END> handleNotePageLoad(req, resp, session); } }</code><technical_language>do of adding some errorMsg in page if a user ADMIN permission access this page</technical_language>

Target:
protected void handleGet(final HttpServletRequest req, final HttpServletResponse resp, final Session session) throws ServletException, IOException { if(isAdmin(session.getUser())) { handleNotePageLoad(req, resp, session); } else { warningNonAdminUsers(resp, "The requested user doesn't have admin permission"); } }
Source:
<code>public void close() { reset(false); try { baos.close(); } catch (IOException e) { throw new ParquetRuntimeException("Error closing output stream.", e){ }; <START> } <END> }</code><technical_language>factor out</technical_language>

Target:
public void close() { reset(false); baos.close(); }
Source:
<code>public ACNVModeledSegment(final SimpleInterval interval, final PosteriorSummary segmentMeanPosteriorSummary, final PosteriorSummary minorAlleleFractionPosteriorSummary) { <START> super(interval, ModeledSegment.NO_CALL, 0, segmentMeanPosteriorSummary.mean()); <END> this.segmentMeanPosteriorSummary = segmentMeanPosteriorSummary; this.minorAlleleFractionPosteriorSummary = minorAlleleFractionPosteriorSummary; }</code><technical_language>note mean() -> center() #330 give posterior mode instead of posterior</technical_language>

Target:
public ACNVModeledSegment(final SimpleInterval interval, final PosteriorSummary segmentMeanPosteriorSummary, final PosteriorSummary minorAlleleFractionPosteriorSummary) { super(interval, ModeledSegment.NO_CALL, 0, segmentMeanPosteriorSummary.center()); this.segmentMeanPosteriorSummary = segmentMeanPosteriorSummary; this.minorAlleleFractionPosteriorSummary = minorAlleleFractionPosteriorSummary; }
Source:
<code>@Test public void fails_when_unused_stubbings() throws Throwable { <START> try { <END> run(new MockitoStatement() { public void evaluate(IMethods mock, IMethods mock2) throws Throwable { given(mock.simpleMethod(10)).willReturn("foo"); mock2.simpleMethod(15); } }); fail(); } catch (MockitoAssertionError e) { Assertions.assertThat(e.getMessage()).startsWith("Unused stubbings"); } }</code><technical_language>@szczepiq mind ExpectedException rule, this improve readability avoid try/fail/catch blocks distracts reader test case IMO</technical_language>

Target:
@Test public void fails_when_unused_stubbings() throws Throwable { rule.expectFailure(UnnecessaryStubbingException.class); given(mock.simpleMethod(10)).willReturn("foo"); mock2.simpleMethod(10); }
Source:
<code><START> public void errorResponseHasRegistryObjectList() throws Exception { <END> AdapterDocQueryOrchImpl impl = new AdapterDocQueryOrchImpl(); try { impl.respondingGatewayCrossGatewayQuery(null, null); Assert.fail(); } catch (ErrorEventException e) { AdhocQueryResponse response = (AdhocQueryResponse) e.getReturnOverride(); assertNotNull(response.getRegistryObjectList()); assertEquals(0, response.getRegistryObjectList().getIdentifiable().size()); } }</code><technical_language>Optional: need throws Exception catch runtime Exception</technical_language>

Target:
public void errorResponseHasRegistryObjectList() { AdapterDocQueryOrchImpl impl = new AdapterDocQueryOrchImpl(); try { impl.respondingGatewayCrossGatewayQuery(null, null); Assert.fail(); } catch (ErrorEventException e) { AdhocQueryResponse response = (AdhocQueryResponse) e.getReturnOverride(); assertNotNull(response.getRegistryObjectList()); assertEquals(0, response.getRegistryObjectList().getIdentifiable().size()); } }
Source:
<code>public Mono<Void> initialize() { BootstrapperImpl self = this; self.isInitialized = false; return Mono.just(self) .flatMap( value -> self.leaseStore.isInitialized()) .flatMap(initialized -> { self.isInitialized = initialized; if (initialized) { return Mono.empty(); } else { return self.leaseStore.acquireInitializationLock(self.lockTime) .flatMap(lockAcquired -> { self.isLockAcquired = lockAcquired; if (!self.isLockAcquired) { logger.info("Another instance is initializing the store"); try { <START> Thread.sleep(self.sleepTime.toMillis()); <END> } catch (InterruptedException ex) { logger.warn("Unexpected exception caught", ex); } return Mono.just(isLockAcquired); } else { return self.synchronizer.createMissingLeases() .then(self.leaseStore.markInitialized()); } }) .onErrorResume(throwable -> { logger.warn("Unexpected exception caught", throwable); return Mono.just(self.isLockAcquired); }) .flatMap(lockAcquired -> { if (self.isLockAcquired) { return self.leaseStore.releaseInitializationLock(); } return Mono.just(lockAcquired); }); } }) .repeat( () -> !self.isInitialized) .then(); }</code><technical_language>this is blocking call</technical_language>

Target:
public Mono<Void> initialize() { this.isInitialized = false; return Mono.just(this) .flatMap( value -> this.leaseStore.isInitialized()) .flatMap(initialized -> { this.isInitialized = initialized; if (initialized) { return Mono.empty(); } else { return this.leaseStore.acquireInitializationLock(this.lockTime) .flatMap(lockAcquired -> { this.isLockAcquired = lockAcquired; if (!this.isLockAcquired) { logger.info("Another instance is initializing the store"); return Mono.just(isLockAcquired).delayElement(this.sleepTime); } else { return this.synchronizer.createMissingLeases() .then(this.leaseStore.markInitialized()); } }) .onErrorResume(throwable -> { logger.warn("Unexpected exception caught", throwable); return Mono.just(this.isLockAcquired); }) .flatMap(lockAcquired -> { if (this.isLockAcquired) { return this.leaseStore.releaseInitializationLock(); } return Mono.just(lockAcquired); }); } }) .repeat( () -> !this.isInitialized) .then(); }
Source:
<code>public static void main(String[] args) { if (args.length < 2) { <START> System.err.println("Usage: FluoOracle <connectionPropsPath> <applicationName> args..."); <END> System.exit(-1); } String connectionPropsPath = args[0]; String applicationName = args[1]; Objects.requireNonNull(connectionPropsPath); Objects.requireNonNull(applicationName); File connectionPropsFile = new File(connectionPropsPath); Preconditions.checkArgument(connectionPropsFile.exists(), connectionPropsPath + " does not exist"); String[] userArgs = Arrays.copyOfRange(args, 2, args.length); CommandOpts commandOpts = CommandOpts.parse("fluo oracle <app>", userArgs); FluoConfiguration config = new FluoConfiguration(connectionPropsFile); config.setApplicationName(applicationName); commandOpts.overrideConfig(config); CommandUtil.verifyAppInitialized(config); try { org.apache.fluo.api.service.FluoOracle oracle = FluoFactory.newOracle(config); oracle.start(); while (true) { UtilWaitThread.sleep(10000); } } catch (Exception e) { log.error("Exception running FluoOracle: ", e); } }</code><technical_language>instead of args... this call call JCommander generator put -D arg here</technical_language>

Target:
public static void main(String[] args) { CommonOpts opts = CommonOpts.parse("fluo oracle", args); FluoConfiguration config = CommandUtil.resolveFluoConfig(); config.setApplicationName(opts.getApplicationName()); opts.overrideFluoConfig(config); CommandUtil.verifyAppInitialized(config); try { org.apache.fluo.api.service.FluoOracle oracle = FluoFactory.newOracle(config); oracle.start(); while (true) { UtilWaitThread.sleep(10000); } } catch (Exception e) { log.error("Exception running FluoOracle: ", e); } }
Source:
<code>private static UserAgent parseInternal(String userAgent, boolean lenient) { ImmutableUserAgent.Builder builder = ImmutableUserAgent.builder(); List<String> parts = COMMA_SPLITTER.splitToList(userAgent); checkArgument(!parts.isEmpty(), "Empty user agents are not allowed"); Map<String, String> primaryComments = Maps.newHashMap(); Optional<UserAgent.Agent> primaryAgent = tryParseSingleAgent(parts.get(0), primaryComments); if (primaryAgent.isPresent()) { builder.primary(primaryAgent.get()); } else { if (lenient) { builder.primary(UserAgent.Agent.of("unknown", UserAgent.Agent.DEFAULT_VERSION)); } else { throw new IllegalArgumentException("Agent string was malformed: " + parts.get(0)); } } if (primaryComments.containsKey("nodeId")) { builder.nodeId(primaryComments.get("nodeId")); } for (String part : parts.subList(1, parts.size())) { Optional<UserAgent.Agent> informationlAgent = tryParseSingleAgent(part, Maps.newHashMap()); if (informationlAgent.isPresent()) { builder.addInformational(informationlAgent.get()); } else { if (lenient) { <START> log.warn("Cannot parse malformed user agent string", UnsafeArg.of("agent", part)); <END> } else { throw new IllegalArgumentException("Agent string was malformed: " + part); } } } return builder.build(); }</code><technical_language>is this case primary agent case? this unknown/0.0.0</technical_language>

Target:
private static UserAgent parseInternal(String userAgent, boolean lenient) { ImmutableUserAgent.Builder builder = ImmutableUserAgent.builder(); List<String> parts = COMMA_SPLITTER.splitToList(userAgent); if (parts.isEmpty()) { if (lenient) { log.warn("Empty user agent, falling back to default/unknown agent"); return builder.primary(UserAgent.Agent.of("unknown", UserAgent.Agent.DEFAULT_VERSION)).build(); } else { throw new IllegalArgumentException("Empty user agents are not allowed: " + userAgent); } } Map<String, String> primaryComments = Maps.newHashMap(); Optional<UserAgent.Agent> primaryAgent = tryParseSingleAgent(parts.get(0), primaryComments); if (primaryAgent.isPresent()) { builder.primary(primaryAgent.get()); } else { if (lenient) { log.warn("Malformed primary user agent", UnsafeArg.of("agent", parts.get(0))); builder.primary(UserAgent.Agent.of("unknown", UserAgent.Agent.DEFAULT_VERSION)); } else { throw new IllegalArgumentException("Agent string was malformed: " + parts.get(0)); } } if (primaryComments.containsKey("nodeId")) { builder.nodeId(primaryComments.get("nodeId")); } for (String part : parts.subList(1, parts.size())) { Optional<UserAgent.Agent> informationlAgent = tryParseSingleAgent(part, Maps.newHashMap()); if (informationlAgent.isPresent()) { builder.addInformational(informationlAgent.get()); } else { if (lenient) { log.warn("Cannot parse malformed user agent string", UnsafeArg.of("agent", part)); } else { throw new IllegalArgumentException("Agent string was malformed: " + part); } } } return builder.build(); }
Source:
<code>public static void validateNDKVersion(int desiredVersion, String versionStr) throws MojoExecutionException { int version = 0; if (versionStr != null) { versionStr = versionStr.trim(); Pattern pattern = Pattern.compile("[r]([0-9]{1,3})([a-z]{0,1}).*"); Matcher m = pattern.matcher(versionStr); if (m.matches()) { final String group = m.group(1); version = Integer.parseInt(group); } } if (version < desiredVersion) { <START> throw new MojoExecutionException("You are running an old NDK (version " + versionStr + "), please update to at least r7 or later"); <END> } }</code><technical_language>error message desiredVersion instead of hardcoded r7 ... r7 some sort of static final</technical_language>

Target:
public static void validateNDKVersion(int desiredVersion, String versionStr) throws MojoExecutionException { int version = 0; if (versionStr != null) { versionStr = versionStr.trim(); Pattern pattern = Pattern.compile("[r]([0-9]{1,3})([a-z]{0,1}).*"); Matcher m = pattern.matcher(versionStr); if (m.matches()) { final String group = m.group(1); version = Integer.parseInt(group); } } if (version < desiredVersion) { throw new MojoExecutionException("You are running an old NDK (version " + versionStr + "), please update to at least r'" + desiredVersion + "' or later"); } }
Source:
<code>public void onInteract(LivingEnchantmentLevelEvent event) { if (event.getEntityLiving().isSneaking()) { int oldLevel = event.getLevel(); int newLevel = (oldLevel + 1) * 10; event.setLevel(newLevel); <START> System.out.println("Set fortune level from " + oldLevel + " to " + newLevel); <END> } }</code><technical_language>print mentions fortune, this called for enchantments</technical_language>

Target:
public static void onInteract(LivingEnchantmentLevelEvent event) { if (!ENABLED) { return; } if (event.getEntityLiving().isSneaking()) { int oldLevel = event.getLevel(); int newLevel = oldLevel * 10; event.setLevel(newLevel); logger.info("Set enchantment level from " + oldLevel + " to " + newLevel + " for " + event.getEnchantment().getName()); } }
Source:
<code>public String getDisplayString(OrderGroup group) { if (group.isVoided()) <START> return "[No Group]"; <END> Patient patient = group.getPatient(); return patient.getPatientIdentifier().getIdentifier() + " - " + patient.getPersonName().getFullName() + " - " + group.getOrderSet().getName(); }</code><technical_language>do return group for a voided one? Is this a pattern else in code base</technical_language>

Target:
public String getDisplayString(OrderGroup group) { if (group.getOrders() == null) return "[No Orders]"; Patient patient = group.getPatient(); return patient.getPatientIdentifier().getIdentifier() + " - " + patient.getPersonName().getFullName() + " - " + group.getOrderSet().getName(); }
Source:
<code>public Map<Long, Object> retrieveAllWindows() throws IOException { Map<Long, Object> artifactPerWindow = new HashMap<>(); FileSystemWAL.FileSystemWALReader reader = getWal().getReader(); reader.seek(getWal().getWalStartPointer()); Slice windowSlice = readNext(reader); while (reader.getCurrentPointer().compareTo(getWal().getWalEndPointerAfterRecovery()) < 0 && windowSlice != null) { long window = Longs.fromByteArray(windowSlice.toByteArray()); Object data = fromSlice(readNext(reader)); windowSlice = readNext(reader); <START> if (windowSlice == DELETED) { <END> windowSlice = readNext(reader); } else { artifactPerWindow.put(window, data); } } reader.seek(getWal().getWalStartPointer()); return artifactPerWindow; }</code><technical_language>this 2 objects</technical_language>

Target:
public Map<Long, Object> retrieveAllWindows() throws IOException { Map<Long, Object> artifactPerWindow = new HashMap<>(); FileSystemWAL.FileSystemWALReader reader = getWal().getReader(); reader.seek(getWal().getWalStartPointer()); Slice windowSlice = readNext(reader); while (reader.getCurrentPointer().compareTo(getWal().getWalEndPointerAfterRecovery()) < 0 && windowSlice != null) { long window = Longs.fromByteArray(windowSlice.toByteArray()); Object data = fromSlice(readNext(reader)); artifactPerWindow.put(window, data); windowSlice = readNext(reader); } reader.seek(getWal().getWalStartPointer()); return artifactPerWindow; }
Source:
<code>protected boolean runKerberosLogin() { try { UserGroupInformation.AuthenticationMethod authType = JDBCSecurityImpl.getAuthtype(property); <START> if (authType.equals(KERBEROS)) { <END> if (UserGroupInformation.isLoginKeytabBased()) { UserGroupInformation.getLoginUser().reloginFromKeytab(); } else if (UserGroupInformation.isLoginTicketBased()) { UserGroupInformation.getLoginUser().reloginFromTicketCache(); } } } catch (Exception e) { logger.error("Unable to run kinit for zeppelin", e); return false; } return true; }</code><technical_language>authType is needed check runKerberosLogin called kerberos is enabled</technical_language>

Target:
protected boolean runKerberosLogin() { try { if (UserGroupInformation.isLoginKeytabBased()) { UserGroupInformation.getLoginUser().reloginFromKeytab(); return true; } else if (UserGroupInformation.isLoginTicketBased()) { UserGroupInformation.getLoginUser().reloginFromTicketCache(); return true; } } catch (Exception e) { logger.error("Unable to run kinit for zeppelin", e); } return false; }
Source:
<code>private void validateSchema(final EventTypeBase eventType) throws InvalidEventTypeException { try { final String eventTypeSchema = eventType.getSchema().getSchema(); checkJsonIsValid(eventTypeSchema); <START> final JSONObject schemaAsJson = new JSONObject(eventTypeSchema); <END> final Schema schema = SchemaLoader.load(schemaAsJson); if (eventType.getCategory() == EventCategory.BUSINESS && schema.definesProperty("#/metadata")) { throw new InvalidEventTypeException("\"metadata\" property is reserved"); } if (featureToggleService.isFeatureEnabled(CHECK_PARTITIONS_KEYS)) { validatePartitionKeys(schema, eventType); } if (eventType.getCompatibilityMode() == CompatibilityMode.COMPATIBLE) { validateJsonSchemaConstraints(schemaAsJson); } } catch (final JSONException e) { throw new InvalidEventTypeException("schema must be a valid json"); } catch (final SchemaException e) { throw new InvalidEventTypeException("schema must be a valid json-schema"); } }</code><technical_language><LINK_0> create a JSONObject a JSONTokener, call next more tokener determine if reached end of input</technical_language>

Target:
private void validateSchema(final EventTypeBase eventType) throws InvalidEventTypeException { try { final String eventTypeSchema = eventType.getSchema().getSchema(); JsonUtils.checkEventTypeSchemaValid(eventTypeSchema); final JSONObject schemaAsJson = new JSONObject(eventTypeSchema); final Schema schema = SchemaLoader.load(schemaAsJson); if (eventType.getCategory() == EventCategory.BUSINESS && schema.definesProperty("#/metadata")) { throw new InvalidEventTypeException("\"metadata\" property is reserved"); } if (featureToggleService.isFeatureEnabled(CHECK_PARTITIONS_KEYS)) { validatePartitionKeys(schema, eventType); } if (eventType.getCompatibilityMode() == CompatibilityMode.COMPATIBLE) { validateJsonSchemaConstraints(schemaAsJson); } } catch (final JSONException e) { throw new InvalidEventTypeException("schema must be a valid json"); } catch (final SchemaException e) { throw new InvalidEventTypeException("schema must be a valid json-schema"); } }