auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void applyEntityCollision(Entity entity) { if (entity.riding != this && entity.linkedEntity != this) { double dx = entity.x - this.x; double dy = entity.z - this.z; double dz = NukkitMath.getDirection(dx, dy); if (dz >= 0.009999999776482582D) { dz = MathHelper.sqrt((float) dz); dx /= dz; dy /= dz; double d3 = 1.0D / dz; if (d3 > 1.0D) { d3 = 1.0D; } dx *= d3; dy *= d3; dx *= 0.05000000074505806D; dy *= 0.05000000074505806D; dx *= 1.0F + entityCollisionReduction; dz *= 1.0F + entityCollisionReduction; if (this.riding == null) { motionX += -dx; <START> motionZ += -dy; <END> } } } }</code><technical_language>Surely more sense do motionX -= dx;</technical_language>

Target:
public void applyEntityCollision(Entity entity) { if (entity.riding != this && entity.linkedEntity != this) { double dx = entity.x - this.x; double dy = entity.z - this.z; double dz = NukkitMath.getDirection(dx, dy); if (dz >= 0.009999999776482582D) { dz = MathHelper.sqrt((float) dz); dx /= dz; dy /= dz; double d3 = 1.0D / dz; if (d3 > 1.0D) { d3 = 1.0D; } dx *= d3; dy *= d3; dx *= 0.05000000074505806D; dy *= 0.05000000074505806D; dx *= 1.0F + entityCollisionReduction; dz *= 1.0F + entityCollisionReduction; if (this.riding == null) { motionX -= dx; motionZ -= dy; } } } }
Source:
<code>private MainThread[] startQuorum() throws IOException { final int[] clientPorts = new int[SERVER_COUNT]; StringBuilder sb = new StringBuilder(); String server; for (int i = 0; i < SERVER_COUNT; i++) { clientPorts[i] = PortAssignment.unique(); <START> server = "server." <END> + i + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ":participant;127.0.0.1:" + clientPorts[i]; sb.append(server + "\n"); } String currentQuorumCfgSection = sb.toString(); MainThread[] mt = new MainThread[SERVER_COUNT]; for (int i = 0; i < SERVER_COUNT; i++) { mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, false) { @Override public TestQPMain getTestQPMain() { return new MockTestQPMain(); } }; mt[i].start(); } for (int i = 0; i < SERVER_COUNT; i++) { Assert.assertTrue("waiting for server " + i + " being up", ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT)); } return mt; }</code><technical_language>is worth reverting</technical_language>

Target:
private MainThread[] startQuorum() throws IOException { final int[] clientPorts = new int[SERVER_COUNT]; StringBuilder sb = new StringBuilder(); String server; for (int i = 0; i < SERVER_COUNT; i++) { clientPorts[i] = PortAssignment.unique(); server = "server." + i + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ":participant;127.0.0.1:" + clientPorts[i]; sb.append(server + "\n"); } String currentQuorumCfgSection = sb.toString(); MainThread[] mt = new MainThread[SERVER_COUNT]; for (int i = 0; i < SERVER_COUNT; i++) { mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, false) { @Override public TestQPMain getTestQPMain() { return new MockTestQPMain(); } }; mt[i].start(); } for (int i = 0; i < SERVER_COUNT; i++) { assertTrue( "waiting for server " + i + " being up", ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT)); } return mt; }
Source:
<code>public void popMessage(String processorName) throws AxisFault { SynapseConfiguration configuration = getSynapseConfiguration(); MessageConsumer messageConsumer = getMessageConsumer(configuration,processorName); try { popMessageFromQueue(messageConsumer); } catch (SynapseException e) { <START> handleException(log, "Failed to get message : ", e); <END> } messageConsumer.cleanup(); }</code><technical_language>error log is in methods. hard debug issues. rename accrodingly</technical_language>

Target:
public void popMessage(String processorName) throws AxisFault { SynapseConfiguration configuration = getSynapseConfiguration(); MessageConsumer messageConsumer = getMessageConsumer(configuration,processorName); try { popMessageFromQueue(messageConsumer); } catch (SynapseException e) { handleException(log, "Failed to pop message from the queue: ", e); } finally { messageConsumer.cleanup(); } }
Source:
<code>private static void reloadPrefs(Preferences prefs) { String loadConfigMethodString = "loadConfig"; String sessionConfigFieldString = "sessionConfig"; String userConfigFieldString = "userConfig"; try { Method loadConfigMethod = Preferences.class.getDeclaredMethod(loadConfigMethodString, String.class, String.class, Class.class); Field sessionConfigField = Preferences.class.getDeclaredField(sessionConfigFieldString); Field userConfigField = Preferences.class.getDeclaredField(userConfigFieldString); loadConfigMethod.setAccessible(true); sessionConfigField.setAccessible(true); userConfigField.setAccessible(true); sessionConfigField.set(prefs, loadConfigMethod.invoke(prefs, TestController.TEST_DIRECTORY, TestController.TEST_SESSION_CONFIG_FILENAME, SessionConfig.class)); userConfigField.set(prefs, loadConfigMethod.invoke(prefs, TestController.TEST_DIRECTORY, TestController.TEST_USER_CONFIG_FILENAME, UserConfig.class)); } catch (NoSuchMethodException e) { fail(String.format("Problem invoking private method; does %s still exist? %s", loadConfigMethodString, e.toString())); } catch (NoSuchFieldException e) { fail(String.format("Problem accessing private field; do %s and %s still exist? %s", sessionConfigFieldString, userConfigFieldString, e.toString())); <START> } catch (IllegalAccessException | InvocationTargetException e){ <END> fail(String.format("Problem with invoking or accessing. %s", e.toString())); } }</code><technical_language>for catches. Put method signature</technical_language>

Target:
private static void reloadPrefs(Preferences prefs) throws NoSuchMethodException, NoSuchFieldException, InvocationTargetException, IllegalAccessException { String loadConfigMethodString = "loadConfig"; String sessionConfigFieldString = "sessionConfig"; String userConfigFieldString = "userConfig"; Method loadConfigMethod = Preferences.class.getDeclaredMethod(loadConfigMethodString, String.class, String.class, Class.class); Field sessionConfigField = Preferences.class.getDeclaredField(sessionConfigFieldString); Field userConfigField = Preferences.class.getDeclaredField(userConfigFieldString); loadConfigMethod.setAccessible(true); sessionConfigField.setAccessible(true); userConfigField.setAccessible(true); sessionConfigField.set(prefs, loadConfigMethod.invoke(prefs, TestController.TEST_DIRECTORY, TestController.TEST_SESSION_CONFIG_FILENAME, SessionConfig.class)); userConfigField.set(prefs, loadConfigMethod.invoke(prefs, TestController.TEST_DIRECTORY, TestController.TEST_SESSION_CONFIG_FILENAME, UserConfig.class)); }
Source:
<code>private static void removeTestFiles() { File workingDir = new File(WORKING_DIRECTORY_LOCATION); if (workingDir.exists() == false) { <START> workingDir.mkdirs(); <END> } File[] testFiles = { new File(workingDir, "firefly.keystore"), new File(workingDir, "test.keystore"), new File(workingDir, "test-single-cert-reply.cert"), new File(workingDir, "test-cert-chain-reply.cert"), new File(workingDir, "test-exported.cert"), new File(workingDir, "test-trusted.cert"), new File(workingDir, "test-untrusted.cert"), new File(workingDir, "test-untrusted-cert-chain-reply.cert") }; for (File file : testFiles) { if (file.exists()) { file.delete(); } } }</code><technical_language>need create directory if exist. file.exists() check ensures file deleted if exists</technical_language>

Target:
private static void removeTestFiles() { File[] testFiles = { FIREFLY_FILE, TEST_FILE, TEST_SINGLE_CERT_REPLY_FILE, TEST_CERT_CHAIN_REPLY_FILE, TEST_EXPORTED_FILE, TEST_TRUSTED_FILE, TEST_UNTRUSTED_FILE, TEST_UNTRUSTED_CERT_CHAIN_REPLY_FILE }; for (File file : testFiles) { if (file.exists()) { file.delete(); } } }
Source:
<code>protected Injector setupInjector() { return Initialization.makeInjectorWithModules( GuiceInjectors.makeStartupInjector(), ImmutableList.<Module>of( new Module() { @Override public void configure(Binder binder) { JsonConfigProvider.bindInstance( binder, Key.get(DruidNode.class, Self.class), new DruidNode("test", "localhost", null, null, new ServerConfig()) ); binder.bind(JettyServerInitializer.class).to(JettyServerInit.class).in(LazySingleton.class); Multibinder<ServletFilterHolder> multibinder = Multibinder.newSetBinder( binder, ServletFilterHolder.class ); multibinder.addBinding().toInstance( new ServletFilterHolder() { @Override public String getPath() { return "/*"; } @Override public Map<String, String> getInitParameters() { return null; } @Override public Class<? extends Filter> getFilterClass() { return DummyAuthFilter.class; } @Override public Filter getFilter() { return null; } @Override public EnumSet<DispatcherType> getDispatcherType() { return null; } }); Jerseys.addResource(binder, SlowResource.class); Jerseys.addResource(binder, ExceptionResource.class); Jerseys.addResource(binder, DefaultResource.class); <START> binder.bind(AuthorizationManager.class).toInstance(new AuthorizationManager() <END> { @Override public Access authorize( String identity, Resource resource, Action action ) { return new Access(true); } }); LifecycleModule.register(binder, Server.class); } } ) ); }</code><technical_language>replaced NoopAuthorizationManager</technical_language>

Target:
protected Injector setupInjector() { return Initialization.makeInjectorWithModules( GuiceInjectors.makeStartupInjector(), ImmutableList.<Module>of( new Module() { @Override public void configure(Binder binder) { JsonConfigProvider.bindInstance( binder, Key.get(DruidNode.class, Self.class), new DruidNode("test", "localhost", null, null, new ServerConfig()) ); binder.bind(JettyServerInitializer.class).to(JettyServerInit.class).in(LazySingleton.class); Multibinder<ServletFilterHolder> multibinder = Multibinder.newSetBinder( binder, ServletFilterHolder.class ); multibinder.addBinding().toInstance( new ServletFilterHolder() { @Override public String getPath() { return "/*"; } @Override public Map<String, String> getInitParameters() { return null; } @Override public Class<? extends Filter> getFilterClass() { return DummyAuthFilter.class; } @Override public Filter getFilter() { return null; } @Override public EnumSet<DispatcherType> getDispatcherType() { return null; } }); Jerseys.addResource(binder, SlowResource.class); Jerseys.addResource(binder, ExceptionResource.class); Jerseys.addResource(binder, DefaultResource.class); binder.bind(AuthorizerMapper.class).toInstance(AuthTestUtils.TEST_AUTHORIZER_MAPPER); LifecycleModule.register(binder, Server.class); } } ) ); }
Source:
<code>private void buildIfRequested(final IProject project, IProgressMonitor monitor) throws CoreException { if (!closeProjectsAfterImport && rebuildProjectsAfterImport) { project.build(IncrementalProjectBuilder.CLEAN_BUILD, monitor); <START> project.build(IncrementalProjectBuilder.FULL_BUILD, monitor); <END> } }</code><technical_language>This is needed is autobuild is on</technical_language>

Target:
private void buildIfRequested(final IProject project, IProgressMonitor monitor) throws CoreException { if (rebuildProjectsAfterImport) { project.build(IncrementalProjectBuilder.CLEAN_BUILD, monitor); IWorkspace workspace = project.getWorkspace(); boolean isAutoBuilding = workspace.isAutoBuilding(); if (!isAutoBuilding) { project.build(IncrementalProjectBuilder.FULL_BUILD, monitor); } } }
Source:
<code>public ElasticsearchRecordCursor(List<ElasticsearchColumnHandle> columnHandles, ElasticsearchConnectorConfig config, ElasticsearchSplit split) <START> { <END> requireNonNull(columnHandles, "columnHandle is null"); requireNonNull(config, "config is null"); this.columnHandles = columnHandles; this.maxHits = config.getMaxHits(); this.timeout = config.getRequestTimeout(); for (int i = 0; i < columnHandles.size(); i++) { jsonPathToIndex.put(columnHandles.get(i).getColumnJsonPath(), i); } this.builder = new ElasticsearchQueryBuilder(columnHandles, config, split); this.searchHits = sendElasticsearchQuery(builder).iterator(); }</code><technical_language>fields array</technical_language>

Target:
public ElasticsearchRecordCursor(List<ElasticsearchColumnHandle> columnHandles, ElasticsearchConnectorConfig config, ElasticsearchSplit split) { requireNonNull(columnHandles, "columnHandle is null"); requireNonNull(config, "config is null"); this.columnHandles = columnHandles; this.maxHits = config.getMaxHits(); this.requestTimeout = config.getRequestTimeout(); this.maxAttempts = config.getMaxRequestRetries(); this.maxRetryTime = config.getMaxRetryTime(); for (int i = 0; i < columnHandles.size(); i++) { jsonPathToIndex.put(columnHandles.get(i).getColumnJsonPath(), i); } this.builder = new ElasticsearchQueryBuilder(columnHandles, config, split); this.searchHits = sendElasticsearchQuery(builder).iterator(); }
Source:
<code>public void deleteCommentsByInstructorEmail(String courseId, String email) { Assumption.assertNotNull(Const.StatusCodes.DBLEVEL_NULL_INPUT, courseId); Assumption.assertNotNull(Const.StatusCodes.DBLEVEL_NULL_INPUT, email); getCommentsForGiverQuery(courseId, email).deletePersistentAll(); <START> getPm().flush(); <END> }</code><technical_language>Is a need flush pm</technical_language>

Target:
public void deleteCommentsByInstructorEmail(String courseId, String email) { Assumption.assertNotNull(Const.StatusCodes.DBLEVEL_NULL_INPUT, courseId); Assumption.assertNotNull(Const.StatusCodes.DBLEVEL_NULL_INPUT, email); getCommentsForGiverQuery(courseId, email) .deletePersistentAll(); }
Source:
<code>protected ModelAndView handleNotFound(HttpServletRequest request, HttpServletResponse response) { response.setStatus(HttpStatus.NOT_FOUND.value()); Site site = siteResolver.resolveSite(request); if (site == null) { <START> if (request.getServletPath().equals("/")) { <END> ModelAndView mav = new ModelAndView(" mav.addObject("siteKeys", siteSet.getSiteKeys()); try { mav.addObject("imageCode", getResourceAsBase64("/WEB-INF/themes/root/app/wombat.jpg")); } catch (IOException e) return mav; } else { return new ModelAndView(" } } else { return new ModelAndView(site.getKey() + "/ftl/notFound"); } }</code><technical_language>Please extract if body method, clear "app root page" logic lives. Also, long messing this anyway, I love get build info root page</technical_language>

Target:
protected ModelAndView handleNotFound(HttpServletRequest request, HttpServletResponse response) { Site site = siteResolver.resolveSite(request); if (site == null && request.getServletPath().equals("/")) { return serveAppRoot(); } response.setStatus(HttpStatus.NOT_FOUND.value()); String viewName = (site == null) ? " return new ModelAndView(viewName); }
Source:
<code>private BuildAssignment(BuildCause buildCause, File buildWorkingDirectory, List<Builder> builder, JobPlan plan) { this.buildWorkingDirectory = buildWorkingDirectory; this.builders = builder; this.plan = plan; for (MaterialRevision materialRevision : buildCause.getMaterialRevisions()) { ArrayList<Modification> modifications = new ArrayList<>(); for (Modification modification : materialRevision.getModifications()) { Modification modificationForAgent = new Modification(modification); modificationForAgent.unsetModifiedFiles(); <START> modifications.add(modificationForAgent); <END> } materialRevisions.addRevision(new MaterialRevision(materialRevision.getMaterial(), materialRevision.isChanged(), modifications)); } approver = buildCause.getApprover(); }</code><technical_language>Move this a copy constructor a flag constructs Modification object copying files get rid of unsetModifiedFiles method</technical_language>

Target:
private BuildAssignment(BuildCause buildCause, File buildWorkingDirectory, List<Builder> builder, JobPlan plan) { this.buildWorkingDirectory = buildWorkingDirectory; this.builders = builder; this.plan = plan; for (MaterialRevision materialRevision : buildCause.getMaterialRevisions()) { ArrayList<Modification> modifications = new ArrayList<>(); for (Modification modification : materialRevision.getModifications()) { modifications.add(new Modification(modification, false)); } materialRevisions.addRevision(new MaterialRevision(materialRevision.getMaterial(), materialRevision.isChanged(), modifications)); } approver = buildCause.getApprover(); }
Source:
<code>public int numberOfInserts() { final Integer cachedValue = numberOfInsertsCache; if (cachedValue != null) { return cachedValue; } int numberOfInserts = 0; for (T object : results.keySet()) { <START> if (results.get(object) != null && results.get(object).wasInserted()) { <END> numberOfInserts++; } } numberOfInsertsCache = numberOfInserts; return numberOfInserts; }</code><technical_language>result null, need this != null</technical_language>

Target:
public int numberOfInserts() { final Integer cachedValue = numberOfInsertsCache; if (cachedValue != null) { return cachedValue; } int numberOfInserts = 0; for (T object : results.keySet()) { assert results.get(object) != null; if (results.get(object).wasInserted()) { numberOfInserts++; } } numberOfInsertsCache = numberOfInserts; return numberOfInserts; }
Source:
<code>public JSONRPC2Response process(Object params) { JSONRPC2Response resp = null; try { List<Object> hosts = new LinkedList<Object>(); OVXMap map = OVXMap.getInstance(); Collection<OVXNetwork> vnets = map.listVirtualNetworks().values(); ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addSerializer(Host.class, new PhysicalHostSerializer()); <START> mapper.registerModule(module); <END> for (OVXNetwork vnet : vnets) { hosts.addAll(mapper.convertValue(vnet.getHosts(), List.class)); } resp = new JSONRPC2Response(hosts, 0); } catch (ClassCastException e) { resp = new JSONRPC2Response( new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(), this.cmdName() + ": Unable to fetch host list : " + e.getMessage()), 0); } return resp; }</code><technical_language>module, mapper adding of serializer in constructor of API call? Alternatively, Hosts implement serializable simple call serialize object itself? sense</technical_language>

Target:
public JSONRPC2Response process(Object params) { JSONRPC2Response resp = null; try { List<Object> result; result = mapper.convertValue(hs.getPhysicalHosts(), List.class); resp = new JSONRPC2Response(result, 0); } catch (ClassCastException e) { resp = new JSONRPC2Response( new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(), this.cmdName() + ": Unable to fetch host list : " + e.getMessage()), 0); } return resp; }
Source:
<code>protected EPersonRest createAndReturn(Context context) throws AuthorizeException { HttpServletRequest req = getRequestService().getCurrentRequest().getHttpServletRequest(); ObjectMapper mapper = new ObjectMapper(); EPersonRest epersonRest = null; try { epersonRest = mapper.readValue(req.getInputStream(), EPersonRest.class); } catch (IOException e1) { throw new UnprocessableEntityException("error parsing the body... maybe this is not the right error code"); } String token = req.getParameter("token"); if (StringUtils.isNotBlank(token)) { try { return createAndReturn(context, epersonRest, token); } catch (SQLException e) { <START> log.error(e.getMessage(), e); <END> throw new RuntimeException("Something with wrong in the creation of an EPerson with token: " + token); } } EPerson eperson = createEPersonFromRestObject(context, epersonRest); return converter.toRest(eperson, utils.obtainProjection()); }</code><technical_language>This log.error match RuntimeException. So, this be: log.error("Something wrong in creation of EPerson token: " + token, e); NOTE: RuntimeException "with wrong" "went wrong"</technical_language>

Target:
protected EPersonRest createAndReturn(Context context) throws AuthorizeException { HttpServletRequest req = getRequestService().getCurrentRequest().getHttpServletRequest(); ObjectMapper mapper = new ObjectMapper(); EPersonRest epersonRest = null; try { epersonRest = mapper.readValue(req.getInputStream(), EPersonRest.class); } catch (IOException e1) { throw new UnprocessableEntityException("error parsing the body... maybe this is not the right error code"); } String token = req.getParameter("token"); if (StringUtils.isNotBlank(token)) { try { return createAndReturn(context, epersonRest, token); } catch (SQLException e) { log.error("Something went wrong in the creation of an EPerson with token: " + token, e); throw new RuntimeException("Something went wrong in the creation of an EPerson with token: " + token); } } EPerson eperson = createEPersonFromRestObject(context, epersonRest); return converter.toRest(eperson, utils.obtainProjection()); }
Source:
<code>public void readFields(DataInput arg0) throws IOException { int len = arg0.readInt(); byte[] bytes = new byte[len]; arg0.readFully(bytes); try { ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes)); @SuppressWarnings("unchecked") Map<String, Object> properties = (Map<String, Object>)ois.readObject(); Field[] fields = this.getClass().getFields(); AccessibleObject.setAccessible(fields, true); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; String fieldName = field.getName(); if (properties.containsKey(fieldName)) { field.set(this, properties.get(fieldName)); } } ois.close(); } catch (Exception e) { final Path path = Files.createTempFile("dt-", ".ser"); <START> logger.error("Failed to de-serialize {}. Writing raw data to {}.", this.getClass().getName(), path, e); <END> Files.write(path, bytes); throw new IOException(e); } }</code><technical_language>This security concerns. Consider additional flag logging data</technical_language>

Target:
public void readFields(DataInput arg0) throws IOException { int len = arg0.readInt(); byte[] bytes = new byte[len]; arg0.readFully(bytes); try { ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes)); @SuppressWarnings("unchecked") Map<String, Object> properties = (Map<String, Object>)ois.readObject(); Field[] fields = this.getClass().getFields(); AccessibleObject.setAccessible(fields, true); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; String fieldName = field.getName(); if (properties.containsKey(fieldName)) { field.set(this, properties.get(fieldName)); } } ois.close(); } catch (Exception e) { final Path path = Files.createTempFile("apex-rpc-raw-dump-", ".ser"); logger.error("Failed to de-serialize {}. Writing raw data to {}.", this.getClass().getName(), path, e); Files.write(path, bytes); throw new IOException(e); } }
Source:
<code>private void waitPlanExecuting() { <START> while (orchestrator.isPlanExecuting()) { <END> try { Thread.sleep(10); } catch (final InterruptedException e) { throw new RuntimeException("Interrupted while waiting the completion of plan execution"); } } }</code><technical_language>This a bit dangerous. setting a limit, e.g. number of wait attempts</technical_language>

Target:
private void waitPlanExecuting() { int numLoop = 0; while (orchestrator.isPlanExecuting() && numLoop < MAX_WAIT_LOOP) { ++numLoop; try { Thread.sleep(WAIT_TIME); } catch (final InterruptedException e) { throw new RuntimeException("Interrupted while waiting the completion of plan execution"); } } }
Source:
<code>public AbstractValidatedWidgetWithLabel(W contentWidget) { this(contentWidget, new VisibilityRenderer.SimpleVisibilityRenderer()); <START> addStateUpdateHandler(); <END> }</code><technical_language>I missed this in review - addStateUpdateHandler() is called due this() (the other constructor above) calling addStateUpdateHandler() is needed, I guess</technical_language>

Target:
public AbstractValidatedWidgetWithLabel(W contentWidget) { this(contentWidget, new VisibilityRenderer.SimpleVisibilityRenderer()); }
Source:
<code><START> public final void setExecutor(ExecutorService executor) { <END> this.executor = executor; }</code><technical_language>here, methods</technical_language>

Target:
public void setExecutor(ExecutorService executor) { this.executor = executor; }
Source:
<code>public void testClusterSnapshotWithExplicitPath() throws Exception { File exSnpDir = U.resolveWorkDirectory(U.defaultWorkDirectory(), "ex_snapshots", true); try { IgniteEx ignite = null; for (int i = 0; i < 2; i++) { IgniteConfiguration cfg = optimize(getConfiguration(getTestIgniteInstanceName(i))); cfg.setSnapshotPath(exSnpDir.getAbsolutePath()); ignite = startGrid(cfg); } ignite.cluster().baselineAutoAdjustEnabled(false); ignite.cluster().state(ACTIVE); for (int i = 0; i < CACHE_KEYS_RANGE; i++) ignite.cache(DEFAULT_CACHE_NAME).put(i, i); <START> forceCheckpoint(); <END> ignite.snapshot().createSnapshot(SNAPSHOT_NAME) .get(); stopAllGrids(); IgniteEx snp = startGridsFromSnapshot(2, cfg -> exSnpDir.getAbsolutePath(), SNAPSHOT_NAME, true); assertSnapshotCacheKeys(snp.cache(dfltCacheCfg.getName())); } finally { stopAllGrids(); U.delete(exSnpDir); } }</code><technical_language>do need explicit checkpoint here</technical_language>

Target:
public void testClusterSnapshotWithExplicitPath() throws Exception { File exSnpDir = U.resolveWorkDirectory(U.defaultWorkDirectory(), "ex_snapshots", true); try { IgniteEx ignite = null; for (int i = 0; i < 2; i++) { IgniteConfiguration cfg = optimize(getConfiguration(getTestIgniteInstanceName(i))); cfg.setSnapshotPath(exSnpDir.getAbsolutePath()); ignite = startGrid(cfg); } ignite.cluster().baselineAutoAdjustEnabled(false); ignite.cluster().state(ACTIVE); for (int i = 0; i < CACHE_KEYS_RANGE; i++) ignite.cache(DEFAULT_CACHE_NAME).put(i, i); ignite.snapshot().createSnapshot(SNAPSHOT_NAME) .get(); stopAllGrids(); IgniteEx snp = startGridsFromSnapshot(2, cfg -> exSnpDir.getAbsolutePath(), SNAPSHOT_NAME, true); assertSnapshotCacheKeys(snp.cache(dfltCacheCfg.getName())); } finally { stopAllGrids(); U.delete(exSnpDir); } }
Source:
<code><START> public EventTypeValidator getValidator(final String name) throws InternalNakadiException, NoSuchEventTypeException { <END> return getCached(name).map(CachedValue::getEventTypeValidator).orElse(null); }</code><technical_language>If return null - method declared @Nullable, properly handled in places is called. other possibility orElseThrow(...) instead</technical_language>

Target:
public EventTypeValidator getValidator(final String name) throws InternalNakadiException, NoSuchEventTypeException { return getCached(name).map(CachedValue::getEventTypeValidator) .orElseThrow(() -> new NoSuchEventTypeException("Event type " + name + " does not exists")); }
Source:
<code>public void testReconfigureServer() { api().reconfigureServer(serverId, 4, CpuSpeed.HIGHPERFORMANCE.name(), 1); <START> waitForServerState(api(), serverId, State.PENDING_CHANGE, 30 * 60 * 1000, "Error"); <END> waitForServerState(api(), serverId, State.NORMAL, 30 * 60 * 1000, "Error"); }</code><technical_language>Is reconfigure operation is fast enough this state? sense wait for intermediate states</technical_language>

Target:
public void testReconfigureServer() { api().reconfigureServer(serverId, 4, CpuSpeed.HIGHPERFORMANCE.name(), 1); waitForServerState(api(), serverId, State.NORMAL, 30 * 60 * 1000, "Error"); }
Source:
<code>private static Constraint getConstraint(LiteralTree literal) { Constraint result = null; if (literal.is(Kind.BOOLEAN_LITERAL)) { result = "true".equals(literal.value()) ? Constraint.TRUE : Constraint.FALSE; } if (literal.is(Kind.STRING_LITERAL)) { result = literal.value().length() > 2 ? Constraint.TRUTHY_STRING_PRIMITIVE : Constraint.EMPTY_STRING_PRIMITIVE; } if (literal.is(Kind.NUMERIC_LITERAL)) { <START> result = isTruthyNumeric(literal) ? Constraint.POSITIVE_NUMBER_PRIMITIVE : Constraint.ZERO; <END> } if (literal.is(Kind.REGULAR_EXPRESSION_LITERAL)) { result = Constraint.REGEXP; } if (result != null) { return result; } throw new IllegalStateException("Unknown literal: " + literal); }</code><technical_language>rename this isPositiveNumeric</technical_language>

Target:
private static Constraint getConstraint(LiteralTree literal) { Constraint result = null; if (literal.is(Kind.BOOLEAN_LITERAL)) { result = "true".equals(literal.value()) ? Constraint.TRUE : Constraint.FALSE; } if (literal.is(Kind.STRING_LITERAL)) { result = literal.value().length() > 2 ? Constraint.TRUTHY_STRING_PRIMITIVE : Constraint.EMPTY_STRING_PRIMITIVE; } if (literal.is(Kind.NUMERIC_LITERAL)) { result = isZero(literal) ? Constraint.ZERO : Constraint.POSITIVE_NUMBER_PRIMITIVE; } if (literal.is(Kind.REGULAR_EXPRESSION_LITERAL)) { result = Constraint.REGEXP; } if (result != null) { return result; } throw new IllegalStateException("Unknown literal: " + literal); }
Source:
<code><START> private static Document parseInputStream( final InputStream instream ) <END> throws ParserConfigurationException, SAXException, IOException { final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setFeature( XMLConstants.FEATURE_SECURE_PROCESSING, true ); dbf.setFeature( "<LINK_0>", true ); final DocumentBuilder db = dbf.newDocumentBuilder(); return db.parse( new InputSource( instream ) ); }</code><technical_language>Suggest this public static else place call set a secure parser</technical_language>

Target:
private static Document parseInputStream( final InputStream instream ) throws ParserConfigurationException, SAXException, IOException { final DocumentBuilderFactory dbf = XMLParserFactoryProducer.createSecureDocBuilderFactory(); final DocumentBuilder db = dbf.newDocumentBuilder(); return db.parse( new InputSource( instream ) ); }
Source:
<code>private void onWsAgentConnectionIsLost() { eventBus.fireEvent(new WsAgentServerStoppedEvent(devMachineName)); Workspace workspace = appContext.getWorkspace(); <START> if (workspace == null || workspace.getStatus() != WorkspaceStatus.RUNNING) { <END> return; } dialogFactory .createChoiceDialog( localizationConstant.wsAgentNotRespondingDialogTitle(), localizationConstant.wsAgentNotRespondingDialogMessage(), localizationConstant.wsAgentNotRespondingDialogRestart(), localizationConstant.wsAgentNotRespondingDialogClose(), () -> { eventBus.addHandler(WorkspaceStoppedEvent.TYPE, event -> reloadPage(false)); actionManager.performAction(STOP_WORKSPACE, emptyMap()); }, null) .show(); }</code><technical_language>IDE initialization improved a lot in Che 6. Current workspace info set in AppContext IDE initialization. if IDE reach a workspace loading - IDE initialization fails. So, in Che 6, checking workspace == null is redundant appContext.getWorkspace() return null. If so, please ping me</technical_language>

Target:
private void onWsAgentConnectionIsLost() { WorkspaceImpl workspace = appContext.getWorkspace(); if (workspace.getStatus() != WorkspaceStatus.RUNNING) { return; } wsAgentServerUtilProvider .get() .getWsAgentServerMachine() .ifPresent(machine -> eventBus.fireEvent(new WsAgentServerStoppedEvent(machine.getName()))); dialogFactory .createChoiceDialog( localizationConstant.wsAgentNotRespondingDialogTitle(), localizationConstant.wsAgentNotRespondingDialogMessage(), localizationConstant.wsAgentNotRespondingDialogRestart(), localizationConstant.wsAgentNotRespondingDialogClose(), () -> { eventBus.addHandler(WorkspaceStoppedEvent.TYPE, event -> reloadPage(false)); actionManager.performAction(STOP_WORKSPACE, emptyMap()); }, null) .show(); }
Source:
<code>public void validateImpl(Query parameter) { List<String> validationErrors = new ArrayList<>(); if(CollectionUtils.isNullOrEmpty(parameter.getTable())) { validationErrors.add("table name cannot be null or empty"); } if(parameter.getSort() == null) { validationErrors.add("sort order needs to be specified"); } if(parameter.getFrom() < 0) { validationErrors.add("from must be non-negative integer"); } if(parameter.getLimit() <= 0) { validationErrors.add("limit must be positive integer"); } <START> if (parameter.getLimit() >= elasticsearchTuningConfig.getDocumentsLimitAllowed()){ <END> validationErrors.add(String.format("Limit more than %s is not supported", elasticsearchTuningConfig.getDocumentsLimitAllowed())); } if(!CollectionUtils.isNullOrEmpty(validationErrors)) { throw FoxtrotExceptions.createMalformedQueryException(parameter, validationErrors); } }</code><technical_language>greater</technical_language>

Target:
public void validateImpl(Query parameter) { List<String> validationErrors = new ArrayList<>(); if(CollectionUtils.isNullOrEmpty(parameter.getTable())) { validationErrors.add("table name cannot be null or empty"); } if(parameter.getSort() == null) { validationErrors.add("sort order needs to be specified"); } if(parameter.getFrom() < 0) { validationErrors.add("from must be non-negative integer"); } if(parameter.getLimit() <= 0) { validationErrors.add("limit must be positive integer"); } if (parameter.getLimit() > elasticsearchTuningConfig.getDocumentsLimitAllowed()){ validationErrors.add(String.format("Limit more than %s is not supported", elasticsearchTuningConfig.getDocumentsLimitAllowed())); } if(!CollectionUtils.isNullOrEmpty(validationErrors)) { throw FoxtrotExceptions.createMalformedQueryException(parameter, validationErrors); } }
Source:
<code>public void formatFilenameFromFormNameTest() { <START> assertNull(FormNameUtils.formatFilenameFromFormName(null)); <END> assertEquals("simple", FormNameUtils.formatFilenameFromFormName("simple")); assertEquals("CamelCase", FormNameUtils.formatFilenameFromFormName("CamelCase")); assertEquals("01234566789", FormNameUtils.formatFilenameFromFormName("01234566789")); assertEquals("trimWhitespace", FormNameUtils.formatFilenameFromFormName(" trimWhitespace ")); assertEquals("keep internal spaces", FormNameUtils.formatFilenameFromFormName("keep internal spaces")); assertEquals("other whitespace", FormNameUtils.formatFilenameFromFormName("other\n\twhitespace")); assertEquals("repeated whitespace", FormNameUtils.formatFilenameFromFormName("repeated whitespace")); assertEquals("Turkish İ kept", FormNameUtils.formatFilenameFromFormName("Turkish İ kept")); assertEquals("registered symbol stripped", FormNameUtils.formatFilenameFromFormName("registered symbol ® stripped")); assertEquals("unicode fragment stripped", FormNameUtils.formatFilenameFromFormName("unicode fragment \ud800 stripped")); }</code><technical_language>typically favored hamcrest assertThat matchers assertions read more sentences I @seadowg @grzesiek2010 typically do same: - assertThat(FormNameUtils.formatFilenameFromFormName(null), is(nullValue())); - assertThat(FormNameUtils.formatFilenameFromFormName("simple"), is("simple")); I feel strongly imposing a standard hard read wanted knew tools</technical_language>

Target:
public void formatFilenameFromFormNameTest() { assertThat(formatFilenameFromFormName(null), is(nullValue())); assertThat(formatFilenameFromFormName("simple"), is("simple")); assertThat(formatFilenameFromFormName("CamelCase"), is("CamelCase")); assertThat(formatFilenameFromFormName("01234566789"), is("01234566789")); assertThat(formatFilenameFromFormName(" trimWhitespace "), is("trimWhitespace")); assertThat(formatFilenameFromFormName("keep internal spaces"), is("keep internal spaces")); assertThat(formatFilenameFromFormName("other\n\twhitespace"), is("other whitespace")); assertThat(formatFilenameFromFormName("repeated whitespace"), is("repeated whitespace")); assertThat(formatFilenameFromFormName("Turkish İ kept"), is("Turkish İ kept")); assertThat(formatFilenameFromFormName("registered symbol ® stripped"), is("registered symbol stripped")); assertThat(formatFilenameFromFormName("unicode fragment \ud800 stripped"), is("unicode fragment stripped")); }
Source:
<code>private int calculateDropdownTop() { int ddTop; DropdownPosition dropdownPosition = options.getDropdownPosition(); switch (dropdownPosition.getPosition()) { case DOWN: ddTop = positionDown(); break; case UP: ddTop = positionUp(); break; case AUTO: if (dropdownPosition.getBoundaries() == null) { ddTop = positionRelativeToWindow(); } else { ddTop = positionRelativeToBoundaries(); } break; default: <START> ddTop = 0; <END> break; } return ddTop; }</code><technical_language>default position</technical_language>

Target:
private int calculateDropdownTop() { int ddTop; DropdownPosition dropdownPosition = options.getDropdownPosition(); switch (dropdownPosition.getPosition()) { case BELOW: ddTop = positionBelow(); break; case ABOVE: ddTop = positionAbove(); break; case AUTO: if (dropdownPosition.getBoundaries() == null) { ddTop = positionRelativeToWindow(); } else { ddTop = positionRelativeToBoundaries(); } break; default: ddTop = positionBelow(); break; } return ddTop; }
Source:
<code>protected boolean engineVerify(final String algorithm, final Password password, final char[] guess) throws InvalidKeyException { if (password instanceof AbstractPasswordImpl) { final AbstractPasswordImpl abstractPassword = (AbstractPasswordImpl) password; if (algorithm.equals(abstractPassword.getAlgorithm())) { return abstractPassword.verify(guess); } } switch (algorithm) { <START> case ALGORITHM_SHA256CRYPT: <END> case ALGORITHM_SHA512CRYPT: { if (password instanceof UnixSHACryptPassword) { try { return UnixSHACryptPasswordUtil.verify(password, guess); } catch (NoSuchAlgorithmException e) { throw new InvalidKeyException("Cannot verify password", e); } } else { break; } } } throw new InvalidKeyException(); }</code><technical_language>this part handled in block, UnixSHACryptPassword extending AbstractPasswordImpl</technical_language>

Target:
protected boolean engineVerify(final String algorithm, final Password password, final char[] guess) throws InvalidKeyException { if (password instanceof AbstractPasswordImpl) { final AbstractPasswordImpl abstractPassword = (AbstractPasswordImpl) password; if (algorithm.equals(abstractPassword.getAlgorithm())) { return abstractPassword.verify(guess); } } throw new InvalidKeyException(); }
Source:
<code>public void run() { if (!getDRepresentationToExport().isEmpty()) { super.run(); } else { MessageDialog.openInformation(Display.getCurrent().getActiveShell(), "Export representations", "The selected <START> resource does not <END> contain any representation to export."); } }</code><technical_language>do consider resource, selected elements (and descendants). read "The selected elements do contain"</technical_language>

Target:
public void run() { if (!getDRepresentationToExport().isEmpty()) { super.run(); } else { MessageDialog.openInformation(Display.getCurrent().getActiveShell(), "Export representations", "The selected elements do not contain any representation to export."); } }
Source:
<code><START> private byte[] instrument(final byte[] source) { <END> final long classId = CRC64.classId(source); final int originalVersion = BytecodeVersion.read(source); final byte[] b = BytecodeVersion.downgradeIfNeeded(originalVersion, source); final ClassReader reader = new ClassReader(b); final ClassWriter writer = new ClassWriter(reader, 0) { @Override protected String getCommonSuperClass(final String type1, final String type2) { throw new IllegalStateException(); } }; final IProbeArrayStrategy strategy = ProbeArrayStrategyFactory .createFor(classId, reader, accessorGenerator); final ClassVisitor visitor = new ClassProbesAdapter( new ClassInstrumenter(strategy, writer), true); reader.accept(visitor, ClassReader.EXPAND_FRAMES); final byte[] instrumented = writer.toByteArray(); BytecodeVersion.set(instrumented, originalVersion); return instrumented; }</code><technical_language>Move private method public instrument() methods</technical_language>

Target:
private byte[] instrument(final byte[] source) { final long classId = CRC64.classId(source); final int originalVersion = BytecodeVersion.get(source); final byte[] b = BytecodeVersion.downgradeIfNeeded(originalVersion, source); final ClassReader reader = new ClassReader(b); final ClassWriter writer = new ClassWriter(reader, 0) { @Override protected String getCommonSuperClass(final String type1, final String type2) { throw new IllegalStateException(); } }; final IProbeArrayStrategy strategy = ProbeArrayStrategyFactory .createFor(classId, reader, accessorGenerator); final ClassVisitor visitor = new ClassProbesAdapter( new ClassInstrumenter(strategy, writer), true); reader.accept(visitor, ClassReader.EXPAND_FRAMES); final byte[] instrumented = writer.toByteArray(); BytecodeVersion.set(instrumented, originalVersion); return instrumented; }
Source:
<code>public void testFileBatchInputFormatAvro() throws Exception { File fileAvro = new File(temporaryFolder.newFolder(), "test.avro"); String outputDatasetName = "test-filesource-avro"; <START> ApplicationManager appManager = createSourceAndDeployApp(fileAvro, "avro", outputDatasetName, RECORD_SCHEMA); <END> org.apache.avro.Schema avroSchema = new org.apache.avro.Schema.Parser().parse(RECORD_SCHEMA.toString()); GenericRecord record = new GenericRecordBuilder(avroSchema) .set("i", Integer.MAX_VALUE) .set("l", Long.MAX_VALUE) .set("file", fileAvro.getAbsolutePath()) .build(); DataSetManager<TimePartitionedFileSet> inputManager = getDataset("TestFile"); DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(avroSchema); DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(datumWriter); dataFileWriter.create(avroSchema, fileAvro); dataFileWriter.append(record); dataFileWriter.close(); inputManager.flush(); workflowStartAndWait(appManager); List<StructuredRecord> expected = ImmutableList.of( StructuredRecord.builder(RECORD_SCHEMA) .set("i", Integer.MAX_VALUE) .set("l", Long.MAX_VALUE) .set("file", fileAvro.toURI().toString()) .build() ); DataSetManager<Table> outputManager = getDataset(outputDatasetName); List<StructuredRecord> output = MockSink.readOutput(outputManager); Assert.assertEquals(output, expected); }</code><technical_language>avro parquet tests a schema is different, compatible to, write schema. This is test logic is setting input schema key in input format. For example, I able remove a field write schema read correctly</technical_language>

Target:
public void testFileBatchInputFormatAvro() throws Exception { File fileAvro = new File(temporaryFolder.newFolder(), "test.avro"); String outputDatasetName = "test-filesource-avro"; String appName = "FileSourceAvro"; ApplicationManager appManager = createSourceAndDeployApp(appName, fileAvro, "avro", outputDatasetName, RECORD_SCHEMA); org.apache.avro.Schema avroSchema = new org.apache.avro.Schema.Parser().parse(RECORD_SCHEMA.toString()); GenericRecord record = new GenericRecordBuilder(avroSchema) .set("i", Integer.MAX_VALUE) .set("l", Long.MAX_VALUE) .set("file", fileAvro.getAbsolutePath()) .build(); DataSetManager<TimePartitionedFileSet> inputManager = getDataset("TestFile"); DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(avroSchema); DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(datumWriter); dataFileWriter.create(avroSchema, fileAvro); dataFileWriter.append(record); dataFileWriter.close(); inputManager.flush(); workflowStartAndWait(appManager); List<StructuredRecord> expected = ImmutableList.of( StructuredRecord.builder(RECORD_SCHEMA) .set("i", Integer.MAX_VALUE) .set("l", Long.MAX_VALUE) .set("file", fileAvro.toURI().toString()) .build() ); DataSetManager<Table> outputManager = getDataset(outputDatasetName); List<StructuredRecord> output = MockSink.readOutput(outputManager); Assert.assertEquals(output, expected); }
Source:
<code>public static MapillaryImportedImage createInstance(final ImageEntry geoImage) { if (geoImage == null) { return null; } if (geoImage.getFile() == null) { throw new IllegalArgumentException("Can't create an imported image from an ImageEntry without associated file."); } final CachedLatLon cachedCoord = geoImage.getPos(); LatLon coord = cachedCoord == null ? null : cachedCoord.getRoundedToOsmPrecision(); if (coord == null) { final MapView mv = MapillaryPlugin.getMapView(); coord = mv == null ? new LatLon(0, 0) : mv.getProjection().eastNorth2latlon(mv.getCenter()); } final double ca = geoImage.getExifImgDir() == null ? 0 : geoImage.getExifImgDir(); final long time = geoImage.hasGpsTime() ? geoImage.getGpsTime().getTime() : geoImage.hasExifTime() ? geoImage.getExifTime().getTime() : System.currentTimeMillis(); final double width = geoImage.getWidth(); final double height = geoImage.getHeight(); <START> final boolean pano = (width >= 4096) && (width == height * 2); <END> return new MapillaryImportedImage(coord, ca, geoImage.getFile(), pano, time); }</code><technical_language>familiar enough Mapillary if a panorama a fixed ratio of width == height * 2. Is case, width >= height * 2 safer</technical_language>

Target:
public static MapillaryImportedImage createInstance(final ImageEntry geoImage) { if (geoImage == null) { return null; } if (geoImage.getFile() == null) { throw new IllegalArgumentException("Can't create an imported image from an ImageEntry without associated file."); } final CachedLatLon cachedCoord = geoImage.getPos(); LatLon coord = cachedCoord == null ? null : cachedCoord.getRoundedToOsmPrecision(); if (coord == null) { final MapView mv = MapillaryPlugin.getMapView(); coord = mv == null ? new LatLon(0, 0) : mv.getProjection().eastNorth2latlon(mv.getCenter()); } final double ca = geoImage.getExifImgDir() == null ? 0 : geoImage.getExifImgDir(); final long time = geoImage.hasGpsTime() ? geoImage.getGpsTime().getTime() : geoImage.hasExifTime() ? geoImage.getExifTime().getTime() : System.currentTimeMillis(); boolean pano = false; try (FileInputStream fis = new FileInputStream(geoImage.getFile())) { pano = ImageMetaDataUtil.isPanorama(fis); } catch(IOException ex) { Logging.trace(ex); } return new MapillaryImportedImage(coord, ca, geoImage.getFile(), pano, time); }
Source:
<code>private static void loadProperties(File file, Properties props, String listKey) throws IOException { String[] keys = getArray(props, listKey); for (String key : keys) { <START> File scannerFile = new File(file.getParent(), key + ".properties"); try (InputStream pluginFis = Files.newInputStream(scannerFile.toPath())) { Properties p = new Properties(); p.load(pluginFis); for (Map.Entry<Object, Object> prop : p.entrySet()) { props.put(key + "." + prop.getKey(), prop.getValue()); } <END> } } }</code><technical_language>mixing "scanner" "plugin" wording in this method. abstract method, I remain consistent, else (component?)</technical_language>

Target:
private static void loadProperties(File file, Properties props, String listKey) throws IOException { String[] keys = getArray(props, listKey); for (String key : keys) { File propFile = new File(file.getParent(), key + ".properties"); try (InputStream fileInputStream = Files.newInputStream(propFile.toPath())) { Properties p = new Properties(); p.load(fileInputStream); for (Map.Entry<Object, Object> prop : p.entrySet()) { props.put(key + "." + prop.getKey(), prop.getValue()); } } } }