auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.delete_video_dialog, container, false); TextView title_tv = (TextView) v.findViewById(R.id.tv_dialog_title); title_tv.setVisibility(View.GONE); TextView dialog_tv_1 = (TextView) v .findViewById(R.id.tv_dialog_message1); dialog_tv_1.setText(getArguments().getString("dialog_msg_1")); Button positiveBtn = (Button) v.findViewById(R.id.positiveButton); <START> positiveBtn.setText(getArguments().getString("dialog_yes_btn").toUpperCase()); <END> positiveBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { if (callback != null && isVisible()) { callback.onPositiveClicked(); dismiss(); } } catch (Exception e) { logger.error(e); } } }); Button negativebtn = (Button) v.findViewById(R.id.negativeButton); negativebtn.setText(getArguments().getString("dialog_no_btn").toUpperCase()); negativebtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (callback != null && isVisible()) { callback.onNegativeClicked(); dismiss(); } } }); return v; }</code><technical_language>Instead, <code>android:textAllCaps</code> property for <code>TextView</code> in XML. This is good, if this dialog class is supposed show some other contents buttons do text in Caps</technical_language>

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.delete_video_dialog, container, false); TextView title_tv = (TextView) v.findViewById(R.id.tv_dialog_title); title_tv.setVisibility(View.GONE); TextView dialog_tv_1 = (TextView) v .findViewById(R.id.tv_dialog_message1); dialog_tv_1.setText(getArguments().getString("dialog_msg_1")); Button positiveBtn = (Button) v.findViewById(R.id.positiveButton); positiveBtn.setText(getArguments().getString("dialog_yes_btn")); positiveBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { if (callback != null && isVisible()) { callback.onPositiveClicked(); dismiss(); } } catch (Exception e) { logger.error(e); } } }); Button negativebtn = (Button) v.findViewById(R.id.negativeButton); negativebtn.setText(getArguments().getString("dialog_no_btn").toUpperCase()); negativebtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (callback != null && isVisible()) { callback.onNegativeClicked(); dismiss(); } } }); return v; }
Source:
<code>private void disconnectStorageByType(StorageType storageType, List<StorageServerConnections> connections) { Optional<StorageDomain> heDomain = <START> storageDomainDao.getAllForStoragePool(getStoragePool().getId()) .stream() .filter(StorageDomain::isHostedEngineStorage) <END> .findAny(); if (heDomain.isPresent()) { String heID = heDomain.get().getStorageStaticData().getStorage(); connections = connections.stream().filter(c -> !c.getId().equals(heID)).collect(Collectors.toList()); } storageHelperDirector.getItem(storageType).prepareDisconnectHostFromStoragePoolServers(getParameters(), connections); VDSReturnValue vdsReturnValue = runVdsCommand( VDSCommandType.DisconnectStorageServer, new StorageServerConnectionManagementVDSParameters(getVds().getId(), getStoragePool().getId(), storageType, connections)); setSucceeded(vdsReturnValue.getSucceeded()); if (!vdsReturnValue.getSucceeded()) { storageHelperDirector.getItem(storageType) .isConnectSucceeded((HashMap<String, String>) vdsReturnValue.getReturnValue(), connections); } }</code><technical_language>easier StorageDomainDao#getHostedEngineStorageDomainIds()</technical_language>

Target:
private void disconnectStorageByType(StorageType storageType, List<StorageServerConnections> connections) { List<String> heIds = storageDomainDao.getHostedEngineStorageDomainIds().stream() .map(storageDomainDao::get) .map(StorageDomain::getStorageStaticData) .map(StorageDomainStatic::getStorage) .collect(Collectors.toList()); connections = connections.stream() .filter(c -> heIds.stream().noneMatch(heId -> c.getId().equals(heId))) .collect(Collectors.toList()); storageHelperDirector.getItem(storageType).prepareDisconnectHostFromStoragePoolServers(getParameters(), connections); VDSReturnValue vdsReturnValue = runVdsCommand( VDSCommandType.DisconnectStorageServer, new StorageServerConnectionManagementVDSParameters(getVds().getId(), getStoragePool().getId(), storageType, connections)); setSucceeded(vdsReturnValue.getSucceeded()); if (!vdsReturnValue.getSucceeded()) { storageHelperDirector.getItem(storageType) .isConnectSucceeded((HashMap<String, String>) vdsReturnValue.getReturnValue(), connections); } }
Source:
<code>public void verifyVideoWidth(int widthDesired) { String content = getContent(); int width = Integer.parseInt( <START> content.substring(content.indexOf("px") - 4, content.indexOf("px") - 1) <END> ); Assertion.assertNumber( widthDesired, width, "width is " + width + " should be " + widthDesired ); }</code><technical_language>I of scope of this pull request, number of magic numbers :disappointed:</technical_language>

Target:
public void verifyVideoWidth(int widthDesired) { String content = getContent(); int width = Integer.parseInt( content.substring(content.indexOf("px") - 4, content.indexOf("px") - 1) ); Assertion.assertNumber( widthDesired, width, "Video width in source edit mode is " + width + " while desired width is " + widthDesired ); }
Source:
<code><START> public <K, V> ConcurrentMap<K, V> getPersistentConcurrentMap(String name) { <END> return new ConcurrentHashMap<K, V>(); }</code><technical_language>get saved in a data structure repeated calls name return map</technical_language>

Target:
public <K extends Serializable, V extends Serializable> ConcurrentMap<K, V> getPersistentConcurrentMap(String name) { ConcurrentMap concurrentMap = knownMaps.get(name); if (concurrentMap != null) { return concurrentMap; } else { ConcurrentHashMap<K, V> newMap = new ConcurrentHashMap<K, V>(); concurrentMap = knownMaps.putIfAbsent(name, newMap); if (concurrentMap == null) { return newMap; } else { return concurrentMap; } } }
Source:
<code>public AuthCache(Protocol.ExpiringAction action) { this.cachedAction = action; try { if (action.expiresIn != null && !action.expiresIn.isEmpty()) { this.validUntil = System.currentTimeMillis() + Long.parseLong(action.expiresIn); } else if (action.expiresAt != null && !action.expiresAt.isEmpty()) { this.validUntil = ISO_FORMAT.parse(action.expiresAt) .getTime() - AUTH_CACHE_EAGER_TIMEOUT; } else { this.validUntil = System.currentTimeMillis() + <START> 1000; <END> } } catch (Exception e) { this.validUntil = System.currentTimeMillis() + 1000; } }</code><technical_language>This a constant. Do need configure this</technical_language>

Target:
public AuthCache(Protocol.ExpiringAction action) { this.cachedAction = action; try { if (action.expiresIn != null && !action.expiresIn.isEmpty()) { this.validUntil = System.currentTimeMillis() + Long.parseLong(action.expiresIn); } else if (action.expiresAt != null && !action.expiresAt.isEmpty()) { this.validUntil = ISO_FORMAT.parse(action.expiresAt) .getTime() - AUTH_CACHE_EAGER_TIMEOUT; } else { this.validUntil = System.currentTimeMillis(); } } catch (Exception e) { this.validUntil = System.currentTimeMillis(); } }
Source:
<code>public Object getAnyExample(String nodeKey,ObjectNode node, String location, ParseResult result ){ JsonNode example = node.get(nodeKey); if (example != null) { if (example.getNodeType().equals(JsonNodeType.STRING)) { String value = getString(nodeKey, node, false, location, result); if (StringUtils.isNotBlank(value)) { return value; } } if (example.getNodeType().equals(JsonNodeType.NUMBER)) { Integer integerExample = getInteger(nodeKey, node, false, location, result); <START> JsonNode format = node.get("format"); <END> if (integerExample != null && !(format != null && format.asText().equals("int64"))) { return integerExample; }else { BigDecimal bigDecimalExample = getBigDecimal(nodeKey, node, false, location, result); if (bigDecimalExample != null) { return bigDecimalExample; } } } else if (example.getNodeType().equals(JsonNodeType.OBJECT)) { ObjectNode objectValue = getObject(nodeKey, node, false, location, result); if (objectValue != null) { return objectValue; } } else if (example.getNodeType().equals(JsonNodeType.ARRAY)) { ArrayNode arrayValue = getArray(nodeKey, node, false, location, result); if (arrayValue != null) { return arrayValue; } } } return null; }</code><technical_language>Thanks!! @joeljons, I push some changes I permissions repo, is I validated: In method getInteger() line: 1196 : I added a boolean validation number is integer, return null if false integers validated public Integer getInteger(String key, ObjectNode node, boolean required, String location, ParseResult result) { Integer = null; JsonNode v = node.get(key); if (node == null || v == null) { if (required) { result.missing(location, key); result.invalid(); } } else if(v.getNodeType().equals(JsonNodeType.NUMBER)) { if (v.isInt()) { = v.intValue(); } } else if(!v.isValueNode()) { result.invalidType(location, key, "integer", node); } return value; }</technical_language>

Target:
public Object getAnyExample(String nodeKey,ObjectNode node, String location, ParseResult result ){ JsonNode example = node.get(nodeKey); if (example != null) { if (example.getNodeType().equals(JsonNodeType.STRING)) { String value = getString(nodeKey, node, false, location, result); if (StringUtils.isNotBlank(value)) { return value; } } if (example.getNodeType().equals(JsonNodeType.NUMBER)) { Integer integerExample = getInteger(nodeKey, node, false, location, result); if (integerExample != null) { return integerExample; }else { BigDecimal bigDecimalExample = getBigDecimal(nodeKey, node, false, location, result); if (bigDecimalExample != null) { return bigDecimalExample; } } } else if (example.getNodeType().equals(JsonNodeType.OBJECT)) { ObjectNode objectValue = getObject(nodeKey, node, false, location, result); if (objectValue != null) { return objectValue; } } else if (example.getNodeType().equals(JsonNodeType.ARRAY)) { ArrayNode arrayValue = getArray(nodeKey, node, false, location, result); if (arrayValue != null) { return arrayValue; } } } return null; }
Source:
<code>public FieldBridge provideFieldBridge(ExtendedBridgeProviderContext context) { AnnotatedElement annotatedElement = context.getAnnotatedElement(); if ( Date.class.isAssignableFrom( context.getReturnType() ) ) { <START> if ( annotatedElement.isAnnotationPresent( org.hibernate.search.annotations.DateBridge.class ) ) { <END> DateBridge dateBridgeAnnotation = annotatedElement.getAnnotation( org.hibernate.search.annotations.DateBridge.class ); return getDateFieldBridge( dateBridgeAnnotation.resolution() ); } else { return getDateFieldBridge( Resolution.MILLISECOND ); } } else if ( Calendar.class.isAssignableFrom( context.getReturnType() ) ) { if ( annotatedElement.isAnnotationPresent( org.hibernate.search.annotations.DateBridge.class ) ) { DateBridge dateBridgeAnnotation = annotatedElement.getAnnotation( org.hibernate.search.annotations.DateBridge.class ); return getCalendarFieldBridge( dateBridgeAnnotation.resolution() ); } else { return getCalendarFieldBridge( Resolution.MILLISECOND ); } } return null; }</code><technical_language>Is strong need for FQN</technical_language>

Target:
public FieldBridge provideFieldBridge(ExtendedBridgeProviderContext context) { AnnotatedElement annotatedElement = context.getAnnotatedElement(); if ( Date.class.isAssignableFrom( context.getReturnType() ) ) { if ( annotatedElement.isAnnotationPresent( DateBridge.class ) ) { DateBridge dateBridgeAnnotation = annotatedElement.getAnnotation( DateBridge.class ); return getDateFieldBridge( dateBridgeAnnotation.resolution() ); } else { return getDateFieldBridge( Resolution.MILLISECOND ); } } else if ( Calendar.class.isAssignableFrom( context.getReturnType() ) ) { if ( annotatedElement.isAnnotationPresent( DateBridge.class ) ) { DateBridge dateBridgeAnnotation = annotatedElement.getAnnotation( DateBridge.class ); return getCalendarFieldBridge( dateBridgeAnnotation.resolution() ); } else { return getCalendarFieldBridge( Resolution.MILLISECOND ); } } return null; }
Source:
<code>public boolean shouldUpload(JAXBElement<TVAMainType> tvaElem) { BroadcastEventType broadcastEvent = extractBroadcastEvent(tvaElem); Optional<String> broadcastPcrid = getPcrid(broadcastEvent); String crid = broadcastEvent.getProgram().getCrid(); String broadcastImi = broadcastEvent.getInstanceMetadataId(); if (!broadcastPcrid.isPresent()) { return true; } <START> if(broadcastImi.equals(sentBroadcastProgramUrlStore.getSentBroadcastEventImi(crid, broadcastPcrid.get()).get())){ <END> if(sentBroadcastProgramUrlStore. getSentBroadcastEventTransmissionDate(crid, broadcastPcrid.get()).get().isBefore(LocalDate.now().minusDays(51))) { return true; } } return false; }</code><technical_language>need do 2 database queries here. store do query returns a object crid date</technical_language>

Target:
public boolean shouldUpload(JAXBElement<TVAMainType> tvaElem) { BroadcastEventType broadcastEvent = extractBroadcastEvent(tvaElem); Optional<String> broadcastPcrid = getPcrid(broadcastEvent); String crid = broadcastEvent.getProgram().getCrid(); String broadcastImi = broadcastEvent.getInstanceMetadataId(); Optional<BroadcastEventRecord> broadcastEventRecords = sentBroadcastProgramUrlStore .getSentBroadcastEventRecords(crid, broadcastPcrid.get()); if(!broadcastEventRecords.isPresent()) { return true; } if(!broadcastPcrid.isPresent()) { return true; } if(broadcastImi.equals(broadcastEventRecords.get().getBroadcastEventImi())) { return true; } if(broadcastEventRecords.get() .getBroadcastTransmissionDate() .isBefore(LocalDate.now().minusDays(DAYS_BROADCAST_LAST_SENT))) { return true; } LOGGER.trace("Broadcast is not uploaded, since it has been last sent for less than " + DAYS_BROADCAST_LAST_SENT + " days or its ProgramURL has already been associated with this service ID and item"); return false; }
Source:
<code>public List<String> getBrokers() { List<String> brokerList = new ArrayList<>(); for (JsonNode broker : _brokers) { <START> String[] brokerPath = broker.textValue().split("_"); <END> if(brokerPath.length < 3){ throw new RuntimeException("Invalid Broker Name found in controller: " + broker.textValue()); } String brokerHostPort = String.format("%s:%s", brokerPath[1], brokerPath[2]); brokerList.add(brokerHostPort); } return brokerList; }</code><technical_language>get host name port instance config instead of broker name</technical_language>

Target:
public List<String> getBrokers() { List<String> brokerList = new ArrayList<>(); for (JsonNode broker : _brokers) { String hostName = broker.get("host").textValue(); Integer port = broker.get("port").intValue(); String brokerIP = hostName; if(hostName.contains("_")) { String[] hostNamePart = hostName.split("_"); brokerIP = hostNamePart[hostNamePart.length - 1]; } String brokerIPPort = String.format("%s:%d", brokerIP, port); brokerList.add(brokerIPPort); } return brokerList; }
Source:
<code>private Notification createFrom(Talk talk) { NotificationCompat.Builder notificationBuilder = createDefaultBuilder(1); notificationBuilder .setContentIntent(createPendingIntentForSingleSession(talk.getId())) .setContentTitle(talk.getName()) <START> .setContentText(talk.getRooms().get(0).getName()) <END> .setGroup(GROUP_KEY_NOTIFY_SESSION); NotificationCompat.BigTextStyle richNotification = createBigTextRichNotification(notificationBuilder, talk); return richNotification.build(); }</code><technical_language>join a comma</technical_language>

Target:
private Notification createFrom(Talk talk) { NotificationCompat.Builder notificationBuilder = createDefaultBuilder(1); notificationBuilder .setContentIntent(createPendingIntentForSingleSession(talk.getId())) .setContentTitle(talk.getName()) .setContentText(getRoomName(talk)) .setGroup(GROUP_KEY_NOTIFY_SESSION); NotificationCompat.BigTextStyle richNotification = createBigTextRichNotification(notificationBuilder, talk); return richNotification.build(); }
Source:
<code>public SaslClient createSaslClient(final String[] mechanisms, final String authorizationId, final String protocol, final String serverName, Map<String, ?> props, final CallbackHandler cbh) throws SaslException { Assert.checkNotNullParam("cbh", cbh); if (props == null) props = Collections.emptyMap(); <START> if (PlainSasl.isMatched(props, true)) for (String mechanism : mechanisms) { <END> if (SaslMechanismInformation.Names.PLAIN.equals(mechanism)) { return new PlainSaslClient(authorizationId, cbh); } } return null; }</code><technical_language>true/false for query conversely in other factories - false for create true for getMechanismNames</technical_language>

Target:
public SaslClient createSaslClient(final String[] mechanisms, final String authorizationId, final String protocol, final String serverName, Map<String, ?> props, final CallbackHandler cbh) throws SaslException { Assert.checkNotNullParam("cbh", cbh); if (props == null) props = Collections.emptyMap(); if (PlainSasl.isMatched(props, false)) for (String mechanism : mechanisms) { if (SaslMechanismInformation.Names.PLAIN.equals(mechanism)) { return new PlainSaslClient(authorizationId, cbh); } } return null; }
Source:
<code>public IosRSAPublicKey(byte[] encoded) { try { iosSecKey = createPublicSecKeyRef (encoded); } catch (Exception e) { throw new ProviderException(e); <START> } <END> }</code><technical_language>Please fix indention. Google's style guide requires spaces-only (no tabs), two-space normal indent, four-space line continuation indent, 100 columns max</technical_language>

Target:
public IosRSAPublicKey(byte[] encoded) { try { iosSecKey = createPublicSecKeyRef (encoded); } catch (Exception exp) { throw new ProviderException(exp); } }
Source:
<code>public static void main(String[] args) { if (args.length != 4) { System.out.println("usage: FunctionalTest <ENDPOINT> <ACCESSKEY> <SECRETKEY> <REGION>"); System.exit(-1); } <START> if (System.getenv("MINIO_MINT") != null) { <END> mintEnv = true; String dataDir = System.getenv("DATA_DIR"); dataFile1Mb = Paths.get(dataDir + "/datafile-1-MB"); dataFile65Mb = Paths.get(dataDir + "/datafile-65-MB"); } endpoint = args[0]; accessKey = args[1]; secretKey = args[2]; region = args[3]; try { client = new MinioClient(endpoint, accessKey, secretKey); FunctionalTest.runTests(); client = new MinioClient(endpoint, accessKey, secretKey, region); FunctionalTest.runFastTests(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } }</code><technical_language>is variable MINIO_MINT in Mint env . I DATA_DIR here</technical_language>

Target:
public static void main(String[] args) { if (args.length != 4) { System.out.println("usage: FunctionalTest <ENDPOINT> <ACCESSKEY> <SECRETKEY> <REGION>"); System.exit(-1); } String dataDir = System.getenv("MINT_DATA_DIR"); if (dataDir != null && !dataDir.equals("")) { mintEnv = true; dataFile1Mb = Paths.get(dataDir, "datafile-1-MB"); dataFile65Mb = Paths.get(dataDir, "datafile-65-MB"); } endpoint = args[0]; accessKey = args[1]; secretKey = args[2]; region = args[3]; try { client = new MinioClient(endpoint, accessKey, secretKey); FunctionalTest.runTests(); client = new MinioClient(endpoint, accessKey, secretKey, region); FunctionalTest.runFastTests(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } }
Source:
<code>protected void addAbnormalMaOntology(){ String sqlQuery="SELECT pp.id as id, ot.name as name, stable_id, ontology_acc FROM phenotype_parameter pp " + " INNER JOIN phenotype_parameter_lnk_ontology_annotation pploa ON pp.id = pploa.parameter_id " + " INNER JOIN phenotype_parameter_ontology_annotation ppoa ON ppoa.id = pploa.annotation_id " + " INNER JOIN ontology_term ot ON ot.acc = ppoa.ontology_acc " + " WHERE ppoa.ontology_db_id=8 LIMIT 10000"; try (PreparedStatement p = komp2DbConnection.prepareStatement(sqlQuery)) { <START> System.out.println("PipelineIndexer: sql= " + sqlQuery); <END> ResultSet resultSet = p.executeQuery(); while (resultSet.next()) { String parameterId = resultSet.getString("stable_id"); paramIdToParameter.get(parameterId).setMaId(resultSet.getString("ontology_acc")); paramIdToParameter.get(parameterId).setMaName(resultSet.getString("name")); } } catch (Exception e) { e.printStackTrace(); } }</code><technical_language>remove sysout</technical_language>

Target:
protected void addAbnormalMaOntology(){ String sqlQuery="SELECT pp.id as id, ot.name as name, stable_id, ontology_acc FROM phenotype_parameter pp " + " INNER JOIN phenotype_parameter_lnk_ontology_annotation pploa ON pp.id = pploa.parameter_id " + " INNER JOIN phenotype_parameter_ontology_annotation ppoa ON ppoa.id = pploa.annotation_id " + " INNER JOIN ontology_term ot ON ot.acc = ppoa.ontology_acc " + " WHERE ppoa.ontology_db_id=8 LIMIT 10000"; try (PreparedStatement p = komp2DbConnection.prepareStatement(sqlQuery)) { ResultSet resultSet = p.executeQuery(); while (resultSet.next()) { String parameterId = resultSet.getString("stable_id"); paramIdToParameter.get(parameterId).setMaId(resultSet.getString("ontology_acc")); paramIdToParameter.get(parameterId).setMaName(resultSet.getString("name")); } } catch (Exception e) { e.printStackTrace(); } }
Source:
<code>public void stopModuleSkipRefresh(Module module, ServletContext servletContext) { try { Method stopModule = WebModuleUtil.class.getDeclaredMethod("stopModule", Module.class, ServletContext.class, Boolean.TYPE); stopModule.setAccessible(true); stopModule.invoke(null, module, servletContext, true); } catch (NoSuchMethodException e) { <START> throw new RuntimeException(); <END> } catch (InvocationTargetException e) { throw new RuntimeException(); } catch (IllegalAccessException e) { throw new RuntimeException(); } }</code><technical_language>exceptions some sort of message happened, instead of eating original message</technical_language>

Target:
public void stopModuleSkipRefresh(Module module, ServletContext servletContext) { ModuleFactory.stopModule(module); try { Method stopModule = WebModuleUtil.class.getDeclaredMethod("stopModule", Module.class, ServletContext.class, Boolean.TYPE); stopModule.setAccessible(true); stopModule.invoke(null, module, servletContext, true); } catch (NoSuchMethodException e) { throw new RuntimeException(STOP_MODULE_SKIP_REFRESH_EXCEPTION_MESSAGE, e); } catch (InvocationTargetException e) { throw new RuntimeException(STOP_MODULE_SKIP_REFRESH_EXCEPTION_MESSAGE, e); } catch (IllegalAccessException e) { throw new RuntimeException(STOP_MODULE_SKIP_REFRESH_EXCEPTION_MESSAGE, e); } }
Source:
<code>public boolean isFieldPresent(String fieldName, String documentType) { if (documentType == null) { documentType = ""; } for (int i = 0; i < inputs.length; i++) { DCInput field = inputs[i]; String fullName = field.getElement() + "." + <START> field.getQualifier(); <END> if (fullName.equals(fieldName) ) { if (field.isAllowedFor(documentType)) { return true; } } } return false; }</code><technical_language>Again, I add field. getSchema(). DRY, add this a new method DCInput class, e.g. field.getFullName()</technical_language>

Target:
public boolean isFieldPresent(String fieldName, String documentType) { if (documentType == null) { documentType = ""; } for (int i = 0; i < inputs.length; i++) { DCInput field = inputs[i]; String fullName = field.getFieldName(); if (fullName.equals(fieldName) ) { if (field.isAllowedFor(documentType)) { return true; } } } return false; }
Source:
<code>private CoreModule() { addDeserializer(String.class, new StdScalarDeserializer<String>(String.class) { private static final long serialVersionUID = 6977627268309308664L; @Override public String deserialize(final JsonParser jp, final DeserializationContext ctx) throws IOException { <START> return StringUtils.trim(jp.getValueAsString()); <END> } }); }</code><technical_language>Idea: goal afaik is trim string deserialized in JSON context, call trim(super.deserialize(jp, ctx)); in case this super.deserialize evolves in lib</technical_language>

Target:
private CoreModule() { addDeserializer(String.class, new StdScalarDeserializer<String>(String.class) { private static final long serialVersionUID = 6977627268309308664L; private final StringDeserializer STRING_DESERIALIZER = new StringDeserializer(); @Override public String deserialize(final JsonParser jp, final DeserializationContext ctx) throws IOException { return StringUtils.trim(STRING_DESERIALIZER.deserialize(jp, ctx)); } }); }
Source:
<code>protected GsonBuilder createGsonBuilder() { final GsonBuilder g = super.createGsonBuilder(); <START> g.registerTypeAdapter(com.google.gerrit.prettify.common.BaseEdit.class, <END> new com.google.gerrit.prettify.common.EditDeserializer()); return g; }</code><technical_language>LineEdit</technical_language>

Target:
protected GsonBuilder createGsonBuilder() { final GsonBuilder g = super.createGsonBuilder(); g.registerTypeAdapter(com.google.gerrit.prettify.common.LineEdit.class, new com.google.gerrit.prettify.common.EditDeserializer()); return g; }
Source:
<code>public static AggregateFunction get(String functionName) { if (functionName.equals("COUNT")) { return new CountAggregateFunction(); } else if (functionName.equals("AVG")) { return new AverageAggregateFunction(); } else if (functionName.equals("SUM")) { return new SumAggregateFunction(); } else if (functionName.equals("MAX")) { return new MaxAggregateFunction(); } else if (functionName.equals("MIN")) { <START> return new MinAggregateFunction(); <END> } else { return null; } }</code><technical_language>I guess nicer return single instances FunctionType.MIN, FunctionType.COUNT etc..</technical_language>

Target:
public static AggregateFunction get(String functionName) { if (functionName.equals("COUNT")) { return FunctionType.COUNT; } else if (functionName.equals("AVG")) { return FunctionType.AVG; } else if (functionName.equals("SUM")) { return FunctionType.SUM; } else if (functionName.equals("MAX")) { return FunctionType.MAX; } else if (functionName.equals("MIN")) { return FunctionType.MIN; } else { return null; } }
Source:
<code>public void testArray_385750() throws Exception { AssertionHelper a = getCPPAssertionHelper(); a.assertReadWriteFlags("int* a = new int[10]", "a", WRITE); <START> a.assertReadWriteFlags("*a = 5", "a", WRITE); <END> a.assertReadWriteFlags("a[1] = 1", "a", WRITE); a.assertReadWriteFlags("++a[1]", "a", READ | WRITE); a.assertReadWriteFlags("a[1]--", "a", READ | WRITE); a.assertReadWriteFlags("a[1] += 1", "a", READ | WRITE); a.assertReadWriteFlags("&(a[1]) = 1", "a", WRITE); a.assertReadWriteFlags("b = a[0]", "a", READ); a.assertReadWriteFlags("b += a[0]", "a", READ); a.assertReadWriteFlags("c[1][2] = 1", "c", WRITE); a.assertReadWriteFlags("c[1][2]++", "c", READ | WRITE); a.assertReadWriteFlags("d[1][2][3] = 1", "d", WRITE); }</code><technical_language>is wrong return WRITE in this case "a" change. Returning WRITE affect Extract Function refactoring forcing "a" output parameter a return value. Treating array expressions differently sense for variable declared arrays pointers, problem is for int x[4]; is int* const x;</technical_language>

Target:
public void testArray_385750() throws Exception { AssertionHelper a = getCPPAssertionHelper(); a.assertReadWriteFlags("int* a = new int[10]", "a", WRITE); a.assertReadWriteFlags("a[1] = 1", "a", WRITE); a.assertReadWriteFlags("++a[1]", "a", READ | WRITE); a.assertReadWriteFlags("a[1]--", "a", READ | WRITE); a.assertReadWriteFlags("a[1] += 1", "a", READ | WRITE); a.assertReadWriteFlags("b = a[0]", "a", READ); a.assertReadWriteFlags("b = *a", "a", READ); a.assertReadWriteFlags("b += a[0]", "a", READ); a.assertReadWriteFlags("c[1][2] = 1", "c", WRITE); a.assertReadWriteFlags("*c[1][2] = 1", "c", WRITE); a.assertReadWriteFlags("c[1][2]++", "c", READ | WRITE); a.assertReadWriteFlags("d[1][2][3] = 1", "d", WRITE); }
Source:
<code><START> missingFailureHandler(Class<?> cls, Class<? extends Message> failureClass) { <END> final String msg = format( "Missing failure handler for failure class %s in the class %s", failureClass, cls ); return new IllegalStateException(msg); }</code><technical_language>I think, transfer a method parameters a name a previous position</technical_language>

Target:
private static IllegalStateException missingFailureHandler( Class<?> cls, Class<? extends Message> failureClass) { final String msg = format( "Missing failure handler for failure class %s in the class %s", failureClass, cls ); return new IllegalStateException(msg); }
Source:
<code>public void verifyTableSize(int width, int height) { waitForElementByElement(tables.get(tables.size()-1)); int chromeWidth = width - 1; int chromeHeight = height - 1; <START> Assertion.assertTrue( <END> tables.get(tables.size()-1).getCssValue("width").equals(Integer.toString(width) + "px") || tables.get(tables.size()-1).getCssValue("width").equals(Integer.toString(chromeWidth) + "px") ); Assertion.assertTrue( tables.get(tables.size()-1).getCssValue("height").equals(Integer.toString(height) + "px") || tables.get(tables.size()-1).getCssValue("height").equals(Integer.toString(chromeHeight) + "px") ); PageObjectLogging.log("verifyTableSize", "table has correct size", true); }</code><technical_language>Assertion.stringContains() append "px"</technical_language>

Target:
public void verifyTableSize(int width, int height) { waitForElementByElement(table); Dimension size = table.getSize(); Assertion.assertEquals(size.getHeight(), height); Assertion.assertEquals(size.getWidth(), width); PageObjectLogging.log("verifyTableSize", "table has correct size", true); }
Source:
<code>protected Control createCustomArea(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(2, false)); composite.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL)); checkButton = new Button(composite, SWT.CHECK); <START> checkButton.setText(checkBoxMessage); <END> checkButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { checked = checkButton.getSelection(); } }); return composite; }</code><technical_language>want change this checkButton.setText(Strings.isValid(checkBoxMessage) ? checkBoxMessage : "<NONE>");</technical_language>

Target:
protected Control createCustomArea(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(2, false)); composite.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL)); checkButton = new Button(composite, SWT.CHECK); checkButton.setText(Strings.isValid(checkBoxMessage) ? checkBoxMessage : "<NONE>"); checkButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { checked = checkButton.getSelection(); } }); return composite; }
Source:
<code>public void install() { DownloadResolver resolver = Entities.newDownloader(this); List<String> urls = resolver.getTargets(); String saveAs = resolver.getFilename(); List<String> commands = ImmutableList.<String>builder() .addAll(BashCommands.commandsToDownloadUrlsAs(urls, saveAs)) <START> .add(BashCommands.installJavaLatestOrFail()) <END> .add(String.format("tar zxvf %s", saveAs)) .build(); newScript(INSTALLING).body.append(commands).execute(); setExpandedInstallDir(getInstallDir() + "/" + resolver.getUnpackedDirectoryName(format("elasticsearch-%s", getVersion()))); }</code><technical_language>more logical swap order of lines (install java, download tarball, unpack tarball)</technical_language>

Target:
public void install() { DownloadResolver resolver = Entities.newDownloader(this); List<String> urls = resolver.getTargets(); String saveAs = resolver.getFilename(); List<String> commands = ImmutableList.<String>builder() .add(BashCommands.installJavaLatestOrFail()) .addAll(BashCommands.commandsToDownloadUrlsAs(urls, saveAs)) .add(String.format("tar zxvf %s", saveAs)) .build(); newScript(INSTALLING).body.append(commands).execute(); setExpandedInstallDir(getInstallDir() + "/" + resolver.getUnpackedDirectoryName(format("elasticsearch-%s", getVersion()))); }
Source:
<code>public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_search_compilations: <START> getBaseActivity().startSupportActionMode(searchActionModeCallback); <END> return true; default: return super.onOptionsItemSelected(item); } }</code><technical_language>this a plain getActivity() call? reason need a BaseActivity for startSupportActionMode</technical_language>

Target:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_search_compilations: ((AppCompatActivity) getActivity()).startSupportActionMode(searchActionModeCallback); return true; default: return super.onOptionsItemSelected(item); } }
Source:
<code>public void setRetentionPolicy(RetentionPolicyType policyType, Object... params) { assert(m_retentionPolicy == null); <START> switch(policyType) { <END> case TIME_MS: m_retentionPolicy = RetentionPolicyMgr.getInstance().addTimeBasedRetentionPolicy(this, params); break; case MAX_BYTES: m_retentionPolicy = RetentionPolicyMgr.getInstance().addMaxBytesRetentionPolicy(this, params); break; } }</code><technical_language>I feel this switch statement part of RetentionPolicyMgr</technical_language>

Target:
public void setRetentionPolicy(RetentionPolicyType policyType, Object... params) { assert(m_retentionPolicy == null); m_retentionPolicy = RetentionPolicyMgr.getInstance().addRetentionPolicy(policyType, this, params); }
Source:
<code><START> public void shouldNeverConsiderCompletelyParsed() { <END> Source source = null; SpiderHtmlFormParser htmlParser = createSpiderHtmlFormParser(); HttpMessage messageHtmlResponse = createMessageWith("NoForms.html"); boolean completelyParsed = htmlParser.parseResource(messageHtmlResponse, source, BASE_DEPTH); assertThat(completelyParsed, is(equalTo(false))); }</code><technical_language>shouldNeverConsiderCompletelyParsedWhenSourceNull? this considered fully parsed</technical_language>

Target:
public void shouldNeverConsiderCompletelyParsed() { SpiderHtmlFormParser htmlParser = createSpiderHtmlFormParser(); HttpMessage messageHtmlResponse = createMessageWith("NoForms.html"); Source source = createSource(messageHtmlResponse); boolean completelyParsed = htmlParser.parseResource(messageHtmlResponse, source, BASE_DEPTH); assertThat(completelyParsed, is(equalTo(false))); }
Source:
<code>public void stop() throws LifecycleException { try { target.stop(); <START> } catch (LifecycleException ex) { <END> throw(ex); } }</code><technical_language>Catching Exception rethrowing as-is is equivalent catching all. implementation of this method target.stop();, exception management (much simpler!)</technical_language>

Target:
public void stop() throws LifecycleException { target.stop(); }
Source:
<code>public void onTimer(MessageCollector collector, TaskCoordinator coordinator) { KeyValueStore<K, PartialJoinMessage<M>> thisState = thisPartialJoinFn.getState(); KeyValueIterator<K, PartialJoinMessage<M>> iterator = thisState.all(); List<K> keysToRemove = new ArrayList<>(); long now = System.currentTimeMillis(); while (iterator.hasNext()) { Entry<K, PartialJoinMessage<M>> entry = iterator.next(); if (entry.getValue().getTimestamp() < now - ttlMs) { <START> keysToRemove.add(entry.getKey()); <END> } else { break; } } thisState.deleteAll(keysToRemove); this.propagateTimer(collector, coordinator); }</code><technical_language>Instead of adding keys a separate list iterating list (using deleteAll), I if efficient invoke remove() iterator right away? AFAIK, safe modify map iterator</technical_language>

Target:
public void onTimer(MessageCollector collector, TaskCoordinator coordinator) { long now = System.currentTimeMillis(); KeyValueStore<K, PartialJoinMessage<M>> thisState = thisPartialJoinFn.getState(); KeyValueIterator<K, PartialJoinMessage<M>> iterator = thisState.all(); List<K> keysToRemove = new ArrayList<>(); while (iterator.hasNext()) { Entry<K, PartialJoinMessage<M>> entry = iterator.next(); if (entry.getValue().getReceivedTimeMs() < now - ttlMs) { keysToRemove.add(entry.getKey()); } else { break; } } iterator.close(); thisState.deleteAll(keysToRemove); LOGGER.info("Operator ID onTimer self time: ms", opId, System.currentTimeMillis() - now); this.propagateTimer(collector, coordinator); }
Source:
<code>public void sync(byte[] bytes) { if (dynamicConfigurationPassiveSync != null) { Set<Require> requires; try { requires = dynamicConfigurationPassiveSync.sync(DynamicConfigSyncData.decode(bytes)); } catch (NomadException n) { throw new RuntimeException(n); } catch (RuntimeException e) { throw e; } <START> if (requires.contains(RESTART_REQUIRED)) { <END> if (requires.contains(ZAP_REQUIRED)) { ServerEnv.getServer().warn("Zapping server"); ServerEnv.getServer().stop(StopAction.ZAP, StopAction.RESTART); } else { ServerEnv.getServer().stop(StopAction.RESTART); } } warnIfPreparedChange(); } }</code><technical_language>is difference this warn a logger</technical_language>

Target:
public void sync(byte[] bytes) { if (dynamicConfigurationPassiveSync != null) { Set<Require> requires; try { requires = dynamicConfigurationPassiveSync.sync(DynamicConfigSyncData.decode(bytes)); } catch (NomadException n) { throw new RuntimeException(n); } if (requires.contains(RESTART_REQUIRED)) { if (requires.contains(ZAP_REQUIRED)) { ServerEnv.getServer().warn("Zapping server"); ServerEnv.getServer().stop(StopAction.ZAP, StopAction.RESTART); } else { ServerEnv.getServer().stop(StopAction.RESTART); } } warnIfPreparedChange(); } }
Source:
<code>public List<Cohort> getCohortsContainingPatientId(Integer patientId, Boolean voided) throws DAOException { Disjunction orDisjunction = Restrictions.disjunction(); orDisjunction.add(Restrictions.isNull("m.endDate")); orDisjunction.add(Restrictions.gt("m.endDate", new Date())); return (List<Cohort>) sessionFactory.getCurrentSession().createCriteria(Cohort.class) .add(Restrictions.eq("voided", voided)) .createAlias("members", "m") .add(Restrictions.le("m.startDate", new Date())) .add(orDisjunction) .createAlias("m.patient", "p") <START> .add(Restrictions.eq("p.patientId", patientId)) <END> .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY) .list(); }</code><technical_language>need this restriction createAlias calls, I restriction in place of 2 lines this: Restrictions.eq("m.patient", new Patient(1)) Alternatively load patient patientId loaded patient object in place of of new Patient(1)</technical_language>

Target:
public List<Cohort> getCohortsContainingPatientId(Integer patientId, Boolean voided) throws DAOException { Disjunction orDisjunction = Restrictions.disjunction(); orDisjunction.add(Restrictions.isNull("m.endDate")); orDisjunction.add(Restrictions.gt("m.endDate", new Date())); Patient p = new Patient(patientId); return (List<Cohort>) sessionFactory.getCurrentSession().createCriteria(Cohort.class) .add(Restrictions.eq("voided", voided)) .createAlias("members", "m") .add(Restrictions.le("m.startDate", new Date())) .add(orDisjunction) .add(Restrictions.eq("m.patient", p)) .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY) .list(); }
Source:
<code>void analyzeFiles(List<InputFile> inputFiles) throws IOException { List<String> tsConfigs = tsConfigs(); <START> splitAnalysisByTsConfig(inputFiles, tsConfigs); <END> }</code><technical_language>analyzeFilesWithTsConfigs need list of tsconfigs. I inline splitAnalysisByTsConfig</technical_language>

Target:
void analyzeFiles(List<InputFile> inputFiles) throws IOException { List<String> tsConfigs = tsConfigs(); Map<TsConfigFile, List<InputFile>> filesByTsConfig = TsConfigFile.inputFilesByTsConfig(loadTsConfigs(tsConfigs), inputFiles); for (Map.Entry<TsConfigFile, List<InputFile>> entry : filesByTsConfig.entrySet()) { TsConfigFile tsConfigFile = entry.getKey(); List<InputFile> files = entry.getValue(); if (TsConfigFile.UNMATCHED_CONFIG.equals(tsConfigFile)) { LOG.info("Skipping files with no tsconfig.json", files.size()); LOG.debug("Skipped files: " + files.stream().map(InputFile::toString).collect(Collectors.joining("\n"))); continue; } LOG.info("Analyzing files using tsconfig: {}", files.size(), tsConfigFile); analyzeFilesWithTsConfig(files, tsConfigFile); eslintBridgeServer.newTsConfig(); } }
Source:
<code>public void applyEffect(NBTTagCompound rootCompound, NBTTagCompound modifierTag) { ModifierNBT.IntegerNBT data = ModifierNBT.readInteger(modifierTag); boolean harvest = false; for(Category category : TagUtil.getCategories(rootCompound)) { if(category == Category.HARVEST) harvest = true; } ToolNBT toolData = TagUtil.getOriginalToolStats(rootCompound); NBTTagCompound tag = TagUtil.getToolTag(rootCompound); int level = data.current / max; if(harvest) { float speed = toolData.speed; for(int count = data.current; count > 0; count--) { if(speed <= 10f) { speed += 0.15f - 0.05f * speed / 10f; } else if(speed <= 20f) { speed += 0.1f - 0.05 * speed / 20f; } else { speed += 0.05; } } speed += level * 0.5f; speed -= toolData.speed; speed += tag.getFloat(Tags.MININGSPEED); tag.setFloat(Tags.MININGSPEED, speed); } <START> float attackSpeed = 1.0f + (level * 0.2f); <END> attackSpeed -= toolData.attackSpeed; attackSpeed += tag.getFloat(Tags.ATTACKSPEED); tag.setFloat(Tags.ATTACKSPEED, attackSpeed); }</code><technical_language>Change apply a speed buff redstone applied, level. linear: attackspeed = 1 + (0.2 \* current / max)</technical_language>

Target:
public void applyEffect(NBTTagCompound rootCompound, NBTTagCompound modifierTag) { ModifierNBT.IntegerNBT modData = ModifierNBT.readInteger(modifierTag); boolean harvest = false; for(Category category : TagUtil.getCategories(rootCompound)) { if(category == Category.HARVEST) harvest = true; } ToolNBT data = TagUtil.getToolStats(rootCompound); int level = modData.current / max; if(harvest) { float speed = data.speed; for(int count = modData.current; count > 0; count--) { if(speed <= 10f) { speed += 0.15f - 0.05f * speed / 10f; } else if(speed <= 20f) { speed += 0.1f - 0.05 * speed / 20f; } else { speed += 0.05; } } speed += level * 0.5f; data.speed = speed; } data.attackSpeedMultiplier += (0.2f * modData.current / max); TagUtil.setToolTag(rootCompound, data.get()); }
Source:
<code>protected Function1D<Double, Double> generate(BasisFunctionKnots data, final int index) { ArgumentChecker.notNull(data, "data"); <START> ArgumentChecker.isTrue(index >= 0 && index < data.getNumSplines(), "index must be in range {] to (exclusive)", 0, data.getNumSplines()); <END> return generate(data.getKnots(), data.getDegree(), index); }</code><technical_language>Change "index in range {].." "index in range {}" for correct printing</technical_language>

Target:
protected Function1D<Double, Double> generate(BasisFunctionKnots data, final int index) { ArgumentChecker.notNull(data, "data"); ArgumentChecker.isTrue(index >= 0 && index < data.getNumSplines(), "index must be in range to (exclusive)", 0, data.getNumSplines()); return generate(data.getKnots(), data.getDegree(), index); }
Source:
<code>protected void logAPICall(final String transactionType, final Account account, final UUID paymentMethodId, @Nullable final UUID paymentId, @Nullable final UUID transactionId, @Nullable final BigDecimal amount, @Nullable final Currency currency, @Nullable final String paymentExternalKey, @Nullable final String paymentTransactionExternalKey) { if (log.isInfoEnabled()) { final StringBuilder logLine = new StringBuilder(); logLine.append("PaymentApi : ") .append(transactionType) .append(", account = ") .append(account.getId()); if (paymentMethodId != null) { logLine.append(", paymentMethodId = ") .append(paymentMethodId); } if (paymentExternalKey != null) { logLine.append(", paymentExternalKey = ") .append(paymentExternalKey); } if (paymentTransactionExternalKey != null) { logLine.append(", paymentTransactionExternalKey = ") .append(paymentTransactionExternalKey); } if (paymentId != null) { logLine.append(", paymentId = ") .append(paymentId); } if (transactionId != null) { logLine.append(", transactionId = ") .append(transactionId); } if (amount != null) { logLine.append(", amount = ") .append(amount); } if (currency != null) { logLine.append(", currency = ") .append(currency); } <START> final String requestId = Request.getPerThreadRequestData() != null <END> ? Request.getPerThreadRequestData().getRequestId() : null; if (requestId != null) { logLine.append(", requestId = ") .append(requestId); } log.info(logLine.toString()); } }</code><technical_language>get rid of requestId logging (here below). opened <LINK_0> for tracking (we user token instead, bus events notifications)</technical_language>

Target:
protected void logAPICall(final String transactionType, final Account account, final UUID paymentMethodId, @Nullable final UUID paymentId, @Nullable final UUID transactionId, @Nullable final BigDecimal amount, @Nullable final Currency currency, @Nullable final String paymentExternalKey, @Nullable final String paymentTransactionExternalKey) { if (log.isInfoEnabled()) { final StringBuilder logLine = new StringBuilder(); logLine.append("PaymentApi : ") .append(transactionType) .append(", account = ") .append(account.getId()); if (paymentMethodId != null) { logLine.append(", paymentMethodId = ") .append(paymentMethodId); } if (paymentExternalKey != null) { logLine.append(", paymentExternalKey = ") .append(paymentExternalKey); } if (paymentTransactionExternalKey != null) { logLine.append(", paymentTransactionExternalKey = ") .append(paymentTransactionExternalKey); } if (paymentId != null) { logLine.append(", paymentId = ") .append(paymentId); } if (transactionId != null) { logLine.append(", transactionId = ") .append(transactionId); } if (amount != null) { logLine.append(", amount = ") .append(amount); } if (currency != null) { logLine.append(", currency = ") .append(currency); } log.info(logLine.toString()); } }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { MDC.put(REQUEST_ID, UUIDGenerator.generate()); String loginName = StringUtils.isNotEmpty(LoginUserInfo.getLoginName()) ? LoginUserInfo.getLoginName() : ANONYMOUS; MDC.put(USER_ID, loginName); <START> chain.doFilter(request, response); <END> }</code><technical_language>try finally</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { MDC.put(REQUEST_ID, UUIDGenerator.generate()); String loginName = StringUtils.isNotEmpty(LoginUserInfo.getLoginName()) ? LoginUserInfo.getLoginName() : ANONYMOUS; MDC.put(USER_ID, loginName); chain.doFilter(request, response); } finally { MDC.remove(REQUEST_ID); MDC.remove(USER_ID); } }
Source:
<code>private Address addNewAddressToAddressMap(int id, String host, int initialPort) { synchronized (addressMap) { while (true) { final Address newAddress = createAddress(host, initialPort++); if (!addressMap.containsValue(newAddress)) { addressMap.put(id, newAddress); return newAddress; } } <START> } <END> }</code><technical_language>re-write this method this handle out of port range issue: static final int MAX_PORT_NUMBER = (1 << 16) - 1; private Address addNewAddressToAddressMap(int id, String host, int initialPort) { while (true) { int newPort = initialPort++; if (newPort > MAX_PORT_NUMBER) { throw new IllegalArgumentException("Port number is out of range: " + newPort); } Address newAddress = newAddressOrNull(host, newPort); if (newAddress != null) { synchronized (addressMap) { if (!addressMap.containsValue(newAddress)) { addressMap.put(id, newAddress); return newAddress; } } } } }</technical_language>

Target:
private Address addNewAddressToAddressMap(int id, String host, int initialPort) { synchronized (addressMap) { while (true) { int newPort = initialPort++; if (newPort > MAX_PORT_NUMBER) { throw new IllegalArgumentException( "Exhausted available port range. Try lowering the initial port in " + getClass().getSimpleName() + ": " + newPort); } final Address newAddress = createAddressOrNull(host, newPort); if (!addressMap.containsValue(newAddress)) { addressMap.put(id, newAddress); return newAddress; } } } }