auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> protected <T extends AnkiActivity> T startActivityNormallyOpenCollectionWithIntent(Class<T> clazz, Intent i) { ActivityController multimediaController = Robolectric.buildActivity(clazz, i) .create().start().resume().visible(); return (T) multimediaController.get(); } <END></code><technical_language>read I thought this bound multimedia work a fully general purpose activity starter? suggestion protected <T extends AnkiActivity> T startActivityNormallyOpenCollectionWithIntent(Class<T> clazz, Intent i) { ActivityController controller = Robolectric.buildActivity(clazz, i) .create().start().resume().visible(); //noinspection unchecked return (T) controller.get(); }</technical_language>

Target:
protected <T extends AnkiActivity> T startActivityNormallyOpenCollectionWithIntent(Class<T> clazz, Intent i) { ActivityController controller = Robolectric.buildActivity(clazz, i) .create().start().resume().visible(); return (T) controller.get(); }
Source:
<code>public Factory updateFactory(@ApiParam(value = "Factory ID", required = true) @PathParam("id") String id, Factory newFactory) throws ForbiddenException, NotFoundException, ApiException { final User user = EnvironmentContext.getCurrent().getUser(); if (user == null) { throw new ForbiddenException("No authenticated user"); } Factory existingFactory = factoryStore.getFactory(id); if (existingFactory == null) { throw new NotFoundException("Factory with id " + id + " does not exist."); } String userId = user.getId(); factoryEditValidator.validate(existingFactory, userId); Author newAuthor = newFactory.getCreator(); if (newAuthor == null) { newAuthor = DtoFactory.getInstance().createDto(Author.class); newFactory.setCreator(newAuthor); <START> } <END> if (newAuthor.getUserId() == null) { newAuthor.setUserId(user.getId()); } newFactory.getCreator().withCreated(existingFactory.getCreator().getCreated()); newFactory.setId(existingFactory.getId()); createValidator.validateOnCreate(newFactory); try { newFactory.setLinks(linksHelper.createLinks(newFactory, factoryStore.getFactoryImages(id, null), uriInfo)); } catch (UnsupportedEncodingException e) { throw new ConflictException(e.getLocalizedMessage()); } factoryStore.updateFactory(id, newFactory); return newFactory; }</code><technical_language>throw exception if author is unknown</technical_language>

Target:
public Factory updateFactory(@ApiParam(value = "Factory ID", required = true) @PathParam("id") String id, Factory newFactory) throws ForbiddenException, NotFoundException, ApiException { if (newFactory == null) { throw new ServerException("The updating factory shouldn't be null"); } Factory existingFactory = factoryStore.getFactory(id); if (existingFactory == null) { throw new NotFoundException("Factory with id " + id + " does not exist."); } final User user = EnvironmentContext.getCurrent().getUser(); String userId = user.getId(); factoryEditValidator.validate(existingFactory, userId); Author newAuthor = newFactory.getCreator(); if (newAuthor == null || newAuthor.getUserId() == null) { newAuthor = DtoFactory.getInstance().createDto(Author.class); newFactory.setCreator(newAuthor); } if (newAuthor.getUserId() == null) { newAuthor.setUserId(user.getId()); } newFactory.getCreator().withCreated(existingFactory.getCreator().getCreated()); newFactory.setId(existingFactory.getId()); createValidator.validateOnCreate(newFactory); factoryStore.updateFactory(id, newFactory); try { newFactory.setLinks(linksHelper.createLinks(newFactory, factoryStore.getFactoryImages(id, null), uriInfo)); } catch (UnsupportedEncodingException e) { throw new ServerException(e.getLocalizedMessage()); } return newFactory; }
Source:
<code>public boolean create(String roomName, String subject, HashMap<String, String> customConfigs, List<Jid> occupants) throws NotConnectedException, XmppStringprepException, InterruptedException { MUCLightCreateIQ createMUCLightIQ = new MUCLightCreateIQ(room, roomName, occupants); connection.addSyncStanzaListener(messageListener, fromRoomGroupchatFilter); messageCollector = connection.createPacketCollector(fromRoomGroupchatFilter); StanzaFilter responseFilter = new AndFilter(FromMatchesFilter.createBare(room.asDomainBareJid()), new StanzaTypeFilter(IQ.class)); try { IQ responseIq = connection.createPacketCollectorAndSend(responseFilter, createMUCLightIQ) .nextResultOrThrow(); return responseIq.getType().equals(IQ.Type.result); } catch (NoResponseException | XMPPErrorException e) { removeConnectionCallbacks(); return false; <START> } catch (InterruptedException e) { <END> removeConnectionCallbacks(); return false; } }</code><technical_language>this part of multi-catch above</technical_language>

Target:
public void create(String roomName, String subject, HashMap<String, String> customConfigs, List<Jid> occupants) throws Exception { MUCLightCreateIQ createMUCLightIQ = new MUCLightCreateIQ(room, roomName, occupants); messageCollector = connection.createPacketCollector(fromRoomGroupchatFilter); try { connection.createPacketCollectorAndSend(createMUCLightIQ).nextResultOrThrow(); } catch (InterruptedException | NoResponseException | XMPPErrorException e) { removeConnectionCallbacks(); throw e; } }
Source:
<code>public CustomParseSpec( @JsonProperty("timestampSpec") TimestampSpec timestampSpec, @JsonProperty("dimensionsSpec") DimensionsSpec dimensionsSpec, @JsonProperty("parserClass") String parserClass, @JsonProperty("properties") Map<String, Object> properties ) { super(timestampSpec, dimensionsSpec); this.parserClass = parserClass; this.properties = properties == null ? ImmutableMap.<String, Object>of() : properties; <START> ClassLoader loader = Thread.currentThread().getContextClassLoader(); <END> if (loader == null) { loader = ParseSpec.class.getClassLoader(); } try { constructor = Class.forName(parserClass, true, loader) .getConstructor(TimestampSpec.class, DimensionsSpec.class, Map.class); } catch (Exception e) { throw new IllegalArgumentException(e); } }</code><technical_language>this is for now, nice get more feedback other ways of extending parsers reflection</technical_language>

Target:
public CustomParseSpec( @JsonProperty("timestampSpec") TimestampSpec timestampSpec, @JsonProperty("dimensionsSpec") DimensionsSpec dimensionsSpec, @JsonProperty("parserClass") String parserClass, @JsonProperty("properties") Map<String, Object> properties ) { super(timestampSpec, dimensionsSpec); this.parserClass = parserClass; this.properties = properties == null ? ImmutableMap.<String, Object>of() : properties; ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { loader = ParseSpec.class.getClassLoader(); } try { constructor = Class.forName(parserClass, true, loader) .getConstructor(TimestampSpec.class, DimensionsSpec.class, Map.class); } catch (Exception e) { throw new IllegalArgumentException( "Failed to find proper constructor of parser `" + parserClass + "` by exception " + e, e ); } }
Source:
<code>public void testCourseInfoPaths() throws Exception { String url = "edxapp://course_info?path_id=course/cosmology-anux-anu-astro4x"; String pathId = Uri.parse(url).getQueryParameter(URLInterceptorWebViewClient.PARAM_PATH_ID); if(pathId.startsWith(URLInterceptorWebViewClient.COURSE)){ pathId = pathId.replaceFirst(URLInterceptorWebViewClient.COURSE,"").trim(); } assertNotNull(pathId); assertEquals("cosmology-anux-anu-astro4x", pathId); <START> print("Path Id - "+pathId); <END> }</code><technical_language><code>print()</code> required. Please remove</technical_language>

Target:
public void testCourseInfoPaths() throws Exception { String url = "edxapp://course_info?path_id=course/cosmology-anux-anu-astro4x"; String pathId = Uri.parse(url).getQueryParameter(URLInterceptorWebViewClient.PARAM_PATH_ID); if(pathId.startsWith(URLInterceptorWebViewClient.COURSE)){ pathId = pathId.replaceFirst(URLInterceptorWebViewClient.COURSE,"").trim(); } assertNotNull(pathId); assertEquals("cosmology-anux-anu-astro4x", pathId); }
Source:
<code>public static String getConcatedTypeNameValues(List<String> typeNames, String typeNameStr, String separator) { if ((typeNames == null) || (typeNames.size() == 0)) { return null; } Map<String, String> typeNameValueMap = getTypeNameValueMap(typeNameStr); StringBuilder sb = new StringBuilder(); for (String key : typeNames) { String result = typeNameValueMap.get(key); <START> if (result != null && !StringUtils.isBlank(result)) { <END> sb.append(result); sb.append(separator); } } return org.apache.commons.lang.StringUtils.chomp(sb.toString(), separator); }</code><technical_language>I more put typeNameValueMap null. fix there</technical_language>

Target:
public static String getConcatedTypeNameValues(List<String> typeNames, String typeNameStr, String separator) { if ((typeNames == null) || (typeNames.size() == 0)) { return null; } Map<String, String> typeNameValueMap = getTypeNameValueMap(typeNameStr); StringBuilder sb = new StringBuilder(); for (String key : typeNames) { String result = typeNameValueMap.get(key); if (result != null) { sb.append(result); sb.append(separator); } } return org.apache.commons.lang.StringUtils.chomp(sb.toString(), separator); }
Source:
<code>protected void activate() { tabsSynchronizer = new SashTabDecorationSynchronizer(sashContainer); <START> sashContainer.addPageLifeCycleListener(pageLifeCycleEventListener); <END> }</code><technical_language>removed in #deactivate</technical_language>

Target:
protected void activate() { sashContainer = new SashWindowsContainer(this); sashContainer.setContentProvider(getContentProvider()); sashContainer.createPartControl(parentComposite); tabMouseEventListener = new TabMouseEventListener(sashContainer, getSite()); tabsSynchronizer = new SashTabDecorationSynchronizer(sashContainer); sashContainer.addPageLifeCycleListener(pageLifeCycleEventListener); }
Source:
<code>private void writeThreadPool(XMLExtendedStreamWriter writer, String name, ThreadPoolConfiguration threadPoolConfiguration) throws XMLStreamException { ThreadPoolExecutorFactory<?> threadPoolFactory = threadPoolConfiguration.threadPoolFactory(); if (threadPoolFactory != null) { writer.writeStartElement(THREAD_POOL_FACTORIES.get(threadPoolFactory.getClass().getName())); writer.writeAttribute(Attribute.NAME, name); ThreadFactory threadFactory = threadPoolConfiguration.threadFactory(); if (threadFactory instanceof DefaultThreadFactory) { DefaultThreadFactory tf = (DefaultThreadFactory) threadFactory; writer.writeAttribute(Attribute.THREAD_FACTORY, tf.getName()); } if (threadPoolFactory instanceof BlockingThreadPoolExecutorFactory) { BlockingThreadPoolExecutorFactory pool = (BlockingThreadPoolExecutorFactory) threadPoolFactory; writer.writeAttribute(Attribute.MAX_THREADS, Integer.toString(pool.maxThreads())); writer.writeAttribute(Attribute.CORE_THREADS, Integer.toString(pool.coreThreads())); writer.writeAttribute(Attribute.QUEUE_LENGTH, Integer.toString(pool.queueLength())); writer.writeAttribute(Attribute.KEEP_ALIVE_TIME, Long.toString(pool.keepAlive())); <START> } else if (threadPoolFactory instanceof CachedThreadPoolExecutorFactory) { <END> CachedThreadPoolExecutorFactory pool = (CachedThreadPoolExecutorFactory) threadPoolFactory; } writer.writeEndElement(); } }</code><technical_language>this else branch is needed</technical_language>

Target:
private void writeThreadPool(XMLExtendedStreamWriter writer, String name, ThreadPoolConfiguration threadPoolConfiguration) throws XMLStreamException { ThreadPoolExecutorFactory<?> threadPoolFactory = threadPoolConfiguration.threadPoolFactory(); if (threadPoolFactory != null) { writer.writeStartElement(THREAD_POOL_FACTORIES.get(threadPoolFactory.getClass().getName())); writer.writeAttribute(Attribute.NAME, name); ThreadFactory threadFactory = threadPoolConfiguration.threadFactory(); if (threadFactory instanceof DefaultThreadFactory) { DefaultThreadFactory tf = (DefaultThreadFactory) threadFactory; writer.writeAttribute(Attribute.THREAD_FACTORY, tf.getName()); } if (threadPoolFactory instanceof BlockingThreadPoolExecutorFactory) { BlockingThreadPoolExecutorFactory pool = (BlockingThreadPoolExecutorFactory) threadPoolFactory; writer.writeAttribute(Attribute.MAX_THREADS, Integer.toString(pool.maxThreads())); writer.writeAttribute(Attribute.CORE_THREADS, Integer.toString(pool.coreThreads())); writer.writeAttribute(Attribute.QUEUE_LENGTH, Integer.toString(pool.queueLength())); writer.writeAttribute(Attribute.KEEP_ALIVE_TIME, Long.toString(pool.keepAlive())); } writer.writeEndElement(); } }
Source:
<code>public static Set<?> toSet( Object value ) { if ( value == null || value instanceof NoValue ) { return Collections.emptySet(); } else if ( value instanceof SequenceValue ) { SequenceValue sequenceValue = (SequenceValue) value; Iterator<AnyValue> iterator = sequenceValue.iterator(); <START> Set<AnyValue> set = sequenceValue.iterationPreference() == RANDOM_ACCESS ? <END> new HashSet<>( sequenceValue.length() ) : new HashSet<>(); while ( iterator.hasNext() ) { AnyValue element = iterator.next(); set.add( element ); } return set; } else if ( value instanceof Collection<?> ) { return new HashSet<>( (Collection<?>) value ); } else if ( value instanceof LongStream ) { LongStream stream = (LongStream) value; return stream.boxed().collect( Collectors.toSet() ); } else if ( value instanceof IntStream ) { IntStream stream = (IntStream) value; return stream.boxed().collect( Collectors.toSet() ); } else if ( value instanceof DoubleStream ) { DoubleStream stream = (DoubleStream) value; return stream.boxed().collect( Collectors.toSet() ); } else if ( value.getClass().isArray() ) { int len = Array.getLength( value ); HashSet<Object> collection = new HashSet<>( len ); for ( int i = 0; i < len; i++ ) { collection.add( Array.get( value, i ) ); } return collection; } throw new CypherTypeException( "Don't know how to create a set out of " + value.getClass().getSimpleName(), null ); }</code><technical_language>If RANDOM_ACCESS save creating iterator well, if ( sequenceValue.iterationPreference() == RANDOM_ACCESS ) { for ( int i = 0; i < sequenceValue.length(); i++ ) { set.add( sequenceValue.value( i ) ); } } else { //same }</technical_language>

Target:
public static Set<?> toSet( Object value ) { if ( value == null || value == NO_VALUE ) { return Collections.emptySet(); } else if ( value instanceof SequenceValue ) { SequenceValue sequenceValue = (SequenceValue) value; Iterator<AnyValue> iterator = sequenceValue.iterator(); Set<AnyValue> set; if ( sequenceValue.iterationPreference() == RANDOM_ACCESS ) { int length = sequenceValue.length(); set = new HashSet<>( length ); for ( int i = 0; i < length; i++ ) { set.add( sequenceValue.value( i ) ); } } else { set = new HashSet<>(); while ( iterator.hasNext() ) { AnyValue element = iterator.next(); set.add( element ); } } return set; } else if ( value instanceof Collection<?> ) { return new HashSet<>( (Collection<?>) value ); } else if ( value instanceof LongStream ) { LongStream stream = (LongStream) value; return stream.boxed().collect( Collectors.toSet() ); } else if ( value instanceof IntStream ) { IntStream stream = (IntStream) value; return stream.boxed().collect( Collectors.toSet() ); } else if ( value instanceof DoubleStream ) { DoubleStream stream = (DoubleStream) value; return stream.boxed().collect( Collectors.toSet() ); } else if ( value.getClass().isArray() ) { int len = Array.getLength( value ); HashSet<Object> collection = new HashSet<>( len ); for ( int i = 0; i < len; i++ ) { collection.add( Array.get( value, i ) ); } return collection; } throw new CypherTypeException( "Don't know how to create a set out of " + value.getClass().getSimpleName(), null ); }
Source:
<code>public void updateMetadata(String name, String metadataName, Metadata metadata) throws EntityNotFoundException { Product product = null; Metadata updatedMetadata = null; try { product = productManager.load(name); updatedMetadata = product.getMetadata(metadataName); if (updatedMetadata == null || !updatedMetadata.getKey().equals(metadataName)) { log.warning("Exception: metadata not found or wrong " + metadata.getKey()); throw new APIException(new EntityNotFoundException(Metadata.class, "Metadata not found : " + metadataName, metadata)); } } catch (Exception e) { <START> log.warning("EntityNotFoundException: " + e.getMessage()); <END> throw new APIException(new EntityNotFoundException(Product.class, name, e)); } if (metadata.getDescription()!= null) { updatedMetadata.setDescription(metadata.getDescription()); } updatedMetadata.setValue(metadata.getValue()); try { productManager.update(product); } catch (Exception e) { log.warning("Exception but it works "+ e.getMessage()); } }</code><technical_language>more explicit write a log message. Anyway, a warning log message error log message</technical_language>

Target:
public void updateMetadata(String name, String metadataName, Metadata metadata) throws APIException { Product product = null; Metadata updatedMetadata = null; try { product = productManager.load(name); } catch (Exception e) { log.warning("The product: " + name + " does not exist" + e.getMessage()); throw new APIException(new EntityNotFoundException(Product.class, name, e)); } try { updatedMetadata = product.getMetadata(metadataName); } catch (Exception e) { log.warning("Exception: metadata not found or wrong" + metadata.getKey()); throw new APIException(new EntityNotFoundException(Metadata.class, "Metadata not found : " + metadataName, metadata)); } if (metadata.getDescription()!= null) { updatedMetadata.setDescription(metadata.getDescription()); } updatedMetadata.setValue(metadata.getValue()); try { productManager.update(product); } catch (Exception e) { log.warning("Exception but it works " + e.getMessage()); } }
Source:
<code>private ActivityLogEntry(Builder builder) { logTime = builder.logTime; actionServletName = (builder.actionServletName == null) ? Const.ActivityLog.UNKNOWN : builder.actionServletName; actionTimeTaken = builder.actionTimeTaken; actionName = (builder.actionName == null) ? Const.ActivityLog.UNKNOWN : builder.actionName; userRole = (builder.userRole == null) ? Const.ActivityLog.UNKNOWN : builder.userRole; userName = (builder.userName == null) ? Const.ActivityLog.UNKNOWN : builder.userName; userGoogleId = (builder.userGoogleId == null) ? Const.ActivityLog.UNKNOWN : builder.userGoogleId; userEmail = (builder.userEmail == null) ? Const.ActivityLog.UNKNOWN : builder.userEmail; logMessage = (builder.logMessage == null) ? Const.ActivityLog.UNKNOWN : builder.logMessage; actionUrl = (builder.actionUrl == null) ? Const.ActivityLog.UNKNOWN : builder.actionUrl; logId = (builder.logId == null) <START> ? Const.ActivityLog.UNKNOWN : builder.logId; <END> actionTimeTaken = builder.actionTimeTaken; isMasqueradeUserRole = builder.isMasqueradeUserRole; }</code><technical_language>null checks moved builder instead default values a single chunk of code</technical_language>

Target:
private ActivityLogEntry(Builder builder) { constructFromBuilder(builder); }
Source:
<code>private void archive(Injector injector) throws IOException { ConfigFactory cf = injector.getInstance(ConfigFactory.class); ConfigLoaderManager loader = injector.getInstance(ConfigLoaderManager.class); <START> Path projectPath = (projectDirName == null) ? <END> Paths.get("").toAbsolutePath() : Paths.get(projectDirName).normalize().toAbsolutePath(); injector.getInstance(Archiver.class).createArchive(projectPath, Paths.get(output)); out.println("Created " + output + "."); out.println("Use `" + programName + " upload <path.tar.gz> <project> <revision>` to upload it a server."); out.println(""); out.println(" Examples:"); out.println(" $ " + programName + " upload " + output + " $(basename $(pwd)) -r $(date +%Y%m%d-%H%M%S)"); out.println(" $ " + programName + " upload " + output + " $(git rev-parse --abbrev-ref HEAD) -r $(git rev-parse HEAD)"); out.println(""); }</code><technical_language>fields (params paramsFile ) removed now</technical_language>

Target:
private void archive(Injector injector) throws IOException { Path projectPath = (projectDirName == null) ? Paths.get("").toAbsolutePath() : Paths.get(projectDirName).normalize().toAbsolutePath(); injector.getInstance(Archiver.class).createArchive(projectPath, Paths.get(output)); out.println("Created " + output + "."); out.println("Use `" + programName + " upload <path.tar.gz> <project> <revision>` to upload it a server."); out.println(""); out.println(" Examples:"); out.println(" $ " + programName + " upload " + output + " $(basename $(pwd)) -r $(date +%Y%m%d-%H%M%S)"); out.println(" $ " + programName + " upload " + output + " $(git rev-parse --abbrev-ref HEAD) -r $(git rev-parse HEAD)"); out.println(""); }
Source:
<code>public void testEquals() { List args = new ArrayList<String>(); <START> Map map = new HashMap<String,String>(); <END> args.add("foo"); map.put("bar", "baz"); TaskLaunchRequest request = new TaskLaunchRequest(URI, Collections.EMPTY_LIST, Collections.EMPTY_MAP, Collections.EMPTY_MAP); TaskLaunchRequest request2 = new TaskLaunchRequest(URI, Collections.EMPTY_LIST, Collections.EMPTY_MAP, Collections.EMPTY_MAP); assertFalse(request.equals(null)); assertFalse(request.equals("nope")); assertTrue(request.equals(request)); assertTrue(request.equals(request2)); TaskLaunchRequest requestDiff = new TaskLaunchRequest("http://oops", Collections.EMPTY_LIST, Collections.EMPTY_MAP, Collections.EMPTY_MAP); assertFalse(request.equals(requestDiff)); requestDiff = new TaskLaunchRequest(URI, args, Collections.EMPTY_MAP, Collections.EMPTY_MAP); assertFalse(request.equals(requestDiff)); requestDiff = new TaskLaunchRequest(URI, null, null, null); assertTrue(request.equals(requestDiff)); requestDiff = new TaskLaunchRequest(URI, Collections.EMPTY_LIST, map, Collections.EMPTY_MAP); assertFalse(request.equals(requestDiff)); requestDiff = new TaskLaunchRequest(URI, Collections.EMPTY_LIST, Collections.EMPTY_MAP, map); assertFalse(request.equals(requestDiff)); assertEquals(request.hashCode(), request.hashCode()); }</code><technical_language>Generics for List Map</technical_language>

Target:
public void testEquals() { List<String> args = new ArrayList<>(); Map<String, String> map = new HashMap<>(); args.add("foo"); map.put("bar", "baz"); TaskLaunchRequest request = new TaskLaunchRequest(URI, Collections.EMPTY_LIST, Collections.EMPTY_MAP, Collections.EMPTY_MAP); TaskLaunchRequest request2 = new TaskLaunchRequest(URI, Collections.EMPTY_LIST, Collections.EMPTY_MAP, Collections.EMPTY_MAP); assertFalse(request.equals(null)); assertFalse(request.equals("nope")); assertTrue(request.equals(request)); assertTrue(request.equals(request2)); TaskLaunchRequest requestDiff = new TaskLaunchRequest("http://oops", Collections.EMPTY_LIST, Collections.EMPTY_MAP, Collections.EMPTY_MAP); assertFalse(request.equals(requestDiff)); requestDiff = new TaskLaunchRequest(URI, args, Collections.EMPTY_MAP, Collections.EMPTY_MAP); assertFalse(request.equals(requestDiff)); requestDiff = new TaskLaunchRequest(URI, null, null, null); assertTrue(request.equals(requestDiff)); requestDiff = new TaskLaunchRequest(URI, Collections.EMPTY_LIST, map, Collections.EMPTY_MAP); assertFalse(request.equals(requestDiff)); requestDiff = new TaskLaunchRequest(URI, Collections.EMPTY_LIST, Collections.EMPTY_MAP, map); assertFalse(request.equals(requestDiff)); assertEquals(request.hashCode(), request.hashCode()); }
Source:
<code>public TmfConstantTransform() { <START> this(new TmfNanoTimestamp(0)); <END> }</code><technical_language>fOffset = 0</technical_language>

Target:
public TmfConstantTransform() { fOffset = 0; }
Source:
<code>public void copyUpdatedMetadata(UpdatedMetaDataTracker other) { int size = updateMetaDataList.size(); for (UpdateMetaData updateMetaData : other.updateMetaDataList) { <START> updateMetaDataList.add(updateMetaData); <END> String key = getKey(normalizeIdentifier(updateMetaData.getDbName()), normalizeIdentifier(updateMetaData.getTableName())); updateMetaDataMap.put(key, size++); } }</code><technical_language>For safer side, check if entry exist adding it</technical_language>

Target:
public void copyUpdatedMetadata(UpdatedMetaDataTracker other) { int size = updateMetaDataList.size(); for (UpdateMetaData updateMetaDataOther : other.updateMetaDataList) { String key = getKey(normalizeIdentifier(updateMetaDataOther.getDbName()), normalizeIdentifier(updateMetaDataOther.getTableName())); Integer idx = updateMetaDataMap.get(key); if (idx == null) { updateMetaDataList.add(updateMetaDataOther); updateMetaDataMap.put(key, size++); } else if (updateMetaDataOther.partitionsList != null && updateMetaDataOther.partitionsList.size() != 0) { UpdateMetaData updateMetaData = updateMetaDataList.get(idx); for (Map<String, String> partSpec : updateMetaDataOther.partitionsList) { updateMetaData.addPartition(partSpec); } } } }
Source:
<code>public void addProjectToImport( final ExampleProject exampleProject ) { <START> ListItem li = (ListItem) document.createElement( "li" ); <END> Anchor link = (Anchor) document.createElement( "a" ); link.setTextContent( exampleProject.getName() ); link.setAttribute( "alt", exampleProject.getDescription() ); link.setOnclick( event -> presenter.importProject( exampleProject ) ); li.appendChild( link ); importProjectContainer.appendChild( li ); }</code><technical_language>More programmatic UI construction.. shame.. recording for future refactoring</technical_language>

Target:
public void addProjectToImport( final ExampleProject exampleProject ) { final ImportExampleListItemWidget importExampleListItem = importExampleListItemWidgets.get(); importExampleListItem.init( exampleProject.getName(), exampleProject.getDescription(), () -> presenter.importProject( exampleProject ) ); importProjectContainer.appendChild( importExampleListItem.getElement() ); }
Source:
<code>void registerIQ(IQ iq) { <START> for (IQ.Type type : new IQ.Type[]{ IQ.Type.get, IQ.Type.set }) <END> { xmppConnection.registerIQRequestHandler( new AbstractIqRequestHandler(iq.getChildElementName(), iq.getChildElementNamespace(), type, iqHandlerMode) { @Override public IQ handleIQRequest(IQ iqRequest) { if (logger.isDebugEnabled()) { logger.debug( "Received an IQ with type " + type + ": " + iqRequest.toString()); } return handleIq(iqRequest); } } ); } }</code><technical_language>defining a static array included iq types? for (IQ.Type type : ALL_IQ_TYPES) a collection type do ALL_IQ_TYPES.forEach...</technical_language>

Target:
void registerIQ(IQ iq) { for (IQ.Type type : IQ_TYPES) { xmppConnection.registerIQRequestHandler( new AbstractIqRequestHandler(iq.getChildElementName(), iq.getChildElementNamespace(), type, iqHandlerMode) { @Override public IQ handleIQRequest(IQ iqRequest) { if (logger.isDebugEnabled()) { logger.debug( "Received an IQ with type " + type + ": " + iqRequest.toString()); } return handleIq(iqRequest); } } ); } }
Source:
<code>public List<BasicDocumentRevision> leafRevisions(boolean excludeDeleted) { List<BasicDocumentRevision> res = new ArrayList<BasicDocumentRevision>(); for(DocumentRevisionNode obj : leafs()) { BasicDocumentRevision revision = obj.getData(); <START> if(excludeDeleted){ <END> if(!revision.isDeleted()){ res.add(revision); } }else { res.add(revision); } } return res; }</code><technical_language>simplify this if (!excludeDeleted || (excludeDeleted && !revision.isDeleted()))</technical_language>

Target:
public List<BasicDocumentRevision> leafRevisions(boolean excludeDeleted) { List<BasicDocumentRevision> res = new ArrayList<BasicDocumentRevision>(); for(DocumentRevisionNode obj : leafs()) { BasicDocumentRevision revision = obj.getData(); if (!excludeDeleted || (excludeDeleted && !revision.isDeleted())){ res.add(revision); } } return res; }
Source:
<code>public void testInitialNamedDeployments() { final String urlSubPathToWebApp = APP_NAME; final String urlSubPathToPageToQuery = ""; log.info("test=initialNamedWarDeployments; entity="+entity+"; app="+entity.getApplication()); Entities.start(entity.getApplication(), ImmutableList.of(loc)); Asserts.succeedsEventually(MutableMap.of("timeout", 60*1000), new Runnable() { public void run() { <START> HttpTestUtils.assertHttpStatusCodeEquals(Urls.mergePaths(entity.getAttribute(WebAppService.ROOT_URL), urlSubPathToWebApp, urlSubPathToPageToQuery), 200); <END> }}); }</code><technical_language>nitpick: construct URL in a separate statement for clarity</technical_language>

Target:
public void testInitialNamedDeployments() { final String urlSubPathToWebApp = APP_NAME; final String urlSubPathToPageToQuery = ""; LOG.info("test=testInitialNamedDeployments; entity="+entity+"; app="+entity.getApplication()); Entities.start(entity.getApplication(), ImmutableList.of(loc)); Asserts.succeedsEventually(MutableMap.of("timeout", 60*1000), new Runnable() { public void run() { String url = Urls.mergePaths(entity.getAttribute(WebAppService.ROOT_URL), urlSubPathToWebApp, urlSubPathToPageToQuery); HttpTestUtils.assertHttpStatusCodeEquals(url, 200); }}); }
Source:
<code>public EnumeratedProperty(String theName, String theDescription, Map<String, E> labelsToChoices, E defaultValue, Class<E> valueType, float theUIOrder) { super(theName, theDescription, defaultValue, theUIOrder); <START> this.valueType = valueType; <END> choicesByLabel = Collections.unmodifiableMap(labelsToChoices); labelsByChoice = Collections.unmodifiableMap(CollectionUtil.invertedMapFrom(choicesByLabel)); }</code><technical_language>derive Class<E> of label choices, if is provided? immutable, a real-world case for empty enumerations eludes me</technical_language>

Target:
public EnumeratedProperty(String theName, String theDescription, Map<String, E> labelsToChoices, E defaultValue, Class<E> valueType, float theUIOrder) { this(theName, theDescription, labelsToChoices, defaultValue, valueType, theUIOrder, false); }
Source:
<code>protected void stop() { if (!isEnabled()) return; long duration = System.nanoTime() - start; requests.update(duration, TimeUnit.NANOSECONDS); if (uri != null) { timer("requests", "uri", uri).update(duration, TimeUnit.NANOSECONDS); } <START> if (method != null) { <END> timer(method + "-requests").update(duration, TimeUnit.NANOSECONDS); if (uri != null) { timer(method + "-requests", uri).update(duration, TimeUnit.NANOSECONDS); } } }</code><technical_language>method is null this is dead code</technical_language>

Target:
protected void stop() { if (!isEnabled()) return; long duration = System.nanoTime() - start; requests.update(duration, TimeUnit.NANOSECONDS); if (method != null) { timer(method + "-requests").update(duration, TimeUnit.NANOSECONDS); if (uri != null) { timer(method + "-requests", uri).update(duration, TimeUnit.NANOSECONDS); } } else if (uri != null) { timer("requests", uri).update(duration, TimeUnit.NANOSECONDS); } }
Source:
<code>public List<String> list(final String directory, final String prefix) { try { final List<String> objects = new ArrayList<String>(); final ObjectListing objectListing = amazonS3Client.listObjects(bucketNameForDirectory(directory), prefix); final List<S3ObjectSummary> s3objectSummaries = objectListing.getObjectSummaries(); for (final S3ObjectSummary s3ObjectSummary : s3objectSummaries) { objects.add(s3ObjectSummary.getKey()); } return objects; } catch (final AmazonS3Exception e) { if (missingItemErrorCodes.contains(e.getErrorCode())) { <START> throw new NonExistentItemException("No items found in directory -> " + directory <END> + " with the specified prefix -> " + prefix); } throw e; } }</code><technical_language>return empty collection throw exception</technical_language>

Target:
public List<FilePath> list(final String directory, final String prefix) { try { final List<FilePath> filePathList = new ArrayList<FilePath>(); final ObjectListing objectListing = amazonS3Client.listObjects(bucketNameForDirectory(directory), prefix); final List<S3ObjectSummary> s3objectSummaries = objectListing.getObjectSummaries(); for (final S3ObjectSummary s3ObjectSummary : s3objectSummaries) { final FilePath filePath = new FilePath(directory, s3ObjectSummary.getKey()); filePathList.add(filePath); } return filePathList; } catch (final AmazonS3Exception e) { throw new PersistenceResourceFailureException("An error occurred obtaining a listing of directory -> " + directory + " with prefix -> " + prefix, e); } }
Source:
<code><START> public void waitHttp() { <END> String server = String.format("http://localhost:%s", serverPort); httpServer.setPort(serverPort); start(httpServer); parallel().actions( sequential().actions( waitFor() .http() .url(server) ), sequential().actions( http().server(httpServer).receive().head(), http().server(httpServer).respond(HttpStatus.NOT_FOUND), http().server(httpServer).receive().head(), http().server(httpServer).respond(HttpStatus.OK) ) ); doFinally().actions(stop(httpServer)); }</code><technical_language>is a lot of duplication this test "waitHttpDeprecated". common code factored out test pass waitFor action</technical_language>

Target:
public void waitHttp() { String server = startHttpServerAndGetUrl(); parallel().actions( sequential().actions( waitFor() .http() .url(server) ), sequential().actions( http().server(httpServer).receive().head(), http().server(httpServer).respond(HttpStatus.NOT_FOUND), http().server(httpServer).receive().head(), http().server(httpServer).respond(HttpStatus.OK) ) ); doFinally().actions(stop(httpServer)); }
Source:
<code>public Network() { vmNetwork = true; description = ""; <START> comment = ""; <END> }</code><technical_language>set name empty string here</technical_language>

Target:
public Network() { vmNetwork = true; name = ""; description = ""; comment = ""; }
Source:
<code>public void setEnvironment(Cache<Object, Object> cache, Set<Object> inputKeys) { ComponentRegistry cr = cache.getAdvancedCache().getComponentRegistry(); PersistenceManager loaderManager = cr.getComponent(PersistenceManager.class); this.stores = loaderManager.getStores(RemoteStore.class); Marshaller marshaller = new MigrationMarshaller(); this.cache = cache; this.cache.addListener(listener); <START> this.executorService = Executors.newFixedThreadPool(threads); <END> try { this.ignoredKey = marshaller.objectToByteBuffer(MIGRATION_MANAGER_HOT_ROD_KNOWN_KEYS); } catch (Exception e) { throw new CacheException(e); } }</code><technical_language>name threads</technical_language>

Target:
public void setEnvironment(Cache<Object, Object> cache, Set<Object> inputKeys) { ComponentRegistry cr = cache.getAdvancedCache().getComponentRegistry(); PersistenceManager loaderManager = cr.getComponent(PersistenceManager.class); this.stores = loaderManager.getStores(RemoteStore.class); Marshaller marshaller = new MigrationMarshaller(); this.cache = cache; this.cache.addFilteredListener(listener, new RemovedFilter<>(), null, Util.asSet(CacheEntryRemoved.class)); DefaultThreadFactory threadFactory = new DefaultThreadFactory(null, 1, THREAD_NAME + "-%t", null, null); this.executorService = Executors.newFixedThreadPool(threads, threadFactory); try { this.ignoredKey = marshaller.objectToByteBuffer(MIGRATION_MANAGER_HOT_ROD_KNOWN_KEYS); } catch (Exception e) { throw new CacheException(e); } }
Source:
<code>public void testExpectedRowsMismatch() throws Exception { XMLConfigParser mockParser = Mockito.mock(XMLConfigParser.class); DataModelResult mockDMR = Mockito.mock(DataModelResult.class); <START> RulesApplier mockRA = Mockito.mock(RulesApplier.class); <END> ThreadTime mockTT = Mockito.mock(ThreadTime.class); Scenario mockScenario = Mockito.mock(Scenario.class); WorkloadExecutor mockWE = Mockito.mock(WorkloadExecutor.class); Query mockQuery = Mockito.mock(Query.class); Mockito.when(mockQuery.getExpectedAggregateRowCount()).thenReturn(1L); MultiThreadedRunner mtr = new MultiThreadedRunner("test", mockQuery, mockDMR, mockTT, 10L, 1000L, true, mockRA, mockScenario, mockWE, mockParser); ResultSet mockRS = Mockito.mock(ResultSet.class); Mockito.when(mockRS.next()).thenReturn(true); Mockito.when(mockRS.getLong(1)).thenReturn(2L); try { mtr.getResults(mockRS, "test_iteration", false); fail(); } catch (RuntimeException e) { } }</code><technical_language>common mocked objects initialized in a BeforeClass method re-used in test, avoid code repetition</technical_language>

Target:
public void testExpectedRowsMismatch() throws Exception { Mockito.when(mockQuery.getExpectedAggregateRowCount()).thenReturn(1L); MultiThreadedRunner mtr = new MultiThreadedRunner("test", mockQuery, mockDMR, mockTT, 10L, 1000L, true, mockRA, mockScenario, mockWE, mockParser); Mockito.when(mockRS.next()).thenReturn(true); Mockito.when(mockRS.getLong(1)).thenReturn(2L); try { mtr.getResults(mockRS, "test_iteration", false,0L); fail(); } catch (RuntimeException e) { } }
Source:
<code>public static Expression rewrite(Expression expression, Session session, Metadata metadata, SqlParser sqlParser, SymbolAllocator symbolAllocator) { requireNonNull(metadata, "metadata is null"); requireNonNull(sqlParser, "sqlParser is null"); <START> checkState(!(expression instanceof GroupingOperation), "GroupingOperation should have been re-written to a FunctionCall before execution"); <END> if (expression instanceof SymbolReference) { return expression; } Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes(session, metadata, sqlParser, symbolAllocator.getTypes(), expression, emptyList()); return rewrite(expression, expressionTypes); }</code><technical_language>a checkArgument</technical_language>

Target:
public static Expression rewrite(Expression expression, Session session, Metadata metadata, SqlParser sqlParser, SymbolAllocator symbolAllocator) { requireNonNull(metadata, "metadata is null"); requireNonNull(sqlParser, "sqlParser is null"); if (expression instanceof SymbolReference) { return expression; } Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes(session, metadata, sqlParser, symbolAllocator.getTypes(), expression, emptyList()); return rewrite(expression, expressionTypes); }
Source:
<code>public VariableDeclarationExpr(final Type type, VariableDeclarator var) { setType(type); List<VariableDeclarator> vars = new ArrayList<>(); vars.add(var); <START> setVars(vars); <END> }</code><technical_language>Arrays.asList(var) ? asList(var) Arrays.asList in a static import</technical_language>

Target:
public VariableDeclarationExpr(final Type type, VariableDeclarator var) { setType(type); setVars(Arrays.asList(var)); }
Source:
<code>public UserDataSource(HttpMessage sourceMsg, String param) { super(); String genericUri = createGenericUri(sourceMsg.getRequestHeader().getURI(), param); this.uri = getCachedItem(cachedUris, genericUri); <START> boolean requestUriIsGeneric = sourceMsg.getRequestHeader().getURI().equals(genericUri); if (!requestUriIsGeneric) { <END> this.param = GENERIC_STRING; } else { this.param = getCachedItem(cachedParams, param); } this.stringRepresentation = this.uri + "#" + this.param; }</code><technical_language>Name is giving wrong indication if equal is generic flag isGeneric true. a ! of in 170 line more correct</technical_language>

Target:
public UserDataSource(HttpMessage sourceMsg, String param) { super(); URI originalRequestUri = sourceMsg.getRequestHeader().getURI(); String genericUri = createGenericUri(originalRequestUri, param); this.uri = getCachedItem(cachedUris, genericUri); boolean paramWasReplacedInUri = !originalRequestUri.toString().equals(genericUri); if (paramWasReplacedInUri) { this.param = GENERIC_STRING; } else { this.param = getCachedItem(cachedParams, param); } this.stringRepresentation = this.uri + "#" + this.param; }
Source:
<code>public HashPartitionFunction(final int[] indexes, final int seedIndex) { <START> Preconditions.checkArgument( <END> indexes.length > 0, "HashPartitionFunction requires at least 1 field to hash"); for (int i = 0; i < indexes.length; ++i) { Preconditions.checkArgument( indexes[i] >= 0, "HashPartitionFunction field index %s cannot take negative value %s", i, indexes[i]); } this.indexes = indexes; this.seedIndex = seedIndex % HashUtils.NUM_OF_HASHFUNCTIONS; }</code><technical_language>While it, check uniqueness of indices (I guess MyriaArrayUtils.checkSet())? I if indexes strictly increasing, want e.g. join relations attributes appeared in orders in respective relations</technical_language>

Target:
public HashPartitionFunction(final int[] indexes, final int seedIndex) { Preconditions.checkArgument( indexes.length > 0, "HashPartitionFunction requires at least 1 field to hash"); for (int i = 0; i < indexes.length; ++i) { Preconditions.checkArgument( indexes[i] >= 0, "HashPartitionFunction field index %s cannot take negative value %s", i, indexes[i]); } MyriaArrayUtils.checkSet(indexes); this.indexes = indexes; this.seedIndex = seedIndex % HashUtils.NUM_OF_HASHFUNCTIONS; }
Source:
<code>public int getStateTableIndex(ITimeEvent event) { State state = getEventState(event); if (state != null) { return state.ordinal(); } if (event instanceof TimeEvent) { return INVISIBLE; <START> } <END> return TRANSPARENT; }</code><technical_language>TimeEvent instances in current implementation TRANSPARENT returned (it for filler 'multiple' events)</technical_language>

Target:
public int getStateTableIndex(ITimeEvent event) { State state = getEventState(event); if (state != null) { return state.ordinal(); } if (event instanceof TimeEvent) { TimeEvent tcEvent = (TimeEvent) event; if (tcEvent.hasValue()) { return INVISIBLE; } } return TRANSPARENT; }
Source:
<code>public void checkpoint() throws TransactionFailureException { Preconditions.checkState(currentTx != null, "Cannot checkpoint tx that has not been started"); persist(); try { currentTx = txClient.checkpoint(currentTx); for (TransactionAware txAware : txAwares) { <START> txAware.startTx(currentTx); <END> } } catch (TransactionNotInProgressException e) { String message = String.format("Transaction %d is not in progress.", currentTx.getWritePointer()); LOG.warn(message, e); abort(new TransactionFailureException(message, e)); } catch (Throwable e) { String message = String.format("Exception from checkpoint for transaction %d.", currentTx.getWritePointer()); LOG.warn(message, e); abort(new TransactionFailureException(message, e)); } }</code><technical_language>sense get change set tx-awares here? If do that, tx-awares need part of a check-pointed transaction not</technical_language>

Target:
public void checkpoint() throws TransactionFailureException { Preconditions.checkState(currentTx != null, "Cannot checkpoint tx that has not been started"); persist(); try { currentTx = txClient.checkpoint(currentTx); for (TransactionAware txAware : txAwares) { txAware.updateTx(currentTx); } } catch (TransactionNotInProgressException e) { String message = String.format("Transaction %d is not in progress.", currentTx.getTransactionId()); LOG.warn(message, e); abort(new TransactionFailureException(message, e)); } catch (Throwable e) { String message = String.format("Exception from checkpoint for transaction %d.", currentTx.getTransactionId()); LOG.warn(message, e); abort(new TransactionFailureException(message, e)); } }
Source:
<code>private static Point getPolygonSansHolesCentroid(Polygon polygon) { final int pointCount = polygon.getPointCount(); double xSum = 0; double ySum = 0; double signedArea = 0; for (int i = 0; i < pointCount; i++) { Point current = polygon.getPoint(i); <START> Point next = (i + 1 == polygon.getPointCount()) ? polygon.getPoint(0) : polygon.getPoint(i + 1); <END> double ladder = current.getX() * next.getY() - next.getX() * current.getY(); xSum += (current.getX() + next.getX()) * ladder; ySum += (current.getY() + next.getY()) * ladder; signedArea += ladder; } return new Point(xSum / (signedArea * 3), ySum / (signedArea * 3)); }</code><technical_language>index (i + 1) % polygon.getPointCount()</technical_language>

Target:
private static Point getPolygonSansHolesCentroid(Polygon polygon) { int pointCount = polygon.getPointCount(); double xSum = 0; double ySum = 0; double signedArea = 0; for (int i = 0; i < pointCount; i++) { Point current = polygon.getPoint(i); Point next = polygon.getPoint((i + 1) % polygon.getPointCount()); double ladder = current.getX() * next.getY() - next.getX() * current.getY(); xSum += (current.getX() + next.getX()) * ladder; ySum += (current.getY() + next.getY()) * ladder; signedArea += ladder / 2; } return new Point(xSum / (signedArea * 6), ySum / (signedArea * 6)); }
Source:
<code>public void testHasChangeidWithReplacement() throws Exception { assertEquals( <START> "has changeid\n\nBug: 33\nmore text\nSigned-off-by: me@you.too\n\nChange-Id: Ibd4de0fdf30dd670b53d123ec1f7036a97fd2687\n", <END> call("has changeid\n\nBug: 33\nmore text\nSigned-off-by: me@you.too\n\nChange-Id: I0123456789012345678901234567890123456789\n", true)); }</code><technical_language>this test need change</technical_language>

Target:
public void testHasChangeidWithReplacement() throws Exception { assertEquals( "has changeid\nmore text\n\nSigned-off-by: me@you.too\n" + "Change-Id: I2178563fada5edb2c99a8d8c0d619471b050ec24\nBug: 33\n", call("has changeid\nmore text\n\nSigned-off-by: me@you.too\n" + "Change-Id: I0123456789012345678901234567890123456789\nBug: 33\n", true)); }
Source:
<code>protected void executeQueryCommand() { GlusterVolumeEntity volumeCheck = glusterVolumeDao.getByName(getParameters().getClusterId(), getGlusterVolumeName(getParameters().getVolumeId())); <START> boolean nfs = volumeCheck.isNfsEnabled(); <END> VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetGlusterVolumeProfileInfo, new GlusterVolumeProfileInfoVDSParameters(getParameters().getClusterId(), getUpServerId(getParameters().getClusterId()), getGlusterVolumeName(getParameters().getVolumeId()), nfs)); GlusterVolumeProfileInfo profileInfo = (GlusterVolumeProfileInfo) returnValue.getReturnValue(); if (nfs) { populateBrickNames(profileInfo); } getQueryReturnValue().setReturnValue(profileInfo); }</code><technical_language>this variable based if volume nfsEnabled, if nfs profile is requested. boolean nfs = volumeCheck.isNfsEnabled() && getParameters().isNfs();</technical_language>

Target:
protected void executeQueryCommand() { GlusterVolumeEntity volumeCheck = glusterVolumeDao.getByName(getParameters().getClusterId(), getGlusterVolumeName(getParameters().getVolumeId())); boolean nfs = volumeCheck.isNfsEnabled() && getParameters().isNfs(); VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetGlusterVolumeProfileInfo, new GlusterVolumeProfileInfoVDSParameters(getParameters().getClusterId(), getUpServerId(getParameters().getClusterId()), getGlusterVolumeName(getParameters().getVolumeId()), nfs)); GlusterVolumeProfileInfo profileInfo = (GlusterVolumeProfileInfo) returnValue.getReturnValue(); if (!nfs) { populateBrickNames(profileInfo); } getQueryReturnValue().setReturnValue(profileInfo); }